DataServiceImpl.java :  » Log » nimbitsopen » com » nimbits » server » Android Open Source

Android Open Source » Log » nimbitsopen 
nimbitsopen » com » nimbits » server » DataServiceImpl.java
package com.nimbits.server;



import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.nimbits.PMF;
import com.nimbits.client.Service.DataService;
import com.nimbits.client.objects.DataPoint;
import com.nimbits.client.objects.RecordedValue;
import com.nimbits.server.nimbitsUser.CurrentUser;
import com.nimbits.server.nimbitsUser.NimbitsUser;
import com.nimbits.server.nimbitsUser.UserServiceImpl;

public class DataServiceImpl  extends RemoteServiceServlet implements
DataService {
 
  private static final long serialVersionUID = 1L;
 
  public double solveEquation( DataPoint point) {
    return EquationSolver.solveEquation( point);
  }
 
  
  public RecordedValue getCurrentValue(DataPoint p )
  {
    RecordedValue retObj;
    PersistenceManager pm = PMF.get().getPersistenceManager();
    retObj = getCurrentValue(p, pm);
    pm.close();
    return retObj;  
  }
  
  
  public void recordValue(String pointName , java.util.Date timestamp, double value, String note, double lat, double lng, PersistenceManager pm)   {

    NimbitsUser nuser = new UserServiceImpl().GetNimbitsUser(this.getThreadLocalRequest(),"recordValue 1", pm);

    long userFK = nuser.getID();
    DataPoint point = new  PointServiceImpl().getPointByName(userFK, pointName, null );
    recordValue(nuser, point, timestamp, value, note,lat, lng, pm);

  }
  public void recordValue(String pointName , java.util.Date timestamp, double value, String note, double lat, double lng, String email, String secret, PersistenceManager pm)   {
    if (Secrets.checkSecret(secret))
    {
      NimbitsUser nuser = CurrentUser.getNimbitsUser(email, false, "recordValue 3", pm);
      long userFK = nuser.getID();
      DataPoint point = new  PointServiceImpl().getPointByName(userFK, pointName, pm );
      recordValue(nuser, point, timestamp, value, note,lat, lng, pm);

    }
    
  }
  public void recordValue(DataPoint point , java.util.Date timestamp, double value, String note, double lat, double lng )   {
    //this is the one that is called from rpc
    PersistenceManager pm = PMF.get().getPersistenceManager();
    NimbitsUser nuser = new UserServiceImpl().GetNimbitsUser(this.getThreadLocalRequest(),"recordValue 2", pm);
    recordValue(nuser, point, timestamp, value, note,lat, lng, pm);
    pm.close();
    

  }
  public void recordValue(NimbitsUser nuser, String pointName , java.util.Date timestamp, double value, String note, double lat, double lng, PersistenceManager pm)   {

     
    long userFK = nuser.getID();
    DataPoint point = new  PointServiceImpl().getPointByName(userFK, pointName, null );
    recordValue(nuser, point, timestamp, value, note,lat,lng, pm);

  }
 
  public void recordValue(NimbitsUser u, DataPoint point,
      java.util.Date timestamp, double v, String note, double lat,
      double lng, PersistenceManager pm) {
    boolean closePM = false;
    if (pm == null) {
      pm = PMF.get().getPersistenceManager();
      closePM = true;
    }
    double prev;

    NimbitsUser nuser = null;

    if (u == null) {
      nuser = new UserServiceImpl().GetNimbitsUser(
          this.getThreadLocalRequest(), "recordValue 3", pm);
    } else {
      nuser = u;
    }

    Boolean ignore = point.isSystemPoint();

    if (!ignore)

    {
      RecordedValue prevValue = null;
      RecordedValue currValue = getCurrentValue(point, pm);
      if (currValue != null) {
        if (currValue.getTimestamp().getTime() <= timestamp.getTime()) // this
                                        // means
                                        // it's
                                        // a
                                        // new
                                        // record,
                                        // not
                                        // an
                                        // insert
                                        // into
                                        // a
                                        // prev
                                        // timespane
        {
          prevValue = currValue;
        } else {
          prevValue = getPrevValue(point, timestamp, pm);
        }
      }

      boolean doCompression = true;

      if (!(note == null)) {
        if ((!note.equals(point.getLastNote()))) {
          doCompression = false;

        }

      }
      if (point.getCompression() < 0) {
        doCompression = false;

      }

      if (doCompression) {
        if (!(prevValue == null)) {
          prev = prevValue.getValue();
          if (v <= (prev + point.getCompression())
              && v >= (prev - point.getCompression())) {

            return;

          }

        }

      }
      boolean alarmsent = false;

      // alerts
      try {
        if (point.isHighAlarmOn() || point.isLowAlarmOn()) {
          if (Common.Now().getTime() > point.getLastAlarmSent()
              + (point.getAlarmDelay() * 60 * 1000)) {
            PointServiceImpl ps = new PointServiceImpl();
            if (point.isHighAlarmOn()
                && (v >= point.getHighAlarm())) {
              Email.SendAlarm(point, nuser.getEmail(), v, "h");

              if (point.getAlarmToFacebook()) {
                PostToFB(point, nuser, v, "High Alert!", note);
              }
              if (point.getSendAlarmTweet()) {
                TwitterServiceImpl.sendTweet(nuser,
                    ("Data Point [" + point.getName()
                        + "]=" + v + ". " + note));

              }

              if (point.getSendAlarmIM()) {
                IMServiceImpl.sendMessage(
                    ("Data Point [" + point.getName()
                        + "]=" + v + ". " + note),
                    nuser.getEmail());

              }
              alarmsent = true;
              point.setLastAlarmSent(Common.Now().getTime());
              ps.updatePoint(point);

            }
            if (point.isLowAlarmOn() && v <= point.getLowAlarm()) {
              Email.SendAlarm(point, nuser.getEmail(), v, "l");

              if (point.getAlarmToFacebook()) {
                PostToFB(point, nuser, v, "Low Alert!", note);
              }
              if (point.getSendAlarmTweet()) {
                if (point.getSendAlarmTweet()) {
                  String tweet = "Data Point ["
                      + point.getName() + "]=" + v + ". "
                      + note + "."
                      + point.getDescription();

                  TwitterServiceImpl.sendTweet(nuser, tweet);

                }
              }

              if (point.getSendAlarmIM()) {
                IMServiceImpl.sendMessage(
                    "Low Alarm: Nimbits Data Point ["
                        + point.getName()
                        + "] updated to new value: "
                        + v, nuser.getEmail());

              }

              alarmsent = true;
              point.setLastAlarmSent(Common.Now().getTime());
              ps.updatePoint(point, pm);

            }
            ps = null;
          }
        }
      } catch (Exception e) {

      }

      try {

        RecordedValue c = new RecordedValue();

        c.setPointFK(point.getID());
        c.setValue(v);
        c.setTimestamp(timestamp);
        c.setNote(note);
        c.setLatitude(lat);
        c.setLongitude(lng);
        pm.makePersistent(c);

        updatePointStats(point, v, timestamp, note, pm, lat, lng);
        if (currValue != null) {
          // if (currValue.getTimestamp().getTime() <
          // c.getTimestamp().getTime())
          // {
          // String key = "CacheKey_CurrentValue" +point.getKey();
          // CacheSingleton.getCache().put(key, c2);

          // }
        }

      } catch (Throwable caught) {

        caught.printStackTrace();

      } finally {
        if (closePM) {
          pm.close();
          pm = null;
        }

      }

      if (point.isPostToFacebook() && (nuser.getFacebookToken() != null)
          && (!alarmsent)) {
        PostToFB(point, nuser, v, "", note);

      }
      if (point.getSendIM()) {
        IMServiceImpl.sendMessage(
            "Nimbits Data Point [" + point.getName()
                + "] updated to new value: " + v,
            nuser.getEmail());

      }

      if (point.getSendTweet()) {
        TwitterServiceImpl.sendTweet(nuser,
            ("Nimbits Data Point [" + point.getName()
                + "] updated to new value: " + v + "."));

      }

      if (!(point.getTarget() == null)) {
        DataPoint target = new PointServiceImpl().getPointByID(point
            .getTarget());

        if (!(target == null)) {
          double calcResult = solveEquation(point);
          recordValue(target, timestamp, calcResult, note, lat, lng);
        }
      }

    }

  }
 
  public String getThumbnailURL(DataPoint p)
  {
    String retVal = new  SettingsServiceImpl().getSetting("rooturl") + "/resources/images/nlogo1.jpg?reason=none";
    
    try {
      DataPoint pvals = getTopDataSeries(p, 10);
      
      if (pvals.getValues().size() > 0)
      {
        retVal = "http://chart.apis.google.com/chart?cht=lc&chs=100x100&chd=t:";
        for (int i = 0; i < pvals.getValues().size(); i++)
        {
          retVal +=  pvals.getValues().get(i).getValue() +",";
        }
        retVal = retVal.substring(0, retVal.length()-1);
        double h = p.getHighestRecordedValue();
        double l = p.getLowestRecordedValue();
        if (h==l)
        {
          h = h-10;
          l = l +10;
        }
        
        retVal += "&chds="+ l + "," + h;
           
      }
      else
      {
        retVal = new  SettingsServiceImpl().getSetting("rooturl") + "/resources/images/nlogo1.jpg?reason=nodata&point=" + p.getName();
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      retVal = new  SettingsServiceImpl().getSetting("rooturl") + "/resources/images/nlogo1.jpg?code=001&reason=" + e.getMessage();
    }
    return retVal;
    
  }
   private void PostToFB(DataPoint p, NimbitsUser nuser, double v, String alarmMessage, String note)
  {
    String m = ("Data Point [" + p.getName() + "]=" + v + ".");
    
    String token = nuser.getFacebookToken();
    
    String picture = getThumbnailURL(p);
    
    String link = "http://www.nimbits.com"; 
    
   
     
    if (p.isPublic())
    {
      new FaceBookServiceImpl().updateStatus(token,m, picture, link, "See Charts, Maps and More",note, "Point Description: " + p.getDescription() ); 
    }
    else
    {
      new FaceBookServiceImpl().updateStatus(token,m, picture, new  SettingsServiceImpl().getSetting("rooturl") , "Go to Nimbits", "This is a private data point, charts are not available", "Point Description: " + p.getDescription()); 
    }

  }
  @SuppressWarnings("unchecked")
  public void updatePointStats(DataPoint point, double v, Date timestamp,String note, PersistenceManager pm, double lat, double lng )
  {
    //update point stats
     

    Query q = pm.newQuery(DataPoint.class, "id ==k");
    q.declareParameters("Long k");
    List<DataPoint> result;
    result = (List<DataPoint>) q.execute(point.getID());

    try {
      if (result.size() > 0) {
        Transaction tx = pm.currentTransaction();
        tx.begin();
        DataPoint p;
        p =  result.get(0);
        if (p.getLowestRecordedValue() > v)
          p.setLastRecordedValue(v);

        if (p.getHighestRecordedValue() < v)
          p.setHighestRecordedValue(v);
        if (p.getLastRecordedTimestamp().getTime() < timestamp.getTime())
        {
          p.setLastRecordedTimestamp(timestamp);
        p.setLastRecordedValue(v);
        p.setLastNote(note);
        }
      if (lat != 0)
      {
        p.setLastLat(lat);
      }
      if (lng != 0)
      {
        p.setLastLng(lng);
      }
        tx.commit();


      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    finally
    {
     
    }
  }
  public void recordSystemValue(DataPoint point,  Date timestamp,  double v,String note, PersistenceManager pm){
  //  PersistenceManager pm = null;

    try
    {



      pm = PMF.get().getPersistenceManager();

      RecordedValue c = new RecordedValue();
      c.setPointFK(point.getID());
      c.setValue( v );
      c.setTimestamp(timestamp);
      pm.makePersistent(c);
      updatePointStats(  point,   v,   timestamp,note, pm,0,0);



    } catch (Throwable caught) {


      caught.printStackTrace();

    } finally {

      pm.close();
      pm = null;




    }
   


  }
 
  @SuppressWarnings({ "unchecked", "unused" })
  private String getDataSeriesXML(ArrayList<DataPoint> points,
      java.util.Date startDate, java.util.Date endDate)
  {
    String x = "";


    PersistenceManager pm = PMF.get().getPersistenceManager();
    //  User user = getUser();

    x += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    x += "<Values>\n";
    for (DataPoint point : points) {


      Query q = pm.newQuery(RecordedValue.class,
      "pointKey == k && timestamp >= sd && timestamp <= ed");
      q.declareImports("import java.util.Date");
      Map<String,Object> args = new HashMap<String,Object>();
      args.put("k", point.getID());
      args.put("sd", startDate);
      args.put("ed", endDate);

      q.declareParameters("Long k, Date sd, Date ed");
      q.setOrdering("timestamp descending");
      // q.setRange(0,1);
      List<RecordedValue> data = (List<RecordedValue>) q.executeWithMap(args);

      x += "<point unit=\"" + point.getUnit() + "\" name=\"" + point.getName() + "\">\n";
      if (data.size() > 0) {
        for (RecordedValue dx : data) {
          x += " <Point value=\""
            + dx.getValue() 
            + "\" timestamp=\"" + dx.getTimestamp().getTime()
            + "\" />\n";
        }
      } else {
        x += " <Point value=\"" + 0.00 + "\" timestamp=\""
        + Common.Now().getTime() + "\" />\n";

      }
      x += "</point>\n";

    }
    x += "</Values>\n";
    return x;
  }
  @SuppressWarnings("unchecked")
  private RecordedValue getAverage(DataPoint point,  java.util.Date startDate, java.util.Date endDate)
  {
    RecordedValue retObj = null;


    PersistenceManager pm = PMF.get().getPersistenceManager();


    Query q = pm.newQuery(RecordedValue.class,
    "pointFK== k && timestamp >= sd && timestamp <= ed");
    q.declareImports("import java.util.Date");
    Map<String,Object> args = new HashMap<String,Object>();
    args.put("k", point.getID());
    args.put("sd", startDate);
    args.put("ed", endDate);

    q.declareParameters("String k, Date sd, Date ed");
    q.setOrdering("timestamp descending");
    // q.setRange(0,1);
    List<RecordedValue> data = (List<RecordedValue>) q.executeWithMap(args);



    double r =0;
    if (data.size() > 0)
    {
      for (RecordedValue v : data)
      {

        r += v.getValue();
      }
      r = r/data.size();
      retObj = new RecordedValue();
      retObj.setTimestamp(startDate);
      retObj.setValue(r);
      retObj.setPointFK(point.getID());
    }




    pm.close();


    return retObj;
  }

//  public Double getEmailHourCount( PersistenceManager pm)
//  {
//    double t = 0;
//
//    DataPoint p =  getDataSeries( "EmailQuota", new Date(new Date().getTime() - ((1000 * 60) * 60)), new Date());
//    for (RecordedValue v : p.getValues())
//    {
//      t += v.getValue();
//    }
//
//    return t;
//
//  }
 
  public DataPoint getDataSeries( String pointName, java.util.Date startDate, java.util.Date endDate, PersistenceManager pm)
  {
    //UserServiceImpl U = new UserServiceImpl();
    NimbitsUser nuser = new UserServiceImpl().GetNimbitsUser(this.getThreadLocalRequest(),"getDataSeries", pm);
    long userFK = nuser.getID();
    ArrayList<DataPoint> pointsFull;


    DataPoint point = new  PointServiceImpl().getPointByName(userFK, pointName, null );
    ArrayList<DataPoint> points = new ArrayList<DataPoint>();
    points.add(point);
    pointsFull = getDataSeries(points, startDate, endDate);
    return pointsFull.get(0);

  }
  
  public  DataPoint getTopDataSeries(String pointName, int maxValues, PersistenceManager pm )  
  {
    //called from RPC
  //  PersistenceManager pm = PMF.get().getPersistenceManager();
    NimbitsUser nuser = new UserServiceImpl().GetNimbitsUser(this.getThreadLocalRequest(),"getTopDataSeries", pm);
    long userFK = nuser.getID();
      DataPoint point = new  PointServiceImpl().getPointByName(userFK, pointName, pm );
      point = getTopDataSeries(point,  maxValues, pm);
    //  pm.close();
      
    return point;

  }
  public  DataPoint getTopDataSeries(String email, String pointName, int maxValues, PersistenceManager pm)  
  {
    NimbitsUser nuser = CurrentUser.getNimbitsUser(email, false, "gettop", pm);
    long userFK = nuser.getID();
       
    DataPoint point = new  PointServiceImpl().getPointByName(userFK, pointName, pm );

    point = getTopDataSeries(point,  maxValues, pm);
    return point;

  }
  public  ArrayList<DataPoint> getTopDataSeries(String[] pointlist, int maxValues, PersistenceManager pm)  
  {
    NimbitsUser nuser = new UserServiceImpl().GetNimbitsUser(this.getThreadLocalRequest(),"getTopDataSeries", pm);
    long userFK = nuser.getID();
    ArrayList<DataPoint> retObj = new ArrayList<DataPoint>();
     
    for (String s : pointlist)
    {
      DataPoint point = new  PointServiceImpl().getPointByName(userFK, s, pm );
      point = getTopDataSeries(point,  maxValues);
      retObj.add(point);
      
    }
    
    
    return retObj;

  }
  
  public  DataPoint getTopDataSeries(DataPoint point, int maxValues )
  {
    PersistenceManager pm = PMF.get().getPersistenceManager();
    DataPoint retVal = getTopDataSeries(  point,   maxValues,   pm);
    pm.close();
    return retVal;
    
  }
  
  
  //this can throw an exception if the indexes are building on prod
  public  DataPoint getTopDataSeries(DataPoint point, int maxValues, PersistenceManager pm)
  {
    
    boolean closepm = false;
    DataPoint retObj = point;
    
    if (pm == null)
    {
       pm = PMF.get().getPersistenceManager();
       closepm = true;
    }
    try {
      Query q = pm.newQuery(RecordedValue.class, "pointFK== k");
      q.declareImports("import java.util.Date");
      Map<String, Long> args = new HashMap<String, Long>();
      args.put("k", point.getID());
      q.setRange(0, maxValues);
      q.declareParameters("Long k");
      q.setOrdering("timestamp ascending");
      @SuppressWarnings("unchecked")
      List<RecordedValue> data = (List<RecordedValue>) q
      .executeWithMap(args);
      
      
      retObj.setValues((List<RecordedValue>) pm.detachCopyAll(data));
      
      
      
      
    } catch (Exception e) {
      //Email.sendEmail(Global.AdminEmail,e.getMessage());
    }
    finally
    {
      if (closepm){
        pm.close();
      }
      
    }
    return retObj;
  }
   
  public   DataPoint getTopDataSeries(long pointid, int maxValues)
  {
     DataPoint p = new PointServiceImpl().getPointByID(pointid);
     DataPoint retObj = getTopDataSeries(p, maxValues);
     
    return retObj;
  }
  
  public   ArrayList<DataPoint> getDataSeries(ArrayList<DataPoint> points, java.util.Date startDate, java.util.Date endDate)
  {
    return getDataSeries(points, startDate, endDate, null);
    
  }
   
  @SuppressWarnings("unchecked")
  public   ArrayList<DataPoint> getDataSeries(ArrayList<DataPoint> points, java.util.Date startDate, java.util.Date endDate, PersistenceManager pm)
  {



    boolean closepm = false;
     if(pm == null)
     {
        pm = PMF.get().getPersistenceManager();
        closepm = true;
     }
     
 
    try {
      for (DataPoint point : points) {


        Query q = pm.newQuery(RecordedValue.class,
        "pointFK== k && timestamp >= sd && timestamp <= ed");
        q.declareImports("import java.util.Date");
        Map<String, Object> args = new HashMap<String, Object>();
        args.put("k", point.getID());
        args.put("sd", startDate);
        args.put("ed", endDate);

        q.declareParameters("String k, Date sd, Date ed");
        q.setOrdering("timestamp descending");
        //q.setRange(0,1000);
        List<RecordedValue> data = (List<RecordedValue>) q.executeWithMap(args);
        //ArrayList<Value> values = new ArrayList<Value>();

        //values.addAll(data);

        point.setValues((List<RecordedValue>) pm.detachCopyAll(data));
        
        
        
        ////System.out.println("Get Dsx:" + data.size());




      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    finally
    {
      if (closepm)
      {
        pm.close();
      }
    }

    return points;
  }
  public DataPoint getDataSeries( String pointName, java.util.Date startDate, java.util.Date endDate, long average, PersistenceManager pm)
  {
    NimbitsUser nuser = new UserServiceImpl().GetNimbitsUser(this.getThreadLocalRequest(),"getDataSeries",pm);

    long userFK = nuser.getID();
    ArrayList<DataPoint> pointsFull;
   
    
    
    DataPoint point = new  PointServiceImpl().getPointByName(userFK, pointName, pm );
    ArrayList<DataPoint> points = new ArrayList<DataPoint>();
    points.add(point);
    pointsFull = getDataSeries(points, startDate, endDate, pm);
    return pointsFull.get(0);

  }

  public ArrayList<DataPoint> getDataSeries(ArrayList<DataPoint> points, java.util.Date startDate, java.util.Date endDate, long averageSeconds)
  {


    for (DataPoint point : points) {
      ArrayList<RecordedValue> values = new ArrayList<RecordedValue>();
      Date endCap = new Date(startDate.getTime() + (averageSeconds * 1000));


      if (endCap.getTime() > endDate.getTime())
      {
        RecordedValue avg = getAverage(point, startDate, endDate);
        values.add(avg);
      }
      else
      {
        while (endCap.getTime() <= endDate.getTime())
        {

          RecordedValue avg = getAverage(point, startDate, endCap);
          if (! (avg == null))
          {
            values.add(avg);
          }
          endCap = new Date(endCap.getTime() + (averageSeconds * 1000));
          startDate = new Date(endCap.getTime() + 1000);

        }
        if ((endDate.getTime() - endCap.getTime()) > 0)
        {
          RecordedValue avg = getAverage(point, startDate, endDate);
          if (! (avg == null))
          {
            values.add(avg);
          }
        }

      }


      point.setValues(values);




    }

    return points;
  }
//  public static RecordedValue getPrevValue(DataPoint  point, Date d,  PersistenceManager pm  )  {
//    RecordedValue retObj;
//     
//     retObj = getPrevValue(point,d, pm);
//   
//     return retObj;  
//  }
  @SuppressWarnings("unchecked")
  private static RecordedValue getPrevValue(DataPoint  point, Date d, PersistenceManager pm)  {
   
    Query q = pm.newQuery(RecordedValue.class,
    "pointFK== k  && timestamp <= d");
    q.declareImports("import java.util.Date;");
     Map<String,Object> args = new HashMap<String,Object>();
    args.put("k", point.getID());
    args.put("d", d);
    q.declareParameters("String k, Date d");
    q.setOrdering("timestamp descending");
    q.setRange(0, 1);
    List<RecordedValue> data = (List<RecordedValue>) q.executeWithMap(args);
    RecordedValue dx = null;
    if (data.size() > 0) {
      dx= data.get(0);
    } 
    
    data = null;
    q = null;
    pm = null;
    return dx;
  }
  public RecordedValue getCurrentValue(String pointName, String email, String secret, PersistenceManager pm)   {
    
    
    
    if (Secrets.checkSecret(secret))
      {
      //TODO need to confirm the secret app owns the point
      NimbitsUser nuser = CurrentUser.getNimbitsUser(email, false, "getCurrentValue", pm);
      long userFK = nuser.getID();
      DataPoint p = new  PointServiceImpl().getPointByName(userFK, pointName, pm );
      return getCurrentValue(p, pm);
      }
    else
      return null;
    

    

  }
  public RecordedValue getCurrentValue(String pointName, PersistenceManager pm)   {
    
    NimbitsUser nuser = new UserServiceImpl().GetNimbitsUser(this.getThreadLocalRequest(),"getCurrentValue", pm);
    long userFK = nuser.getID();
    DataPoint p = new  PointServiceImpl().getPointByName(userFK, pointName, pm );

    return getCurrentValue(p);

  }
  public RecordedValue getCurrentValuePublic(String pointName, String ownerEmail, PersistenceManager pm) {
    long userFK;

    DataPoint p=null;
    RecordedValue retObj = null;

    NimbitsUser nuser =CurrentUser.getNimbitsUser(ownerEmail, false,"getCurrentValuePublic", pm);
    // new UserServiceImpl().GetNimbitsUser(this.getThreadLocalRequest());
    if (!(nuser == null))
    {
      userFK = nuser.getID();
       p = PointServiceImpl.getPointByNamePublic(userFK, pointName);
       if (! (p==null))
       {
         retObj = new RecordedValue();
          retObj.setPointFK(p.getId());
          retObj.setTimestamp(p.getLastRecordedTimestamp());
          retObj.setValue(p.getLastRecordedValue());

        // retObj =  getCurrentValue(p);
       }
    }
    else
    {
      retObj = new RecordedValue();
      retObj.setTimestamp(new Date());
      retObj.setValue(-9999);
      
    }
    
    
    

    
    return retObj;
    

  }
  public String getTimeChartURL(ArrayList<DataPoint> points,
      PersistenceManager pm) {
  
    String retStr = "";
    retStr = "http://chart.apis.google.com/chart?";
    retStr += "chs=500x200&cht=lc&chco=3072F3,FF0000&chxt=y&chd=t:";
    
    //http://chart.apis.google.com/chart?chxr=0,-15,100&chxt=y&chs=440x220&cht=lc&chco=3072F3,FF0000&chds=-15,100,-15,100&chd=t:20,30,40,50,60,70,80|5,10,22,35,85&chdl=Ponies|Unicorns&chdlp=b&chg=10,10&chls=2,4,1|1&chma=5,5,5,25
    int high = 0;
    int low = 0;
    
    for (DataPoint p : points)
    {
      p = getTopDataSeries(p, 10,pm);
      for (RecordedValue v : p.getValues())
      {
        retStr += v.getValue() + ",";
        if (v.getValue() > high)
        {
          high = (int) v.getValue();
          
        }
        if (v.getValue() < low)
        {
          low = (int) v.getValue();
          
        }
      }
      retStr = (String) retStr.subSequence(0, retStr.length()-1);
      retStr += "|";
      
    }
    retStr = (String) retStr.subSequence(0, retStr.length()-1);
    retStr += "&chdl=";
    String scaleStr = "";
    
    for (DataPoint p : points)
    {
       
      try {
        retStr += URLEncoder.encode( p.getName(),"UTF-8") + "|";
      } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      scaleStr += low + "," + high + ",";
      
    }
    retStr = (String) retStr.subSequence(0, retStr.length()-1);
    scaleStr = (String) scaleStr.subSequence(0, scaleStr.length()-1);
    retStr += "&chxr=0," + low + "," + high;
  
    //set same scale:
    retStr += "&chds=" + scaleStr;
    retStr += "&chdlp=b&chls=1|1";
    
    return retStr;
  }
   
  private RecordedValue getCurrentValue(DataPoint p, PersistenceManager pm)
  {

    DataPoint x = new PointServiceImpl().getPointByID(p.getId(), pm);
    RecordedValue retObj = new RecordedValue();
    if (x != null)
    {
      retObj.setPointFK(x.getId());
      retObj.setTimestamp(x.getLastRecordedTimestamp());
      retObj.setValue(x.getLastRecordedValue());
      retObj.setNote(x.getLastNote());
      retObj.setLatitude(x.getLastLat());
      retObj.setLongitude(x.getLastLng());
    }
    
    return retObj;


  }

}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.