Exemplo n.º 1
0
  /**
   * Searches a fusion table in user's Google tables.
   *
   * @param tableName name of fusion table to search
   * @param context android context
   * @param accountName name of account
   * @param isDelete whether delete this track
   * @return true means find and delete fusion table
   */
  public static boolean searchFusionTableByTitle(
      String tableName, Context context, String accountName, boolean isDelete) {
    try {
      GoogleAccountCredential credential =
          SendToGoogleUtils.getGoogleAccountCredential(
              context, accountName, SendToGoogleUtils.FUSION_TABLES_SCOPE);
      if (credential == null) {
        return false;
      }
      Fusiontables fusiontables =
          new Fusiontables.Builder(
                  AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential)
              .build();
      List<Table> tables = fusiontables.table().list().execute().getItems();
      for (Iterator<Table> iterator = tables.iterator(); iterator.hasNext(); ) {
        Table table = (Table) iterator.next();
        String title = table.getName();
        if (title.equals(tableName)) {
          if (isDelete) {
            fusiontables.table().delete(table.getTableId()).execute();
          }
          return true;
        }
      }

    } catch (Exception e) {
      Log.d(EndToEndTestUtils.LOG_TAG, "Failed when operate fusion table.", e);
    }
    return false;
  }
  /** Inserts a row in the newly created table for the authenticated user. */
  private static void insertData(String tableId) throws IOException {
    Sql sql =
        fusiontables
            .query()
            .sql(
                "INSERT INTO "
                    + tableId
                    + " (Text,Number,Location,Date) "
                    + "VALUES ("
                    + "'Google Inc', "
                    + "1, "
                    + "'1600 Amphitheatre Parkway Mountain View, "
                    + "CA 94043, USA','"
                    + new DateTime(new Date())
                    + "')");

    try {
      sql.execute();
    } catch (IllegalArgumentException e) {
      // For google-api-services-fusiontables-v1-rev1-1.7.2-beta this exception will always
      // been thrown.
      // Please see issue 545: JSON response could not be deserialized to Sqlresponse.class
      // http://code.google.com/p/google-api-java-client/issues/detail?id=545
    }
  }
  /** Create a table for the authenticated user. */
  private static String createTable() throws IOException {
    View.header("Create Sample Table");

    // Create a new table
    Table table = new Table();
    table.setName(UUID.randomUUID().toString());
    table.setIsExportable(false);
    table.setDescription("Sample Table");

    // Set columns for new table
    table.setColumns(
        Arrays.asList(
            new Column().setName("Text").setType("STRING"),
            new Column().setName("Number").setType("NUMBER"),
            new Column().setName("Location").setType("LOCATION"),
            new Column().setName("Date").setType("DATETIME")));

    // Adds a new column to the table.
    Fusiontables.Table.Insert t = fusiontables.table().insert(table);
    Table r = t.execute();

    View.show(r);

    return r.getTableId();
  }
  /**
   * @param tableId
   * @throws IOException
   */
  private static void showRows(String tableId) throws IOException {
    View.header("Showing Rows From Table");

    Sql sql = fusiontables.query().sql("SELECT Text,Number,Location,Date FROM " + tableId);

    try {
      sql.execute();
    } catch (IllegalArgumentException e) {
      // For google-api-services-fusiontables-v1-rev1-1.7.2-beta this exception will always
      // been thrown.
      // Please see issue 545: JSON response could not be deserialized to Sqlresponse.class
      // http://code.google.com/p/google-api-java-client/issues/detail?id=545
    }
  }
  /** List tables for the authenticated user. */
  private static void listTables() throws IOException {
    View.header("Listing My Tables");

    // Fetch the table list
    Fusiontables.Table.List listTables = fusiontables.table().list();
    TableList tablelist = listTables.execute();

    if (tablelist.getItems() == null || tablelist.getItems().isEmpty()) {
      System.out.println("No tables found!");
      return;
    }

    for (Table table : tablelist.getItems()) {
      View.show(table);
      View.separator();
    }
  }
 //	----------------------------------------------------------------------------------------------------------------
 //      Method:     GetTableId
 //      Inputs:	    none
 //     Outputs:	    none
 // Description:     Get Table ID from Table Nam
 //	----------------------------------------------------------------------------------------------------------------
 private static String GetTableId(String tableName) throws IOException {
   String tid = null; // Set default return
   System.out.println("Get Table ID: " + tableName); // Print header
   // Get the table list
   Fusiontables.Table.List listTables = FusionTables.table().list();
   TableList tablelist = listTables.execute(); //
   // If there are no tables, print that info
   if (tablelist.getItems() == null || tablelist.getItems().isEmpty()) { //
     System.out.println("No tables found!"); //
   } //
   else // Else, loop through tables, find match
   { // If it matches then save the table ID
     for (Table table : tablelist.getItems()) //
     { //
       if (table.getName().equals(tableName)) tid = table.getTableId();
     } // Printout the results of that
     System.out.println(tableName + " - tableId: " + tid); //
   } //
   return tid; // Return the table ID
 }
 /** Deletes a table for the authenticated user. */
 private static void deleteTable(String tableId) throws IOException {
   View.header("Delete Sample Table");
   // Deletes a table
   Delete delete = fusiontables.table().delete(tableId);
   delete.execute();
 }
  //	----------------------------------------------------------------------------------------------------------------
  //      Method:     AddNewEntry
  //      Inputs:	    RF Data Entry (JSON)
  //     Outputs:	    Success = TRUE / Failure = FALSE
  // Description:     Insert new data to table  (executes SQL command)
  //	----------------------------------------------------------------------------------------------------------------
  public boolean AddNewEntry(String json, boolean fusion_tables) {
    boolean status; // Return status (success / failure)

    try // Try to get JSON, and save data to database
    { //
      Gson gson = new GsonBuilder().create(); // Create Gson builder
      RFData RFMember = gson.fromJson(json, RFData.class); // Convert from JSON to RFData
      if (RFMember.XbeeID != -1) // If not default then save data
      {
        // Print debug information to port
        System.out.println(
            "Insert New RF Data into Table - XbeeID: "
                + RFMember.XbeeID
                + ", RSSI: "
                + RFMember.RSSI);

        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sql_string; // Build up SQL string
        sql_string = "INSERT INTO RF_Fields ("; // Insert SQL statement, Table: RF_Fields
        sql_string += "intXbeeID,"; // Field: intXbeeID
        sql_string += "intDeviceID,"; // Field: intDeviceID
        sql_string += "fltRSSI,"; // Field: fltRSSI
        sql_string += "fltLatitude,"; // Field: fltLatitude
        sql_string += "fltLongitude,"; // Field: fltLongitude
        sql_string += "fltYaw,"; // Field: fltYaw
        sql_string += "fltPitch,"; // Field: fltPitch
        sql_string += "fltRoll,"; // Field: fltRoll
        sql_string += "dtSampleDate) "; // Field: dtSampleDate
        sql_string += "VALUES ("; // Values indetifier
        sql_string += RFMember.XbeeID + ","; // Value: XbeeID
        sql_string += RFMember.DeviceID + ","; // Value: DeviceID
        sql_string += RFMember.RSSI + ","; // Value: RSSI
        sql_string += RFMember.Latitude + ","; // Value: Latitude
        sql_string += RFMember.Longitude + ","; // Value: Longitude
        sql_string += RFMember.Yaw + ","; // Value: Yaw
        sql_string += RFMember.Pitch + ","; // Value: Pitch
        sql_string += RFMember.Roll + ","; // Value: Roll
        sql_string += "'" + ft.format(RFMember.SampleDate) + "')";
        System.out.println("SQL: " + sql_string); // Debug print the SQL statement
        //
        Statement stmt = conn.createStatement(); // Build SQL statement
        stmt.execute(sql_string); // Execute the SQL statement
        stmt.close(); // Close the statement
        status = true; // Success

        if (fusion_tables) // Only add to the fusion tables if the flag
        { // is set
          // Add to fusion table
          String tableId = GetTableId("RF Field Data"); // Get the "Customer Data" Table
          sql_string = "INSERT INTO " + tableId + " ("; // Insert SQL statement, Table: Table ID
          sql_string += "XbeeID,"; // Field: intXbeeID
          sql_string += "DeviceID,"; // Field: intDeviceID
          sql_string += "RSSI,"; // Field: fltRSSI
          sql_string += "Location,"; // Field: fltLatitude
          sql_string += "Longitude,"; // Field: fltLongitude
          sql_string += "Yaw,"; // Field: fltYaw
          sql_string += "Pitch,"; // Field: fltPitch
          sql_string += "Roll,"; // Field: fltRoll
          sql_string += "SampleDate) "; // Field: dtSampleDate
          sql_string += "VALUES ("; // Values indetifier
          sql_string += RFMember.XbeeID + ","; // Value: XbeeID
          sql_string += RFMember.DeviceID + ","; // Value: DeviceID
          sql_string += RFMember.RSSI + ","; // Value: RSSI
          sql_string += RFMember.Latitude + ","; // Value: Latitude
          sql_string += RFMember.Longitude + ","; // Value: Longitude
          sql_string += RFMember.Yaw + ","; // Value: Yaw
          sql_string += RFMember.Pitch + ","; // Value: Pitch
          sql_string += RFMember.Roll + ","; // Value: Roll
          sql_string += "'" + ft.format(RFMember.SampleDate) + "')";
          Sql sql = FusionTables.query().sql(sql_string); // Build Fusion Query
          // Try and execute the SQL command
          try //
          { //
            sql.executeAndDownloadTo(System.out); // Execute command, stream to the system.out
          } //
          catch (IllegalArgumentException e) //
          { //
          } //
        }
      } //
      else //
      { //
        System.err.println("AddNewEntry: Invalid JSON data"); // Print the exception data and exit
        status = false; // Failure, invalid JSON or data
      }
    } //
    catch (Exception e) // Exception processing:
    { //
      System.err.println("AddNewEntry: " + e.getMessage()); // Print the exception data and exit
      status = false; // Failure
    } //
    return status; // Return status
  }