/v3.2/nimbits-sdk/src/com/nimbits/client/NimbitsClientImpl.java

http://nimbits-server.googlecode.com/ · Java · 667 lines · 431 code · 189 blank · 47 comment · 54 complexity · e3c79bfcb2767bffa5e53541ce5f1d58 MD5 · raw file

  1. package com.nimbits.client;
  2. import com.google.gson.Gson;
  3. import com.nimbits.client.exception.NimbitsRuntimeException;
  4. import com.nimbits.client.model.Const;
  5. import com.nimbits.client.model.category.Category;
  6. import com.nimbits.client.model.category.CategoryName;
  7. import com.nimbits.client.model.category.impl.PointCategoryModelImpl;
  8. import com.nimbits.client.model.diagram.Diagram;
  9. import com.nimbits.client.model.email.EmailAddress;
  10. import com.nimbits.client.model.point.Point;
  11. import com.nimbits.client.model.point.PointModel;
  12. import com.nimbits.client.model.point.PointName;
  13. import com.nimbits.client.model.user.User;
  14. import com.nimbits.client.model.value.Value;
  15. import com.nimbits.client.model.value.ValueModel;
  16. import com.nimbits.client.model.value.ValueModelFactory;
  17. import com.nimbits.gson.GsonFactory;
  18. import com.nimbits.user.GoogleAuthentication;
  19. import com.nimbits.user.GoogleUser;
  20. import com.nimbits.user.NimbitsUser;
  21. import org.apache.http.cookie.Cookie;
  22. import java.io.*;
  23. import java.net.HttpURLConnection;
  24. import java.net.MalformedURLException;
  25. import java.net.URL;
  26. import java.net.URLEncoder;
  27. import java.util.ArrayList;
  28. import java.util.Date;
  29. import java.util.List;
  30. public class NimbitsClientImpl implements NimbitsClient {
  31. final private static Gson gson = GsonFactory.getInstance();
  32. private final GoogleAuthentication G;
  33. private final String host;
  34. private Cookie authCookie;
  35. // private NimbitsClientImpl() {
  36. // }
  37. public NimbitsClientImpl(final NimbitsUser n, final String hostUrl) {
  38. this.host = hostUrl;
  39. G = GoogleAuthentication.getNewGoogleAuthentication();
  40. G.setEmail(n.getEmailAddress());
  41. G.setSecret(n.getNimbitsSecretKey());
  42. }
  43. public NimbitsClientImpl(final GoogleUser g, final String hostUrl) throws Exception {
  44. this.host = hostUrl;
  45. G = GoogleAuthentication.getNewGoogleAuthentication();
  46. G.setEmail(g.getGoogleEmailAddress());
  47. G.Connect(hostUrl, g.getGoogleEmailAddress(), g.getGooglePassword());
  48. }
  49. public String getHost() {
  50. return host;
  51. }
  52. public NimbitsClientImpl(final String token, final EmailAddress email, final String hostUrl) throws Exception {
  53. this.host = hostUrl;
  54. G = GoogleAuthentication.getNewGoogleAuthentication();
  55. G.setEmail(email);
  56. authCookie = G.ConnectAuth(token, hostUrl);
  57. }
  58. public Cookie getAuthCookie() {
  59. return authCookie;
  60. }
  61. public boolean isLoggedIn() {
  62. return Boolean.parseBoolean(doGet(host + Const.PATH_AUTHTEST_SERVICE, ""));
  63. }
  64. public List<User> getUsers() {
  65. String u = host + Const.PATH_USER_SERVICE;
  66. String params = "action=download";
  67. String result = doGet(u, params);
  68. return gson.fromJson(result, GsonFactory.userListType);
  69. }
  70. public String getChart(final String points, final int count) {
  71. final String u = host + Const.Path_CHART_API;
  72. String params = null;
  73. final String result;
  74. try {
  75. params = "count=10&points=" + URLEncoder.encode(points, Const.CONST_ENCODING) + "&chxt=y&chxp=1,75,100&cht=lc&chco=76A4FB&chls=2.0&chs=300x200";
  76. } catch (UnsupportedEncodingException e1) {
  77. e1.printStackTrace();
  78. }
  79. result = doGet(u, params);
  80. return result;
  81. }
  82. public String getChartURL(final String points, final int count, final String additionalParams) {
  83. final String u = host + Const.Path_CHART_API;
  84. String params = null;
  85. try {
  86. params = "count=10&points=" + URLEncoder.encode(points, Const.CONST_ENCODING) + "&" + additionalParams;
  87. } catch (UnsupportedEncodingException e1) {
  88. e1.printStackTrace();
  89. }
  90. return u + "?" + params;
  91. }
  92. public void deletePoint(final PointName pointName) {
  93. final String u = host + Const.PATH_POINT_SERVICE;
  94. try {
  95. String params = "point=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING) + "&action=delete";
  96. doPost(u, params);
  97. } catch (UnsupportedEncodingException ignored) {
  98. }
  99. }
  100. public Value recordValue(final PointName pointName,
  101. final double value,
  102. final Date timestamp) throws IOException {
  103. String u = host + Const.PATH_CURRENT_VALUE;
  104. String params = "point=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING) + "&timestamp=" + timestamp.getTime() + "&value=" + value;
  105. String json = doPost(u, params);
  106. return gson.fromJson(json, ValueModel.class);
  107. }
  108. public Value recordValueWithGet(final PointName pointName, final double value, final Date timestamp) throws IOException {
  109. final String u = host + Const.PATH_CURRENT_VALUE;
  110. String params = "point=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING) +
  111. "&timestamp=" + timestamp.getTime() +
  112. "&value=" + value;
  113. String json = doGet(u, params);
  114. System.out.println(json);
  115. double d = Double.valueOf(json);
  116. return ValueModelFactory.createValueModel(d);
  117. //return gson.fromJson(json, ValueModel.class);
  118. }
  119. public String recordBatch(String params) {
  120. String u = host + Const.PATH_BATCH_SERVICE;
  121. return doPost(u, params);
  122. }
  123. public Value recordValue(PointName pointName, Value v) throws IOException {
  124. String u = host + Const.PATH_CURRENT_VALUE;
  125. String json = gson.toJson(v, ValueModel.class);
  126. String params = Const.PARAM_TIMESTAMP +
  127. "=" + v.getTimestamp().getTime() +
  128. "&" + Const.PARAM_POINT + "=" +
  129. URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING) +
  130. "&" + Const.PARAM_JSON + "=" + URLEncoder.encode(json, Const.CONST_ENCODING);
  131. String result = doPost(u, params);
  132. return gson.fromJson(result, ValueModel.class);
  133. }
  134. /**
  135. * Add a new Category
  136. *
  137. * @param categoryName the name of the new category
  138. * @throws UnsupportedEncodingException
  139. */
  140. public Category addCategory(final CategoryName categoryName) throws UnsupportedEncodingException {
  141. final String u = host + Const.PATH_CATEGORY_SERVICE;
  142. final String params = "name=" + URLEncoder.encode(categoryName.getValue(), Const.CONST_ENCODING);
  143. final String result = doPost(u, params);
  144. return gson.fromJson(result, PointCategoryModelImpl.class);
  145. }
  146. public String deleteCategory(final CategoryName categoryName) {
  147. String retVal = "";
  148. try {
  149. String u = host + Const.PATH_CATEGORY_SERVICE;
  150. String params;
  151. params = "action=delete&name=" + URLEncoder.encode(categoryName.getValue(), Const.CONST_ENCODING);
  152. retVal = doPost(u, params);
  153. } catch (UnsupportedEncodingException ignored) {
  154. }
  155. return retVal;
  156. }
  157. public Point addPoint(final CategoryName categoryName, final PointName pointName) {
  158. Point point = null;
  159. try {
  160. final String u = host + Const.PATH_POINT_SERVICE;
  161. final String params = Const.PARAM_NAME + "=" +
  162. URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING) +
  163. "&" + Const.PARAM_CATEGORY + "=" + URLEncoder.encode(categoryName.getValue(), Const.CONST_ENCODING);
  164. String json = doPost(u, params);
  165. point = gson.fromJson(json, PointModel.class);
  166. } catch (UnsupportedEncodingException ignored) {
  167. }
  168. return point;
  169. }
  170. public Point getPoint(final PointName pointName) {
  171. Point retObj = null;
  172. try {
  173. final String u = host + Const.PATH_POINT_SERVICE;
  174. final String params = Const.PARAM_NAME + "=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING);
  175. String json = doGet(u, params);
  176. retObj = gson.fromJson(json, PointModel.class);
  177. } catch (UnsupportedEncodingException ignored) {
  178. } catch (IOException ignored) {
  179. }
  180. return retObj;
  181. }
  182. @Override
  183. public Point updatePoint(final Point p) {
  184. Point ret = null;
  185. try {
  186. String u = host + Const.PATH_POINT_SERVICE;
  187. String params;
  188. String json = gson.toJson(p);
  189. params = Const.PARAM_JSON + "=" + URLEncoder.encode(json, Const.CONST_ENCODING) +
  190. "&" + Const.PARAM_ACTION + "=" + Const.ACTION_UPDATE;
  191. String response = doPost(u, params);
  192. if (response != null) {
  193. ret = gson.fromJson(response, PointModel.class);
  194. }
  195. } catch (UnsupportedEncodingException e) {
  196. e.printStackTrace();
  197. }
  198. return ret;
  199. }
  200. public Point addPoint(final Point p, final CategoryName categoryName) {
  201. Point retObj = null;
  202. final String newPointJson = gson.toJson(p);
  203. try {
  204. String u = host + Const.PATH_POINT_SERVICE;
  205. String params;
  206. params = Const.PARAM_JSON + "=" + URLEncoder.encode(newPointJson, Const.CONST_ENCODING);
  207. params += "&" + Const.PARAM_CATEGORY + "=" +
  208. URLEncoder.encode(categoryName.getValue(), Const.CONST_ENCODING);
  209. String result = doPost(u, params);
  210. retObj = gson.fromJson(result, PointModel.class);
  211. } catch (UnsupportedEncodingException e) {
  212. }
  213. return retObj;
  214. }
  215. public List<Category> getCategories(final boolean includePoints, final boolean includeDiagrams) {
  216. final String u = host + Const.PATH_CATEGORY_SERVICE;
  217. String params = "";
  218. if (includePoints) {
  219. params = Const.PARAM_INCLUDE_POINTS + "=" + Const.WORD_TRUE;
  220. }
  221. if (includeDiagrams) {
  222. params += "&" + Const.PARAM_INCLUDE_DIAGRAMS + "=" + Const.WORD_TRUE;
  223. }
  224. final String json = doGet(u, params);
  225. List<Category> retObj = null;
  226. if (!(json.trim().length() == 0)) {
  227. retObj = gson.fromJson(json, GsonFactory.categoryListType);
  228. for (Category c : retObj) {
  229. if (c.getJsonPointCollection() != null) {
  230. List<Point> points = gson.fromJson(c.getJsonPointCollection(), GsonFactory.pointListType);
  231. c.setPoints(points);
  232. }
  233. if (c.getJsonDiagramCollection() != null) {
  234. List<Diagram> diagrams = gson.fromJson(c.getJsonDiagramCollection(), GsonFactory.diagramListType);
  235. c.setDiagrams(diagrams);
  236. }
  237. }
  238. }
  239. return retObj;
  240. }
  241. public Category getCategory(final CategoryName categoryName, final boolean includePoints, final boolean includeDiagrams) {
  242. Category c = null;
  243. final String u = host + Const.PATH_CATEGORY_SERVICE;
  244. String params = Const.PARAM_NAME + "=" + categoryName.getValue();
  245. if (includePoints) {
  246. params += "&" + Const.PARAM_INCLUDE_POINTS + "=" + Const.WORD_TRUE;
  247. }
  248. if (includeDiagrams) {
  249. params += "&" + Const.PARAM_INCLUDE_DIAGRAMS + "=" + Const.WORD_TRUE;
  250. }
  251. final String json = doGet(u, params);
  252. if (!(json.trim().length() == 0)) {
  253. c = gson.fromJson(json, PointCategoryModelImpl.class);
  254. if (c.getJsonPointCollection() != null) {
  255. List<Point> points = gson.fromJson(c.getJsonPointCollection(), GsonFactory.categoryListType);
  256. c.setPoints(points);
  257. }
  258. if (c.getJsonDiagramCollection() != null) {
  259. List<Diagram> diagrams = gson.fromJson(c.getJsonDiagramCollection(), GsonFactory.diagramListType);
  260. c.setDiagrams(diagrams);
  261. }
  262. }
  263. return c;
  264. }
  265. public String currentValue(final PointName pointName) throws IOException {
  266. String u = host + Const.PATH_CURRENT_VALUE;
  267. String params = Const.PARAM_POINT + "=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING);
  268. return doGet(u, params);
  269. }
  270. public Object getCurrentDataObject(final PointName pointName, Class<?> cls) {
  271. Value value = getCurrentRecordedValue(pointName);
  272. if (value.getData() != null) {
  273. return gson.fromJson(value.getData(), cls);
  274. } else {
  275. return null;
  276. }
  277. }
  278. public Value getCurrentRecordedValue(final PointName pointName) {
  279. Value retObj = null;
  280. String u = host + Const.PATH_CURRENT_VALUE;
  281. String params;
  282. String json;
  283. try {
  284. params = Const.PARAM_POINT + "=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING) + "&format=json";
  285. json = doGet(u, params);
  286. if (json != null) {
  287. retObj = gson.fromJson(json, ValueModel.class);
  288. }
  289. } catch (Exception e) {
  290. e.printStackTrace();
  291. }
  292. return retObj;
  293. }
  294. public List<Value> getSeries(final PointName pointName, final int count) {
  295. List<Value> retObj = null;
  296. String result;
  297. final String destUrl = host + Const.PATH_SERIES_SERVICE;
  298. String params;
  299. try {
  300. params = Const.PARAM_COUNT + "=" + count + "&" + Const.PARAM_POINT + "=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING);
  301. result = doGet(destUrl, params);
  302. System.out.println(destUrl + "?" + params);
  303. System.out.println(result);
  304. retObj = gson.fromJson(result, GsonFactory.valueListType);
  305. } catch (UnsupportedEncodingException e) {
  306. e.printStackTrace();
  307. } catch (IOException e) {
  308. e.printStackTrace();
  309. }
  310. return retObj;
  311. }
  312. public List<Value> getSeries(final PointName pointName, final Date startDate, final Date endDate) {
  313. final List<Value> retObj = new ArrayList<Value>();
  314. String result;
  315. String destUrl = host + Const.PATH_SERIES_SERVICE;
  316. String params;
  317. int seg = 0;
  318. try {
  319. while (true) {
  320. params = "seg=" + seg + "&sd=" + startDate.getTime() + "&ed=" + endDate.getTime() + "&" + Const.PARAM_POINT + "=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING);
  321. result = doGet(destUrl, params);
  322. List<Value> r = gson.fromJson(result, GsonFactory.valueListType);
  323. if (r == null || r.size() == 0) {
  324. break;
  325. } else {
  326. retObj.addAll(r);
  327. }
  328. seg += 1000;
  329. }
  330. } catch (UnsupportedEncodingException e) {
  331. e.printStackTrace();
  332. } catch (IOException e) {
  333. e.printStackTrace();
  334. }
  335. return retObj;
  336. }
  337. @Override
  338. public void downloadSeries(final PointName pointName, final Date startDate, final Date endDate, final String filename) throws IOException {
  339. final List<Value> r = getSeries(pointName, startDate, endDate);
  340. String json = gson.toJson(r, GsonFactory.valueListType);
  341. Writer out;
  342. out = new OutputStreamWriter(new FileOutputStream(filename));
  343. out.write(json);
  344. out.close();
  345. }
  346. @Override
  347. public List<Value> loadSeriesFile(final String fileName) throws IOException {
  348. final StringBuilder sb = new StringBuilder();
  349. final BufferedReader in = new BufferedReader(new FileReader(fileName));
  350. String str;
  351. while ((str = in.readLine()) != null) {
  352. sb.append(str);
  353. }
  354. in.close();
  355. return gson.fromJson(sb.toString(), GsonFactory.valueListType);
  356. }
  357. private String doGet(final String postUrl, final String params) {
  358. final StringBuilder sb = new StringBuilder();
  359. try {
  360. final String paramsWithAuth = params + getAuthParams();
  361. final URL url = new URL(postUrl + "?" + paramsWithAuth);
  362. final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  363. connection.setDoOutput(true);
  364. connection.setRequestMethod(Const.METHOD_GET);
  365. if (G != null && G.getAuthCookie() != null) {
  366. connection.addRequestProperty("Cookie", G.getAuthCookie().getName() + "=" + G.getAuthCookie().getValue());
  367. }
  368. final BufferedReader reader = new BufferedReader(new InputStreamReader(
  369. connection.getInputStream()));
  370. String line;
  371. while ((line = reader.readLine()) != null) {
  372. sb.append(line);
  373. }
  374. reader.close();
  375. } catch (Exception e) {
  376. //throw e;
  377. }
  378. return sb.toString();
  379. }
  380. public byte[] getBinaryFile(final String postUrl, String params) throws IOException {
  381. int c;
  382. params += getAuthParams();
  383. final URL url = new URL(postUrl + "?" + params);
  384. final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  385. connection.setDoOutput(true);
  386. connection.setRequestMethod(Const.METHOD_GET);
  387. if (G != null && G.getAuthCookie() != null) {
  388. connection.addRequestProperty("Cookie", G.getAuthCookie().getName() + "=" + G.getAuthCookie().getValue());
  389. }
  390. final DataInputStream in = new DataInputStream(connection.getInputStream());
  391. final ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
  392. while ((c = in.read()) != -1) {
  393. byteArrayOut.write(c);
  394. }
  395. in.close();
  396. return byteArrayOut.toByteArray();
  397. }
  398. // public byte[] getBinaryFile(String postUrl, String params) throws Exception {
  399. // byte[] retObj;
  400. // int c;
  401. //
  402. // URL url = new URL(postUrl + "?" + params);
  403. // HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  404. // connection.setDoOutput(true);
  405. // connection.setRequestMethod("GET");
  406. //
  407. // if (G != null) {
  408. //
  409. // try {
  410. // if (G.getAuthCookie() != null) {
  411. // connection.addRequestProperty("Cookie", G.getAuthCookie().getValue() + "=" + G.getAuthCookie().getValue());
  412. // }
  413. //
  414. // } catch (Exception e) {
  415. //
  416. // }
  417. // params += getAuthParams();
  418. //
  419. // }
  420. //
  421. // DataInputStream in = new DataInputStream(connection.getInputStream());
  422. // ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
  423. //
  424. //
  425. // while ((c = in.read()) != -1) {
  426. // byteArrayOut.write(c);
  427. // }
  428. // retObj = byteArrayOut.toByteArray();
  429. //
  430. //
  431. // return retObj;
  432. //
  433. // }
  434. private String getAuthParams() {
  435. StringBuilder b = new StringBuilder();
  436. b.append("&" + Const.PARAM_EMAIL + "=");
  437. b.append(G.getEmail().getValue());
  438. if (G.getSecret() != null) {
  439. b.append("&" + Const.PARAM_SECRET + "=");
  440. b.append(G.getSecret());
  441. }
  442. return b.toString();
  443. }
  444. private String doPost(final String postUrl, final String params) {
  445. String retVal = "";
  446. String postParams = params;
  447. try {
  448. final URL url = new URL(postUrl);
  449. final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  450. connection.setDoOutput(true);
  451. connection.setRequestMethod(Const.METHOD_POST);
  452. connection.setReadTimeout(10000);
  453. if (G != null) {
  454. if (G.getAuthCookie() != null) {
  455. connection.addRequestProperty("Cookie", G.getAuthCookie().getName() + "=" + G.getAuthCookie().getValue());
  456. }
  457. postParams += getAuthParams();
  458. }
  459. // System.out.println(params);
  460. final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
  461. writer.write(postParams);
  462. writer.close();
  463. if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
  464. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  465. String line;
  466. while ((line = reader.readLine()) != null) {
  467. retVal += line;
  468. }
  469. reader.close();
  470. }
  471. } catch (MalformedURLException e) {
  472. throw new NimbitsRuntimeException(e);
  473. } catch (IOException e) {
  474. throw new NimbitsRuntimeException(e);
  475. }
  476. return retVal;
  477. }
  478. }