/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
- package com.nimbits.client;
-
- import com.google.gson.Gson;
- import com.nimbits.client.exception.NimbitsRuntimeException;
- import com.nimbits.client.model.Const;
- import com.nimbits.client.model.category.Category;
- import com.nimbits.client.model.category.CategoryName;
- import com.nimbits.client.model.category.impl.PointCategoryModelImpl;
- import com.nimbits.client.model.diagram.Diagram;
- import com.nimbits.client.model.email.EmailAddress;
- import com.nimbits.client.model.point.Point;
- import com.nimbits.client.model.point.PointModel;
- import com.nimbits.client.model.point.PointName;
- import com.nimbits.client.model.user.User;
- import com.nimbits.client.model.value.Value;
- import com.nimbits.client.model.value.ValueModel;
- import com.nimbits.client.model.value.ValueModelFactory;
- import com.nimbits.gson.GsonFactory;
- import com.nimbits.user.GoogleAuthentication;
- import com.nimbits.user.GoogleUser;
- import com.nimbits.user.NimbitsUser;
- import org.apache.http.cookie.Cookie;
-
- import java.io.*;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.net.URLEncoder;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
-
-
- public class NimbitsClientImpl implements NimbitsClient {
-
- final private static Gson gson = GsonFactory.getInstance();
-
- private final GoogleAuthentication G;
- private final String host;
- private Cookie authCookie;
-
- // private NimbitsClientImpl() {
- // }
-
- public NimbitsClientImpl(final NimbitsUser n, final String hostUrl) {
- this.host = hostUrl;
- G = GoogleAuthentication.getNewGoogleAuthentication();
- G.setEmail(n.getEmailAddress());
- G.setSecret(n.getNimbitsSecretKey());
- }
-
- public NimbitsClientImpl(final GoogleUser g, final String hostUrl) throws Exception {
- this.host = hostUrl;
- G = GoogleAuthentication.getNewGoogleAuthentication();
- G.setEmail(g.getGoogleEmailAddress());
- G.Connect(hostUrl, g.getGoogleEmailAddress(), g.getGooglePassword());
-
- }
-
- public String getHost() {
- return host;
- }
-
- public NimbitsClientImpl(final String token, final EmailAddress email, final String hostUrl) throws Exception {
- this.host = hostUrl;
- G = GoogleAuthentication.getNewGoogleAuthentication();
- G.setEmail(email);
- authCookie = G.ConnectAuth(token, hostUrl);
-
-
- }
-
- public Cookie getAuthCookie() {
- return authCookie;
- }
-
-
- public boolean isLoggedIn() {
-
- return Boolean.parseBoolean(doGet(host + Const.PATH_AUTHTEST_SERVICE, ""));
-
- }
-
- public List<User> getUsers() {
- String u = host + Const.PATH_USER_SERVICE;
- String params = "action=download";
- String result = doGet(u, params);
-
- return gson.fromJson(result, GsonFactory.userListType);
-
-
- }
-
- public String getChart(final String points, final int count) {
- final String u = host + Const.Path_CHART_API;
- String params = null;
- final String result;
- try {
- 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";
- } catch (UnsupportedEncodingException e1) {
-
- e1.printStackTrace();
- }
-
-
- result = doGet(u, params);
-
-
- return result;
- }
-
- public String getChartURL(final String points, final int count, final String additionalParams) {
- final String u = host + Const.Path_CHART_API;
- String params = null;
-
- try {
- params = "count=10&points=" + URLEncoder.encode(points, Const.CONST_ENCODING) + "&" + additionalParams;
-
- } catch (UnsupportedEncodingException e1) {
-
- e1.printStackTrace();
- }
-
-
- return u + "?" + params;
- }
-
- public void deletePoint(final PointName pointName) {
- final String u = host + Const.PATH_POINT_SERVICE;
- try {
- String params = "point=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING) + "&action=delete";
- doPost(u, params);
- } catch (UnsupportedEncodingException ignored) {
-
- }
-
- }
-
- public Value recordValue(final PointName pointName,
- final double value,
- final Date timestamp) throws IOException {
- String u = host + Const.PATH_CURRENT_VALUE;
- String params = "point=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING) + "×tamp=" + timestamp.getTime() + "&value=" + value;
- String json = doPost(u, params);
- return gson.fromJson(json, ValueModel.class);
- }
-
- public Value recordValueWithGet(final PointName pointName, final double value, final Date timestamp) throws IOException {
- final String u = host + Const.PATH_CURRENT_VALUE;
- String params = "point=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING) +
- "×tamp=" + timestamp.getTime() +
- "&value=" + value;
-
- String json = doGet(u, params);
- System.out.println(json);
- double d = Double.valueOf(json);
- return ValueModelFactory.createValueModel(d);
-
- //return gson.fromJson(json, ValueModel.class);
-
- }
-
- public String recordBatch(String params) {
- String u = host + Const.PATH_BATCH_SERVICE;
-
- return doPost(u, params);
- }
-
-
- public Value recordValue(PointName pointName, Value v) throws IOException {
- String u = host + Const.PATH_CURRENT_VALUE;
- String json = gson.toJson(v, ValueModel.class);
- String params = Const.PARAM_TIMESTAMP +
- "=" + v.getTimestamp().getTime() +
- "&" + Const.PARAM_POINT + "=" +
- URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING) +
- "&" + Const.PARAM_JSON + "=" + URLEncoder.encode(json, Const.CONST_ENCODING);
- String result = doPost(u, params);
- return gson.fromJson(result, ValueModel.class);
-
- }
-
- /**
- * Add a new Category
- *
- * @param categoryName the name of the new category
- * @throws UnsupportedEncodingException
- */
- public Category addCategory(final CategoryName categoryName) throws UnsupportedEncodingException {
-
- final String u = host + Const.PATH_CATEGORY_SERVICE;
- final String params = "name=" + URLEncoder.encode(categoryName.getValue(), Const.CONST_ENCODING);
- final String result = doPost(u, params);
- return gson.fromJson(result, PointCategoryModelImpl.class);
-
-
- }
-
- public String deleteCategory(final CategoryName categoryName) {
- String retVal = "";
- try {
- String u = host + Const.PATH_CATEGORY_SERVICE;
- String params;
- params = "action=delete&name=" + URLEncoder.encode(categoryName.getValue(), Const.CONST_ENCODING);
- retVal = doPost(u, params);
- } catch (UnsupportedEncodingException ignored) {
-
- }
- return retVal;
-
-
- }
-
- public Point addPoint(final CategoryName categoryName, final PointName pointName) {
- Point point = null;
-
- try {
- final String u = host + Const.PATH_POINT_SERVICE;
- final String params = Const.PARAM_NAME + "=" +
- URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING) +
- "&" + Const.PARAM_CATEGORY + "=" + URLEncoder.encode(categoryName.getValue(), Const.CONST_ENCODING);
- String json = doPost(u, params);
- point = gson.fromJson(json, PointModel.class);
- } catch (UnsupportedEncodingException ignored) {
-
- }
- return point;
-
-
- }
-
- public Point getPoint(final PointName pointName) {
- Point retObj = null;
-
- try {
- final String u = host + Const.PATH_POINT_SERVICE;
- final String params = Const.PARAM_NAME + "=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING);
- String json = doGet(u, params);
- retObj = gson.fromJson(json, PointModel.class);
-
- } catch (UnsupportedEncodingException ignored) {
-
- } catch (IOException ignored) {
-
- }
- return retObj;
-
-
- }
-
- @Override
- public Point updatePoint(final Point p) {
- Point ret = null;
-
- try {
- String u = host + Const.PATH_POINT_SERVICE;
- String params;
- String json = gson.toJson(p);
- params = Const.PARAM_JSON + "=" + URLEncoder.encode(json, Const.CONST_ENCODING) +
- "&" + Const.PARAM_ACTION + "=" + Const.ACTION_UPDATE;
- String response = doPost(u, params);
- if (response != null) {
- ret = gson.fromJson(response, PointModel.class);
- }
- } catch (UnsupportedEncodingException e) {
-
- e.printStackTrace();
- }
- return ret;
-
- }
-
-
- public Point addPoint(final Point p, final CategoryName categoryName) {
- Point retObj = null;
- final String newPointJson = gson.toJson(p);
- try {
- String u = host + Const.PATH_POINT_SERVICE;
- String params;
- params = Const.PARAM_JSON + "=" + URLEncoder.encode(newPointJson, Const.CONST_ENCODING);
- params += "&" + Const.PARAM_CATEGORY + "=" +
- URLEncoder.encode(categoryName.getValue(), Const.CONST_ENCODING);
- String result = doPost(u, params);
- retObj = gson.fromJson(result, PointModel.class);
- } catch (UnsupportedEncodingException e) {
-
-
- }
- return retObj;
-
- }
-
- public List<Category> getCategories(final boolean includePoints, final boolean includeDiagrams) {
- final String u = host + Const.PATH_CATEGORY_SERVICE;
- String params = "";
-
- if (includePoints) {
- params = Const.PARAM_INCLUDE_POINTS + "=" + Const.WORD_TRUE;
- }
- if (includeDiagrams) {
- params += "&" + Const.PARAM_INCLUDE_DIAGRAMS + "=" + Const.WORD_TRUE;
- }
-
- final String json = doGet(u, params);
-
-
- List<Category> retObj = null;
-
-
- if (!(json.trim().length() == 0)) {
- retObj = gson.fromJson(json, GsonFactory.categoryListType);
-
- for (Category c : retObj) {
- if (c.getJsonPointCollection() != null) {
-
- List<Point> points = gson.fromJson(c.getJsonPointCollection(), GsonFactory.pointListType);
- c.setPoints(points);
-
-
- }
- if (c.getJsonDiagramCollection() != null) {
- List<Diagram> diagrams = gson.fromJson(c.getJsonDiagramCollection(), GsonFactory.diagramListType);
- c.setDiagrams(diagrams);
-
- }
- }
-
- }
-
- return retObj;
-
-
- }
-
- public Category getCategory(final CategoryName categoryName, final boolean includePoints, final boolean includeDiagrams) {
- Category c = null;
- final String u = host + Const.PATH_CATEGORY_SERVICE;
- String params = Const.PARAM_NAME + "=" + categoryName.getValue();
-
- if (includePoints) {
- params += "&" + Const.PARAM_INCLUDE_POINTS + "=" + Const.WORD_TRUE;
- }
- if (includeDiagrams) {
- params += "&" + Const.PARAM_INCLUDE_DIAGRAMS + "=" + Const.WORD_TRUE;
- }
-
- final String json = doGet(u, params);
-
-
- if (!(json.trim().length() == 0)) {
- c = gson.fromJson(json, PointCategoryModelImpl.class);
-
-
- if (c.getJsonPointCollection() != null) {
- List<Point> points = gson.fromJson(c.getJsonPointCollection(), GsonFactory.categoryListType);
- c.setPoints(points);
-
- }
- if (c.getJsonDiagramCollection() != null) {
- List<Diagram> diagrams = gson.fromJson(c.getJsonDiagramCollection(), GsonFactory.diagramListType);
- c.setDiagrams(diagrams);
-
- }
-
- }
-
-
- return c;
-
-
- }
-
- public String currentValue(final PointName pointName) throws IOException {
- String u = host + Const.PATH_CURRENT_VALUE;
- String params = Const.PARAM_POINT + "=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING);
- return doGet(u, params);
-
- }
-
- public Object getCurrentDataObject(final PointName pointName, Class<?> cls) {
- Value value = getCurrentRecordedValue(pointName);
- if (value.getData() != null) {
- return gson.fromJson(value.getData(), cls);
- } else {
- return null;
- }
-
-
- }
-
- public Value getCurrentRecordedValue(final PointName pointName) {
- Value retObj = null;
- String u = host + Const.PATH_CURRENT_VALUE;
- String params;
- String json;
-
- try {
- params = Const.PARAM_POINT + "=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING) + "&format=json";
- json = doGet(u, params);
-
- if (json != null) {
- retObj = gson.fromJson(json, ValueModel.class);
- }
-
- } catch (Exception e) {
-
- e.printStackTrace();
- }
-
-
- return retObj;
-
-
- }
-
- public List<Value> getSeries(final PointName pointName, final int count) {
- List<Value> retObj = null;
-
- String result;
-
- final String destUrl = host + Const.PATH_SERIES_SERVICE;
- String params;
- try {
- params = Const.PARAM_COUNT + "=" + count + "&" + Const.PARAM_POINT + "=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING);
- result = doGet(destUrl, params);
- System.out.println(destUrl + "?" + params);
- System.out.println(result);
- retObj = gson.fromJson(result, GsonFactory.valueListType);
-
- } catch (UnsupportedEncodingException e) {
-
- e.printStackTrace();
- } catch (IOException e) {
-
- e.printStackTrace();
- }
-
- return retObj;
-
- }
-
- public List<Value> getSeries(final PointName pointName, final Date startDate, final Date endDate) {
- final List<Value> retObj = new ArrayList<Value>();
-
-
- String result;
-
- String destUrl = host + Const.PATH_SERIES_SERVICE;
- String params;
- int seg = 0;
-
- try {
- while (true) {
- params = "seg=" + seg + "&sd=" + startDate.getTime() + "&ed=" + endDate.getTime() + "&" + Const.PARAM_POINT + "=" + URLEncoder.encode(pointName.getValue(), Const.CONST_ENCODING);
- result = doGet(destUrl, params);
- List<Value> r = gson.fromJson(result, GsonFactory.valueListType);
-
- if (r == null || r.size() == 0) {
- break;
- } else {
- retObj.addAll(r);
- }
- seg += 1000;
- }
-
- } catch (UnsupportedEncodingException e) {
-
- e.printStackTrace();
- } catch (IOException e) {
-
- e.printStackTrace();
- }
-
- return retObj;
-
- }
-
- @Override
- public void downloadSeries(final PointName pointName, final Date startDate, final Date endDate, final String filename) throws IOException {
- final List<Value> r = getSeries(pointName, startDate, endDate);
-
- String json = gson.toJson(r, GsonFactory.valueListType);
-
- Writer out;
-
- out = new OutputStreamWriter(new FileOutputStream(filename));
- out.write(json);
- out.close();
-
-
- }
-
- @Override
- public List<Value> loadSeriesFile(final String fileName) throws IOException {
-
- final StringBuilder sb = new StringBuilder();
- final BufferedReader in = new BufferedReader(new FileReader(fileName));
- String str;
-
- while ((str = in.readLine()) != null) {
- sb.append(str);
- }
- in.close();
- return gson.fromJson(sb.toString(), GsonFactory.valueListType);
-
- }
-
-
- private String doGet(final String postUrl, final String params) {
- final StringBuilder sb = new StringBuilder();
-
- try {
-
- final String paramsWithAuth = params + getAuthParams();
- final URL url = new URL(postUrl + "?" + paramsWithAuth);
- final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.setDoOutput(true);
- connection.setRequestMethod(Const.METHOD_GET);
-
- if (G != null && G.getAuthCookie() != null) {
-
- connection.addRequestProperty("Cookie", G.getAuthCookie().getName() + "=" + G.getAuthCookie().getValue());
-
- }
-
-
- final BufferedReader reader = new BufferedReader(new InputStreamReader(
- connection.getInputStream()));
-
- String line;
-
- while ((line = reader.readLine()) != null) {
- sb.append(line);
- }
- reader.close();
-
- } catch (Exception e) {
- //throw e;
- }
-
-
- return sb.toString();
-
- }
-
- public byte[] getBinaryFile(final String postUrl, String params) throws IOException {
-
- int c;
- params += getAuthParams();
- final URL url = new URL(postUrl + "?" + params);
- final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.setDoOutput(true);
- connection.setRequestMethod(Const.METHOD_GET);
- if (G != null && G.getAuthCookie() != null) {
-
- connection.addRequestProperty("Cookie", G.getAuthCookie().getName() + "=" + G.getAuthCookie().getValue());
-
-
- }
- final DataInputStream in = new DataInputStream(connection.getInputStream());
- final ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
- while ((c = in.read()) != -1) {
- byteArrayOut.write(c);
- }
- in.close();
- return byteArrayOut.toByteArray();
-
- }
- // public byte[] getBinaryFile(String postUrl, String params) throws Exception {
- // byte[] retObj;
- // int c;
- //
- // URL url = new URL(postUrl + "?" + params);
- // HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- // connection.setDoOutput(true);
- // connection.setRequestMethod("GET");
- //
- // if (G != null) {
- //
- // try {
- // if (G.getAuthCookie() != null) {
- // connection.addRequestProperty("Cookie", G.getAuthCookie().getValue() + "=" + G.getAuthCookie().getValue());
- // }
- //
- // } catch (Exception e) {
- //
- // }
- // params += getAuthParams();
- //
- // }
- //
- // DataInputStream in = new DataInputStream(connection.getInputStream());
- // ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
- //
- //
- // while ((c = in.read()) != -1) {
- // byteArrayOut.write(c);
- // }
- // retObj = byteArrayOut.toByteArray();
- //
- //
- // return retObj;
- //
- // }
-
- private String getAuthParams() {
- StringBuilder b = new StringBuilder();
-
- b.append("&" + Const.PARAM_EMAIL + "=");
- b.append(G.getEmail().getValue());
-
-
- if (G.getSecret() != null) {
- b.append("&" + Const.PARAM_SECRET + "=");
- b.append(G.getSecret());
- }
- return b.toString();
-
-
- }
-
- private String doPost(final String postUrl, final String params) {
- String retVal = "";
- String postParams = params;
- try {
- final URL url = new URL(postUrl);
- final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.setDoOutput(true);
- connection.setRequestMethod(Const.METHOD_POST);
- connection.setReadTimeout(10000);
-
-
- if (G != null) {
-
- if (G.getAuthCookie() != null) {
- connection.addRequestProperty("Cookie", G.getAuthCookie().getName() + "=" + G.getAuthCookie().getValue());
- }
-
- postParams += getAuthParams();
-
- }
-
-
- // System.out.println(params);
-
- final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
- writer.write(postParams);
- writer.close();
- if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
- BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
- String line;
- while ((line = reader.readLine()) != null) {
- retVal += line;
- }
- reader.close();
- }
- } catch (MalformedURLException e) {
- throw new NimbitsRuntimeException(e);
- } catch (IOException e) {
- throw new NimbitsRuntimeException(e);
- }
- return retVal;
-
- }
-
-
- }