PageRenderTime 55ms CodeModel.GetById 16ms app.highlight 34ms RepoModel.GetById 1ms app.codeStats 0ms

/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
  1package com.nimbits.client;
  2
  3import com.google.gson.Gson;
  4import com.nimbits.client.exception.NimbitsRuntimeException;
  5import com.nimbits.client.model.Const;
  6import com.nimbits.client.model.category.Category;
  7import com.nimbits.client.model.category.CategoryName;
  8import com.nimbits.client.model.category.impl.PointCategoryModelImpl;
  9import com.nimbits.client.model.diagram.Diagram;
 10import com.nimbits.client.model.email.EmailAddress;
 11import com.nimbits.client.model.point.Point;
 12import com.nimbits.client.model.point.PointModel;
 13import com.nimbits.client.model.point.PointName;
 14import com.nimbits.client.model.user.User;
 15import com.nimbits.client.model.value.Value;
 16import com.nimbits.client.model.value.ValueModel;
 17import com.nimbits.client.model.value.ValueModelFactory;
 18import com.nimbits.gson.GsonFactory;
 19import com.nimbits.user.GoogleAuthentication;
 20import com.nimbits.user.GoogleUser;
 21import com.nimbits.user.NimbitsUser;
 22import org.apache.http.cookie.Cookie;
 23
 24import java.io.*;
 25import java.net.HttpURLConnection;
 26import java.net.MalformedURLException;
 27import java.net.URL;
 28import java.net.URLEncoder;
 29import java.util.ArrayList;
 30import java.util.Date;
 31import java.util.List;
 32
 33
 34public class NimbitsClientImpl implements NimbitsClient {
 35
 36    final private static Gson gson = GsonFactory.getInstance();
 37
 38    private final GoogleAuthentication G;
 39    private final String host;
 40    private Cookie authCookie;
 41
 42//    private NimbitsClientImpl() {
 43//    }
 44
 45    public NimbitsClientImpl(final NimbitsUser n, final String hostUrl) {
 46        this.host = hostUrl;
 47        G = GoogleAuthentication.getNewGoogleAuthentication();
 48        G.setEmail(n.getEmailAddress());
 49        G.setSecret(n.getNimbitsSecretKey());
 50    }
 51
 52    public NimbitsClientImpl(final GoogleUser g, final String hostUrl) throws Exception {
 53        this.host = hostUrl;
 54        G = GoogleAuthentication.getNewGoogleAuthentication();
 55        G.setEmail(g.getGoogleEmailAddress());
 56        G.Connect(hostUrl, g.getGoogleEmailAddress(), g.getGooglePassword());
 57
 58    }
 59
 60    public String getHost() {
 61        return host;
 62    }
 63
 64    public NimbitsClientImpl(final String token, final EmailAddress email, final String hostUrl) throws Exception {
 65        this.host = hostUrl;
 66        G = GoogleAuthentication.getNewGoogleAuthentication();
 67        G.setEmail(email);
 68        authCookie = G.ConnectAuth(token, hostUrl);
 69
 70
 71    }
 72
 73    public Cookie getAuthCookie() {
 74        return authCookie;
 75    }
 76
 77
 78    public boolean isLoggedIn() {
 79
 80        return Boolean.parseBoolean(doGet(host + Const.PATH_AUTHTEST_SERVICE, ""));
 81
 82    }
 83
 84    public List<User> getUsers() {
 85        String u = host + Const.PATH_USER_SERVICE;
 86        String params = "action=download";
 87        String result = doGet(u, params);
 88
 89        return gson.fromJson(result, GsonFactory.userListType);
 90
 91
 92    }
 93
 94    public String getChart(final String points, final int count) {
 95        final String u = host + Const.Path_CHART_API;
 96        String params = null;
 97        final String result;
 98        try {
 99            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";
100        } catch (UnsupportedEncodingException e1) {
101
102            e1.printStackTrace();
103        }
104
105
106        result = doGet(u, params);
107
108
109        return result;
110    }
111
112    public String getChartURL(final String points, final int count, final String additionalParams) {
113        final String u = host + Const.Path_CHART_API;
114        String params = null;
115
116        try {
117            params = "count=10&points=" + URLEncoder.encode(points, Const.CONST_ENCODING) + "&" + additionalParams;
118
119        } catch (UnsupportedEncodingException e1) {
120
121            e1.printStackTrace();
122        }
123
124
125        return u + "?" + params;
126    }
127
128    public void deletePoint(final PointName pointName) {
129        final String u = host + Const.PATH_POINT_SERVICE;
130        try {
131            String params = "point=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING) + "&action=delete";
132            doPost(u, params);
133        } catch (UnsupportedEncodingException ignored) {
134
135        }
136
137    }
138
139    public Value recordValue(final PointName pointName,
140                             final double value,
141                             final Date timestamp) throws IOException {
142        String u = host + Const.PATH_CURRENT_VALUE;
143        String params = "point=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING) + "&timestamp=" + timestamp.getTime() + "&value=" + value;
144        String json = doPost(u, params);
145        return gson.fromJson(json, ValueModel.class);
146    }
147
148    public Value recordValueWithGet(final PointName pointName, final double value, final Date timestamp) throws IOException {
149        final String u = host + Const.PATH_CURRENT_VALUE;
150        String params = "point=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING) +
151                "&timestamp=" + timestamp.getTime() +
152                "&value=" + value;
153
154        String json = doGet(u, params);
155        System.out.println(json);
156        double d = Double.valueOf(json);
157        return ValueModelFactory.createValueModel(d);
158
159        //return gson.fromJson(json, ValueModel.class);
160
161    }
162
163    public String recordBatch(String params) {
164        String u = host + Const.PATH_BATCH_SERVICE;
165
166        return doPost(u, params);
167    }
168
169
170    public Value recordValue(PointName pointName, Value v) throws IOException {
171        String u = host + Const.PATH_CURRENT_VALUE;
172        String json = gson.toJson(v, ValueModel.class);
173        String params = Const.PARAM_TIMESTAMP +
174                "=" + v.getTimestamp().getTime() +
175                "&" + Const.PARAM_POINT + "=" +
176                URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING) +
177                "&" + Const.PARAM_JSON + "=" + URLEncoder.encode(json, Const.CONST_ENCODING);
178        String result = doPost(u, params);
179        return gson.fromJson(result, ValueModel.class);
180
181    }
182
183    /**
184     * Add a new Category
185     *
186     * @param categoryName the name of the new category
187     * @throws UnsupportedEncodingException
188     */
189    public Category addCategory(final CategoryName categoryName) throws UnsupportedEncodingException {
190
191        final String u = host + Const.PATH_CATEGORY_SERVICE;
192        final String params = "name=" + URLEncoder.encode(categoryName.getValue(), Const.CONST_ENCODING);
193        final String result = doPost(u, params);
194        return gson.fromJson(result, PointCategoryModelImpl.class);
195
196
197    }
198
199    public String deleteCategory(final CategoryName categoryName) {
200        String retVal = "";
201        try {
202            String u = host + Const.PATH_CATEGORY_SERVICE;
203            String params;
204            params = "action=delete&name=" + URLEncoder.encode(categoryName.getValue(), Const.CONST_ENCODING);
205            retVal = doPost(u, params);
206        } catch (UnsupportedEncodingException ignored) {
207
208        }
209        return retVal;
210
211
212    }
213
214    public Point addPoint(final CategoryName categoryName, final PointName pointName) {
215        Point point = null;
216
217        try {
218            final String u = host + Const.PATH_POINT_SERVICE;
219            final String params = Const.PARAM_NAME + "=" +
220                    URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING) +
221                    "&" + Const.PARAM_CATEGORY + "=" + URLEncoder.encode(categoryName.getValue(), Const.CONST_ENCODING);
222            String json = doPost(u, params);
223            point = gson.fromJson(json, PointModel.class);
224        } catch (UnsupportedEncodingException ignored) {
225
226        }
227        return point;
228
229
230    }
231
232    public Point getPoint(final PointName pointName) {
233        Point retObj = null;
234
235        try {
236            final String u = host + Const.PATH_POINT_SERVICE;
237            final String params = Const.PARAM_NAME + "=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING);
238            String json = doGet(u, params);
239            retObj = gson.fromJson(json, PointModel.class);
240
241        } catch (UnsupportedEncodingException ignored) {
242
243        } catch (IOException ignored) {
244
245        }
246        return retObj;
247
248
249    }
250
251    @Override
252    public Point updatePoint(final Point p) {
253        Point ret = null;
254
255        try {
256            String u = host + Const.PATH_POINT_SERVICE;
257            String params;
258            String json = gson.toJson(p);
259            params = Const.PARAM_JSON + "=" + URLEncoder.encode(json, Const.CONST_ENCODING) +
260                    "&" + Const.PARAM_ACTION + "=" + Const.ACTION_UPDATE;
261            String response = doPost(u, params);
262            if (response != null) {
263                ret = gson.fromJson(response, PointModel.class);
264            }
265        } catch (UnsupportedEncodingException e) {
266
267            e.printStackTrace();
268        }
269        return ret;
270
271    }
272
273
274    public Point addPoint(final Point p, final CategoryName categoryName) {
275        Point retObj = null;
276        final String newPointJson = gson.toJson(p);
277        try {
278            String u = host + Const.PATH_POINT_SERVICE;
279            String params;
280            params = Const.PARAM_JSON + "=" + URLEncoder.encode(newPointJson, Const.CONST_ENCODING);
281            params += "&" + Const.PARAM_CATEGORY + "=" +
282                    URLEncoder.encode(categoryName.getValue(), Const.CONST_ENCODING);
283            String result = doPost(u, params);
284            retObj = gson.fromJson(result, PointModel.class);
285        } catch (UnsupportedEncodingException e) {
286
287
288        }
289        return retObj;
290
291    }
292
293    public List<Category> getCategories(final boolean includePoints, final boolean includeDiagrams) {
294        final String u = host + Const.PATH_CATEGORY_SERVICE;
295        String params = "";
296
297        if (includePoints) {
298            params = Const.PARAM_INCLUDE_POINTS + "=" + Const.WORD_TRUE;
299        }
300        if (includeDiagrams) {
301            params += "&" + Const.PARAM_INCLUDE_DIAGRAMS + "=" + Const.WORD_TRUE;
302        }
303
304        final String json = doGet(u, params);
305
306
307        List<Category> retObj = null;
308
309
310        if (!(json.trim().length() == 0)) {
311            retObj = gson.fromJson(json, GsonFactory.categoryListType);
312
313            for (Category c : retObj) {
314                if (c.getJsonPointCollection() != null) {
315
316                    List<Point> points = gson.fromJson(c.getJsonPointCollection(), GsonFactory.pointListType);
317                    c.setPoints(points);
318
319
320                }
321                if (c.getJsonDiagramCollection() != null) {
322                    List<Diagram> diagrams = gson.fromJson(c.getJsonDiagramCollection(), GsonFactory.diagramListType);
323                    c.setDiagrams(diagrams);
324
325                }
326            }
327
328        }
329
330        return retObj;
331
332
333    }
334
335    public Category getCategory(final CategoryName categoryName, final boolean includePoints, final boolean includeDiagrams) {
336        Category c = null;
337        final String u = host + Const.PATH_CATEGORY_SERVICE;
338        String params = Const.PARAM_NAME + "=" + categoryName.getValue();
339
340        if (includePoints) {
341            params += "&" + Const.PARAM_INCLUDE_POINTS + "=" + Const.WORD_TRUE;
342        }
343        if (includeDiagrams) {
344            params += "&" + Const.PARAM_INCLUDE_DIAGRAMS + "=" + Const.WORD_TRUE;
345        }
346
347        final String json = doGet(u, params);
348
349
350        if (!(json.trim().length() == 0)) {
351            c = gson.fromJson(json, PointCategoryModelImpl.class);
352
353
354            if (c.getJsonPointCollection() != null) {
355                List<Point> points = gson.fromJson(c.getJsonPointCollection(), GsonFactory.categoryListType);
356                c.setPoints(points);
357
358            }
359            if (c.getJsonDiagramCollection() != null) {
360                List<Diagram> diagrams = gson.fromJson(c.getJsonDiagramCollection(), GsonFactory.diagramListType);
361                c.setDiagrams(diagrams);
362
363            }
364
365        }
366
367
368        return c;
369
370
371    }
372
373    public String currentValue(final PointName pointName) throws IOException {
374        String u = host + Const.PATH_CURRENT_VALUE;
375        String params = Const.PARAM_POINT + "=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING);
376        return doGet(u, params);
377
378    }
379
380    public Object getCurrentDataObject(final PointName pointName, Class<?> cls) {
381        Value value = getCurrentRecordedValue(pointName);
382        if (value.getData() != null) {
383            return gson.fromJson(value.getData(), cls);
384        } else {
385            return null;
386        }
387
388
389    }
390
391    public Value getCurrentRecordedValue(final PointName pointName) {
392        Value retObj = null;
393        String u = host + Const.PATH_CURRENT_VALUE;
394        String params;
395        String json;
396
397        try {
398            params = Const.PARAM_POINT + "=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING) + "&format=json";
399            json = doGet(u, params);
400
401            if (json != null) {
402                retObj = gson.fromJson(json, ValueModel.class);
403            }
404
405        } catch (Exception e) {
406
407            e.printStackTrace();
408        }
409
410
411        return retObj;
412
413
414    }
415
416    public List<Value> getSeries(final PointName pointName, final int count) {
417        List<Value> retObj = null;
418
419        String result;
420
421        final String destUrl = host + Const.PATH_SERIES_SERVICE;
422        String params;
423        try {
424            params = Const.PARAM_COUNT + "=" + count + "&" + Const.PARAM_POINT + "=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING);
425            result = doGet(destUrl, params);
426            System.out.println(destUrl + "?" + params);
427            System.out.println(result);
428            retObj = gson.fromJson(result, GsonFactory.valueListType);
429
430        } catch (UnsupportedEncodingException e) {
431
432            e.printStackTrace();
433        } catch (IOException e) {
434
435            e.printStackTrace();
436        }
437
438        return retObj;
439
440    }
441
442    public List<Value> getSeries(final PointName pointName, final Date startDate, final Date endDate) {
443        final List<Value> retObj = new ArrayList<Value>();
444
445
446        String result;
447
448        String destUrl = host + Const.PATH_SERIES_SERVICE;
449        String params;
450        int seg = 0;
451
452        try {
453            while (true) {
454                params = "seg=" + seg + "&sd=" + startDate.getTime() + "&ed=" + endDate.getTime() + "&" + Const.PARAM_POINT + "=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING);
455                result = doGet(destUrl, params);
456                List<Value> r = gson.fromJson(result, GsonFactory.valueListType);
457
458                if (r == null || r.size() == 0) {
459                    break;
460                } else {
461                    retObj.addAll(r);
462                }
463                seg += 1000;
464            }
465
466        } catch (UnsupportedEncodingException e) {
467
468            e.printStackTrace();
469        } catch (IOException e) {
470
471            e.printStackTrace();
472        }
473
474        return retObj;
475
476    }
477
478    @Override
479    public void downloadSeries(final PointName pointName, final Date startDate, final Date endDate, final String filename) throws IOException {
480        final List<Value> r = getSeries(pointName, startDate, endDate);
481
482        String json = gson.toJson(r, GsonFactory.valueListType);
483
484        Writer out;
485
486        out = new OutputStreamWriter(new FileOutputStream(filename));
487        out.write(json);
488        out.close();
489
490
491    }
492
493    @Override
494    public List<Value> loadSeriesFile(final String fileName) throws IOException {
495
496        final StringBuilder sb = new StringBuilder();
497        final BufferedReader in = new BufferedReader(new FileReader(fileName));
498        String str;
499
500        while ((str = in.readLine()) != null) {
501            sb.append(str);
502        }
503        in.close();
504        return gson.fromJson(sb.toString(), GsonFactory.valueListType);
505
506    }
507
508
509    private String doGet(final String postUrl, final String params) {
510        final StringBuilder sb = new StringBuilder();
511
512        try {
513
514            final String paramsWithAuth = params + getAuthParams();
515            final URL url = new URL(postUrl + "?" + paramsWithAuth);
516            final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
517            connection.setDoOutput(true);
518            connection.setRequestMethod(Const.METHOD_GET);
519
520            if (G != null && G.getAuthCookie() != null) {
521
522                connection.addRequestProperty("Cookie", G.getAuthCookie().getName() + "=" + G.getAuthCookie().getValue());
523
524            }
525
526
527            final BufferedReader reader = new BufferedReader(new InputStreamReader(
528                    connection.getInputStream()));
529
530            String line;
531
532            while ((line = reader.readLine()) != null) {
533                sb.append(line);
534            }
535            reader.close();
536
537        } catch (Exception e) {
538            //throw e;
539        }
540
541
542        return sb.toString();
543
544    }
545
546    public byte[] getBinaryFile(final String postUrl, String params) throws IOException {
547
548        int c;
549        params += getAuthParams();
550        final URL url = new URL(postUrl + "?" + params);
551        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
552        connection.setDoOutput(true);
553        connection.setRequestMethod(Const.METHOD_GET);
554        if (G != null && G.getAuthCookie() != null) {
555
556            connection.addRequestProperty("Cookie", G.getAuthCookie().getName() + "=" + G.getAuthCookie().getValue());
557
558
559        }
560        final DataInputStream in = new DataInputStream(connection.getInputStream());
561        final ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
562        while ((c = in.read()) != -1) {
563            byteArrayOut.write(c);
564        }
565        in.close();
566        return byteArrayOut.toByteArray();
567
568    }
569//    public byte[] getBinaryFile(String postUrl, String params) throws Exception {
570//        byte[] retObj;
571//        int c;
572//
573//        URL url = new URL(postUrl + "?" + params);
574//        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
575//        connection.setDoOutput(true);
576//        connection.setRequestMethod("GET");
577//
578//        if (G != null) {
579//
580//            try {
581//                if (G.getAuthCookie() != null) {
582//                    connection.addRequestProperty("Cookie", G.getAuthCookie().getValue() + "=" + G.getAuthCookie().getValue());
583//                }
584//
585//            } catch (Exception e) {
586//
587//            }
588//            params += getAuthParams();
589//
590//        }
591//
592//        DataInputStream in = new DataInputStream(connection.getInputStream());
593//        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
594//
595//
596//        while ((c = in.read()) != -1) {
597//            byteArrayOut.write(c);
598//        }
599//        retObj = byteArrayOut.toByteArray();
600//
601//
602//        return retObj;
603//
604//    }
605
606    private String getAuthParams() {
607        StringBuilder b = new StringBuilder();
608
609        b.append("&" + Const.PARAM_EMAIL + "=");
610        b.append(G.getEmail().getValue());
611
612
613        if (G.getSecret() != null) {
614            b.append("&" + Const.PARAM_SECRET + "=");
615            b.append(G.getSecret());
616        }
617        return b.toString();
618
619
620    }
621
622    private String doPost(final String postUrl, final String params) {
623        String retVal = "";
624        String postParams = params;
625        try {
626            final URL url = new URL(postUrl);
627            final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
628            connection.setDoOutput(true);
629            connection.setRequestMethod(Const.METHOD_POST);
630            connection.setReadTimeout(10000);
631
632
633            if (G != null) {
634
635                if (G.getAuthCookie() != null) {
636                    connection.addRequestProperty("Cookie", G.getAuthCookie().getName() + "=" + G.getAuthCookie().getValue());
637                }
638
639                postParams += getAuthParams();
640
641            }
642
643
644            // 	System.out.println(params);
645
646            final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
647            writer.write(postParams);
648            writer.close();
649            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
650                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
651                String line;
652                while ((line = reader.readLine()) != null) {
653                    retVal += line;
654                }
655                reader.close();
656            }
657        } catch (MalformedURLException e) {
658            throw new NimbitsRuntimeException(e);
659        } catch (IOException e) {
660            throw new NimbitsRuntimeException(e);
661        }
662        return retVal;
663
664    }
665
666
667}