Sunday, August 10, 2014

Google App Engine and Google Cloud Message - Send-to-sync messages

Code snippet for sending a Send-to-sync messages in GAE


//API_KEY is a public API key created for application in Google Developers Console

Sender sender = new Sender(API_KEY);
  
Message msg = new Message.Builder()
 .addData("New message received", message)
 .collapseKey("key1").build();
 
Result result = sender.send(msg, gcmid),5);

Friday, August 8, 2014

Customising generated endpoint class - DuplicateRestPathException


Was going build a list function derived from the generated one for a custom query. The GPE gave me  a DuplicateRestPathException. The problem was the return object crashed with the generated function. To solve the problem, I declared another path for my list function.

@SuppressWarnings({ "unchecked", "unused" })
@ApiMethod(name = "listEntitiesWithCondition", path="list_entities_with_condition")
public CollectionResponse<Entity> listEntitiesWithCondition(@Named("para") String para)
{
         String queryString = "select from Entity as Entity where blah blah blah";
 return listEntities(para,null,null); //The generated function
}

Data store pricing


Every write bills to your wallet $$$. To avoid any surprise from Google, check this out before you get your engine in full throttle.

https://developers.google.com/appengine/docs/java/datastore/entities#Java_Understanding_write_costs

https://developers.google.com/appengine/pricing

alls to the datastore API result in the following billable operations. Small datastore operations include calls to allocate datastore ids or keys-only queries, and these operations are free. This table shows how calls map to datastore operations:
API CallDatastore Operations
Entity Get (per entity)1 read
New Entity Put (per entity, regardless of entity size)2 writes + 2 writes per indexed property value + 1 write per composite index value
Existing Entity Put (per entity)1 write + 4 writes per modified indexed property value + 2 writes per modified composite index value
Entity Delete (per entity)2 writes + 2 writes per indexed property value + 1 write per composite index value
Query*1 read + 1 read per entity retrieved


When your application executes a Datastore put operation, the Datastore must perform a number of writes to store the entity. Your application is charged for each of these writes. You can see how many writes will be required to store an entity by looking at the data viewer in the SDK Development Console. This section explains how these write costs are calculated.
Every entity requires a minimum of two writes to store: one for the entity itself and another for the built-in EntitiesByKind index, which is used by the query planner to service a variety of queries. In addition, the Datastore maintains two other built-in indexes,EntitiesByProperty and EntitiesByPropertyDesc, which provide efficient scans of entities by single property values in ascending and descending order, respectively. Each of an entity's indexed property values must be written to each of these indexes...



Friday, August 1, 2014

Retrieving Cloud SQL records to Android App over App Engine

The "Generate Endpoint Class" builds code for your App Engine to insert, update, remove and list your entities stored in the Cloud Datastore. I was out of luck to find any samples or functions to build code to connect and store my data in Cloud SQL. And so, I modified those generated code for connecting my Cloud SQL instance instead of Cloud Datastore. It worked like a charm!

/**
   * This method lists all the entities inserted in datastore.
   * It uses HTTP GET method and paging support.
   *
   * @return A CollectionResponse class containing the list of all entities
   * persisted and a cursor to the next page.
   */
  @SuppressWarnings({"unchecked", "unused"})
  @ApiMethod(name = "listNote")
  public CollectionResponse<Note> listNote(
    @Nullable @Named("cursor") String cursorString,
    @Nullable @Named("limit") Integer limit) {

    EntityManager mgr = null;
    Cursor cursor = null;
    List<Note> execute = null;

    /* Code generated by GPE, connecting to the cloud datastore, remarked
     * try{
      mgr = getEntityManager();
      Query query = mgr.createQuery("select from Note as Note");
      if (cursorString != null && cursorString != "") {
        cursor = Cursor.fromWebSafeString(cursorString);
        query.setHint(JPACursorHelper.CURSOR_HINT, cursor);
      }

      if (limit != null) {
        query.setFirstResult(0);
        query.setMaxResults(limit);
      }*/
   
      Note notesql = new Note();
   
      execute  = new ArrayList<Note>();

      /* Code retrieving record from Cloud SQL */
      try {
   
     String  = "jdbc:google:mysql://projectid:sqlinstancename/guestbook?user=root";
   
     //Database connection
     Connection conn = DriverManager.getConnection(url);
   
     //SQL query
     String statement = "select * from entries";        
       
     //Result of SQL query
     ResultSet rs = conn.createStatement().executeQuery(
           statement);
          int i = 0;        
       
          //Loop over the query result
          while (rs.next()) {
       
         //Constructing notesql by Cloud database content
         notesql = new Note();
         notesql.setId(String.valueOf(i));
         notesql.setDescription(rs.getString("content"));
         notesql.setEmailAddress(rs.getString("guestName"));
         //Add notesql to a list for return
         execute.add(notesql);
         i++;
          }
   
      } catch (SQLException e) {
     e.printStackTrace();
   }
   
      //Code generated by GPE for storing query result from cloud data store, remarked
      //execute = (List<Note>) query.getResultList();
      cursor = JPACursorHelper.getCursor(execute);
      if (cursor != null) cursorString = cursor.toWebSafeString();

      // Tight loop for fetching all entities from datastore and accomodate
      // for lazy fetch.
      for (Note obj : execute);
   
      //Code generated by GPE for closing cloud data store connection, remarked
   /* } finally {
      mgr.close();
    }*/

    return CollectionResponse.<Note>builder()
      .setItems(execute)
      .setNextPageToken(cursorString)
      .build();
  }

Applying SMA10/20, SMA20/50 as trading signals

This is the comparison for results before and after applying SMA10/20 and SMA20/50 in the stock trader. Background Trading 3 stock ma...