How to process incoming JSON data from connected IoT device - mysql

I need some support with a personal project Im working on. I have a connected device which sends JSON data at a defined interval (every 1 min / 5 min/ 15 mins etc) to a specific IP address on port 8080.
The JSON that is sent is in following format:
{
"MeterSN": “1234”,
"Status": ###,
“Variable1”: “###”,
"Variable2”: “###”,
"Variable3”: ###
}
I have started building a PHP Rest API to process this data but am somehow not able to save the to mySQL.
Here is what I have so far:
meterdata.php
class MeterDataInput{
private $conn;
private $table_name = "meterdata";
public $MeterSN;
public $StatusA;
public $Variable1;
public $Variable2;
public $Variable3;
public function __construct($db){
$this->conn = $db;
}
}
function createMeterRecord(){
$query = "INSERT INTO
" . $this->table_name . "
SET
MeterSN=:MeterSN, Status=:Status, Variable1=:Variable1, Variable2=:Variable2, Variable3=:Variable3";
// prepare query
$stmt = $this->conn->prepare($query);
// sanitize
$this->MeterSN=htmlspecialchars(strip_tags($this->MeterSN));
$this->Status=htmlspecialchars(strip_tags($this->Status));
$this->Variable1=htmlspecialchars(strip_tags($this->Variable1));
$this->Variable2=htmlspecialchars(strip_tags($this->Variable2));
$this->Variable3=htmlspecialchars(strip_tags($this->Variable3));
// bind values
$stmt->bindParam(":MeterSN", $this->MeterSN);
$stmt->bindParam(":Status", $this->Status);
$stmt->bindParam(":Variable1", $this->Variable1);
$stmt->bindParam(":Variable2", $this->Variable2);
$stmt->bindParam(":Variable3", $this->Variable3);
// execute query
if($stmt->execute()){
return true;
}
return false;
}
index.php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// get database connection
include_once 'config/db.php';
// instantiate MeterData object
include_once 'objects/meterdata.php';
$database = new Database();
$db = $database->getConnection();
$meterdata = new MeterDataInput($db);
// get posted data
$data = json_decode(file_get_contents("php://input"));
// make sure data is not empty
if(!empty($data->MeterSN)){
// set product property values
$meterdata->MeterSN = $data->MeterSN;
$meterdata->Status = $data->Status;
$meterdata->Variable1 = $data->Variable1;
$meterdata->Variable2 = $data->Variable2;
$meterdata->Variable3 = $data->Variable3;
// create the meter data entry
if($meterdata->createMeterRecord()){
// set response code - 201 created
http_response_code(201);
// update the status
echo json_encode(array("message" => "Data record was added"));
}
// if unable to create the record
else{
// set response code - 503 service unavailable
http_response_code(503);
// tell the user
echo json_encode(array("message" => "Unable to add record."));
}
}
// data is incomplete
else{
// set response code - 400 bad request
http_response_code(400);
// tell the user
echo json_encode(array("message" => "Unable to create data record. Data is incomplete."));
}
Obviously i also have config.php and db.php
I am not sure where i am going wrong, however I am not able to see the records popupate within mySQL.

Related

Ajax format after submit - Laravel

I'm working on project, I faced some problems
If I fill all fields and then submit there is no problem and it saved to database, but my issue if some field is empty the validation messages error appear in another page as JSON format.
I don't use any AJAX code in my view file.
Here is controller code:
public function store(RegisterRequest $request){
$user = User::create($request->all());
$user->password = Hash::make($request['password']);
if ($request->file('avatar')) {
$image = $request->file('avatar');
$destinationPath = base_path() . '/public/uploads/default';
$path = time() . '_' . Str::random(10) . '.' . $image->getClientOriginalExtension();
$image_resize = Intervention::make($image->getRealPath());
$image_resize->resize(300, 300);
$image_resize->save($destinationPath . '/' . $path);
} else {
$path = $user->avatar;
}
$user->avatar = $path;
$user->save();
return redirect()->route('admin.user.index')->with('message','User created successfully');
And here is RegisterRequest code:
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|confirmed',
'country_code' => 'sometimes|required',
'phone'=>Rule::unique('users','phone')->where(function ($query) {
$query->where('country_code', Request::get('country_code'));
})
];
Can you help me please?
Your errors should be accessible inside blade file with $errors variable which you need to iterate and display the errors.
Link to doc which will help you with the render part - https://laravel.com/docs/7.x/validation#quick-displaying-the-validation-errors
Clearly from doc as well
If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.
https://laravel.com/docs/7.x/validation#creating-form-requests
Also refactor the code a bit as following to run only one query to create a user instead of creating and then updating.
public function store(RegisterRequest $request){
if ($request->hasFile('avatar')) {
//use try catch for image conversion might be a rare case of lib failure
try {
$image = $request->file('avatar');
$destinationPath = base_path() . '/public/uploads/default';
$path = time() . '_' . Str::random(10) . '.' . $image->getClientOriginalExtension();
$image_resize = Intervention::make($image->getRealPath());
$image_resize->resize(300, 300);
$image_resize->save($destinationPath . '/' . $path);
$request->avatar = $path;
} catch(\Exception $e){
//handle skip or report error as per your case
}
}
$request['password'] = Hash::make($request['password']);
$user = User::create($request->all());
return redirect()->route('admin.user.index')->with('message','User created successfully');
}

Arduino UNO, update data in MySQL table

I need to update a record in a MySQL table with Arduino UNO. I want to send data from HC-SR06 sensor to db. Firstly I need to see whether a record is updated or not. I am using Ethernet shield and Arduino UNO.
Here is my Arduino source code:
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 177};
EthernetServer server(80);
String txData ="";
String wname = "sensor1";
void setup()
{
Serial.begin(9600);
Ethernet.begin(mac, ip);
server.begin();
}
void loop()
{
txData = "name="+ wname;
EthernetClient client = server.available();
if (client) {
delay (1000);
Serial.println(" client is ok-->");
boolean current_line_is_blank = true;
while (client.connected())
{
delay (1000);
Serial.println(" client connected-->");
if (client.available())
{
delay (1000);
Serial.println(" client available-->");
Serial.println("Connected to MySQL server. Sending data...");
client.print("POST /update_data.php HTTP/1.1\n");
client.print("Host: 192.168.1.177:80\n");
client.print("Connection: close\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(txData.length());
client.print("\n\n");
client.print(txData);
Serial.println("Successfull");
delay (1000);
}
}
delay(1);
client.stop();
}
}
Here is the update_data.php file:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
echo "dbconnect.php will run";
// Connect to MySQL
include("dbconnect.php");
// Prepare the SQL statement
$query = "update arduino.sensors SET value=1
where name = '$_POST[name]' ";
// Go to the review_data.php (optional)
//header("Location: review_data.php");
if(!#mysql_query($query))
{
echo "&Answer; SQL Error - ".mysql_error();
return;
mysql_close();
}
?>
Here is the dbconnect.php file:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
$Username = "root"; // enter your username for mysql
$Password = "1234"; // enter your password for mysql
$Hostname = "localhost"; // this is usually "localhost" unless your database resides on a different server
$Database = "arduino"; //database name
$dbh = mysql_connect($Hostname , $Username, $Password) or die (mysql_error());;
if (!$dbh){
die('MySQL ERROR: ' . mysql_error());
}
#mysql_select_db($Database) or die ('MySQL Error:'.mysql_error());
?>
Client is started and I see the logs on browser like this, bu sensor1 record is not updated.
name=sensor1POST /update_data.php HTTP/1.1
Host: 192.168.1.177:80
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 12
You are literally sending:
update arduino.sensors SET value=1
where name = '$_POST[name]'
to the database. Unless you have a sensor called $_POST[name] nothing will happen!
You need to send the value of variable $_POST[name] as a parameter. I suggest you research Prepared Statements, as building a query by concatenating strings is open to SQL injection attacks.

How to display data to view from db after insertion? [L5.2]

what I am trying to do here is after the insertion I want to display the data in the same page without refreshing the page
ROUTES
Route::post('viewBook/{bookId}', 'CommentsController#insertcomment');
//there's {bookId} cause of this http://localhost:8000/viewBook/1
CONTROLLER
public function insertcomment(Request $request)
{
$commenter = Auth::user()->id;
$comments = new Comments;
$comments->comment = $request->input('mycomment');
$comments->commenter = $commenter;
$comments->save(); //insert success
//getting the data
$data=DB::table('comments')
->select('comment')
->get();
return response()->json($data,true);
}
You don't need to get the data from DB again, just return inserted Comment object:
$commenter = Auth::user()->id;
$comment = new Comments;
$comment->comment = $request->input('mycomment');
$comment->commenter = $commenter;
$comment->save(); //insert success
return response()->json($comment, true);
In your situation.
In http://localhost:8000/viewBook/1. You should send a AJAX request to Route::post('viewBook/{bookId}', 'CommentsController#insertcomment');
Then get response from server for append to current comments HTML section. The response like #Alexey Mezenin answer

How can I see hidden app data in Google Drive?

I have an Android app that stores my notes in hidden app data. I want to export my notes so the question is simple:
How can I access the hidden app data in Google Drive for a specific app?
Indeed, Google does not let you access this hidden app-data folder directly.
But, if you can get your hands on the app's client ID/client secret/digital signature that is used for authentication against Google's servers - then yes, you can basically emulate the app and access the hidden data in your Google Drive using the Drive API.
How it works in Android
Usually, when an android application wants to access a Google API (such as Drive, Games or Google Sign-In - not all are supported) it communicates with the Google Play services client library, which in turn obtains an access token from Google on behalf of the app. This access token is then sent with each request to the API, so that Google knows who is using it and what he is allowed to do with your account (OAuth 2.0). In order to get this access token for the first time, the Google Play service sends an HTTPS POST request to android.clients.google.com/auth with these fields (along with other details):
Token - a "master token" which identifies the Google account and basically allows full access to it
app - the application package name, such as com.whatsapp
client_sig - the application's digital signature (sent as SHA1)
device - the device's Android ID
service - the scopes (permissions) that the app wants to have
So before we can start using the Drive API in the name of a specific app, we need to know its signature and our account's master token. Fortunately, the signature can be easily extracted from the .apk file:
shell> unzip whatsapp.apk META-INF/*
Archive: whatsapp.apk
inflating: META-INF/MANIFEST.MF
inflating: META-INF/WHATSAPP.SF
inflating: META-INF/WHATSAPP.DSA
shell> cd META-INF
shell> keytool -printcert -file WHATSAPP.DSA # can be CERT.RSA or similar
.....
Certificate fingerprints:
SHA1: 38:A0:F7:D5:05:FE:18:FE:C6:4F:BF:34:3E:CA:AA:F3:10:DB:D7:99
Signature algorithm name: SHA1withDSA
Version: 3
The next thing we need is the master token. This special token is normally received and stored on the device when a new google account is added (for example, when first setting up the phone), by making a similar request to the same URL. The difference is that now the app that's asking for permissions is the Play services app itself (com.google.android.gms), and Google is also given additional Email and Passwd parameters to log in with. If the request is successful, we will get back our master token, which could then be added to the user's app request.
You can read this blogpost for more detailed information about the authentication process.
Putting it all together
Now, we can write a code for authentication using these two HTTP requests directly - a code that can browse any app's files with any Google account. Just choose your favorite programming language and client library. I found it easier with PHP:
require __DIR__ . '/vendor/autoload.php'; // Google Drive API
// HTTPS Authentication
$masterToken = getMasterTokenForAccount("your_username#gmail.com", "your_password");
$appSignature = '38a0f7d505fe18fec64fbf343ecaaaf310dbd799';
$appID = 'com.whatsapp';
$accessToken = getGoogleDriveAccessToken($masterToken, $appID, $appSignature);
if ($accessToken === false) return;
// Initializing the Google Drive Client
$client = new Google_Client();
$client->setAccessToken($accessToken);
$client->addScope(Google_Service_Drive::DRIVE_APPDATA);
$client->addScope(Google_Service_Drive::DRIVE_FILE);
$client->setClientId(""); // client id and client secret can be left blank
$client->setClientSecret(""); // because we're faking an android client
$service = new Google_Service_Drive($client);
// Print the names and IDs for up to 10 files.
$optParams = array(
'spaces' => 'appDataFolder',
'fields' => 'nextPageToken, files(id, name)',
'pageSize' => 10
);
$results = $service->files->listFiles($optParams);
if (count($results->getFiles()) == 0)
{
print "No files found.\n";
}
else
{
print "Files:\n";
foreach ($results->getFiles() as $file)
{
print $file->getName() . " (" . $file->getId() . ")\n";
}
}
/*
$fileId = '1kTFG5TmgIGTPJuVynWfhkXxLPgz32QnPJCe5jxL8dTn0';
$content = $service->files->get($fileId, array('alt' => 'media' ));
echo var_dump($content);
*/
function getGoogleDriveAccessToken($masterToken, $appIdentifier, $appSignature)
{
if ($masterToken === false) return false;
$url = 'https://android.clients.google.com/auth';
$deviceID = '0000000000000000';
$requestedService = 'oauth2:https://www.googleapis.com/auth/drive.appdata https://www.googleapis.com/auth/drive.file';
$data = array('Token' => $masterToken, 'app' => $appIdentifier, 'client_sig' => $appSignature, 'device' => $deviceID, 'google_play_services_version' => '8703000', 'service' => $requestedService, 'has_permission' => '1');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\nConnection: close",
'method' => 'POST',
'content' => http_build_query($data),
'ignore_errors' => TRUE,
'protocol_version'=>'1.1',
//'proxy' => 'tcp://127.0.0.1:8080', // optional proxy for debugging
//'request_fulluri' => true
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if (strpos($http_response_header[0], '200 OK') === false)
{
/* Handle error */
print 'An error occured while requesting an access token: ' . $result . "\r\n";
return false;
}
$startsAt = strpos($result, "Auth=") + strlen("Auth=");
$endsAt = strpos($result, "\n", $startsAt);
$accessToken = substr($result, $startsAt, $endsAt - $startsAt);
return "{\"access_token\":\"" . $accessToken . "\", \"refresh_token\":\"TOKEN\", \"token_type\":\"Bearer\", \"expires_in\":360000, \"id_token\":\"TOKEN\", \"created\":" . time() . "}";
}
function getMasterTokenForAccount($email, $password)
{
$url = 'https://android.clients.google.com/auth';
$deviceID = '0000000000000000';
$data = array('Email' => $email, 'Passwd' => $password, 'app' => 'com.google.android.gms', 'client_sig' => '38918a453d07199354f8b19af05ec6562ced5788', 'parentAndroidId' => $deviceID);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\nConnection: close",
'method' => 'POST',
'content' => http_build_query($data),
'ignore_errors' => TRUE,
'protocol_version'=>'1.1',
//'proxy' => 'tcp://127.0.0.1:8080', // optional proxy for debugging
//'request_fulluri' => true
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if (strpos($http_response_header[0], '200 OK') === false)
{
/* Handle error */
print 'An error occured while trying to log in: ' . $result . "\r\n";
return false;
}
$startsAt = strpos($result, "Token=") + strlen("Token=");
$endsAt = strpos($result, "\n", $startsAt);
$token = substr($result, $startsAt, $endsAt - $startsAt);
return $token;
}
And finally, the results -
Files:
gdrive_file_map (1d9QxgC3p4PTXRm_fkAY0OOuTGAckykmDfFls5bAyE1rp)
Databases/msgstore.db.crypt9 (1kTFG5TmgIGTPJuVynWfhkXxLPgz32QnPJCe5jxL8dTn0)
16467702039-invisible (1yHFaxfmuB5xRQHLyRfKlUCVZDkgT1zkcbNWoOuyv1WAR)
Done.
NOTE: This is an unofficial, hacky solution, and so it might have a few problems. For example, the access token is alive only for one hour, after which it won't be refreshed automatically.
A working example as of September 2020
Note: this is actually an addition for Tomer's answer
Things changed since Tomer's original answer was posted.
Currently, to get the master token and avoid the Error=BadAuthentication, you need two things:
Replace Passwd field with EncryptedPasswd and encrypt its value by RSA with google public key (the exact technique was reversed by some guy) - this can be done using phpseclib.
Make HTTPS connection to Google server with the same SSL/TLS options as in one of the supported Android systems. This includes TLS versions and exact list of supported ciphers in right order. If you change the order or add/remove ciphers you'll get Error=BadAuthentication. It took me a whole day to figure this out...
Luckily, PHP >=7.2 comes with openssl-1.1.1 that has all the necessary ciphers to emulate Android 10 client.
So here is rewriten getMasterTokenForAccount() function that sets the ciphers and uses EncryptedPasswd instead of plain Passwd. And below is encryptPasswordWithGoogleKey() implementation that does the encryption.
phpseclib is necessary and can be installed with composer: composer require phpseclib/phpseclib:~2.0
function getMasterTokenForAccount($email, $password)
{
$url = 'https://android.clients.google.com/auth';
$deviceID = '0000000000000000';
$data = array('Email' => $email, 'EncryptedPasswd' => encryptPasswordWithGoogleKey($email, $password), 'app' => 'com.google.android.gms', 'client_sig' => '38918a453d07199354f8b19af05ec6562ced5788', 'parentAndroidId' => $deviceID);
$options = array(
'ssl' => array(
'ciphers' => 'TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20:ECDH+AESGCM:DH+AESGCM:ECDH+AES:DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!eNULL:!MD5:!DSS'),
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\nConnection: close",
'method' => 'POST',
'content' => http_build_query($data),
'ignore_errors' => TRUE,
'protocol_version'=>'1.1',
//'proxy' => 'tcp://127.0.0.1:8080', // optional proxy for debugging
//'request_fulluri' => true
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if (strpos($http_response_header[0], '200 OK') === false)
{
/* Handle error */
print 'An error occured while trying to log in: ' . $result . "\r\n";
return false;
}
$startsAt = strpos($result, "Token=") + strlen("Token=");
$endsAt = strpos($result, "\n", $startsAt);
$token = substr($result, $startsAt, $endsAt - $startsAt);
return $token;
}
function encryptPasswordWithGoogleKey($email, $password)
{
define('GOOGLE_KEY_B64', 'AAAAgMom/1a/v0lblO2Ubrt60J2gcuXSljGFQXgcyZWveWLEwo6prwgi3iJIZdodyhKZQrNWp5nKJ3srRXcUW+F1BD3baEVGcmEgqaLZUNBjm057pKRI16kB0YppeGx5qIQ5QjKzsR8ETQbKLNWgRY0QRNVz34kMJR3P/LgHax/6rmf5AAAAAwEAAQ==');
$google_key_bin = base64_decode(GOOGLE_KEY_B64);
$modulus_len = unpack('Nl', $google_key_bin)['l'];
$modulus_bin = substr($google_key_bin, 4, $modulus_len);
$exponent_len = unpack('Nl', substr($google_key_bin, 4 + $modulus_len, 4))['l'];
$exponent_bin = substr($google_key_bin, 4 + $modulus_len + 4, $exponent_len);
$modulus = new phpseclib\Math\BigInteger($modulus_bin, 256);
$exponent = new phpseclib\Math\BigInteger($exponent_bin, 256);
$rsa = new phpseclib\Crypt\RSA();
$rsa->loadKey(['n' => $modulus, 'e' => $exponent], phpseclib\Crypt\RSA::PUBLIC_FORMAT_RAW);
$rsa->setEncryptionMode(phpseclib\Crypt\RSA::ENCRYPTION_OAEP);
$rsa->setHash('sha1');
$rsa->setMGFHash('sha1');
$encrypted = $rsa->encrypt("{$email}\x00{$password}");
$hash = substr(sha1($google_key_bin, true), 0, 4);
return strtr(base64_encode("\x00{$hash}{$encrypted}"), '+/', '-_');
}
The user cannot directly access data in the hidden app folders, only the app can access them. This is designed for configuration or other hidden data that the user should not directly manipulate. (The user can choose to delete the data to free up the space used by it.)
The only way the user can get access to it is via some functionality exposed by the specific app.
public void retrieveContents(DriveFile file) {
Task<DriveContents> openFileTask =
getDriveResourceClient().openFile(file, DriveFile.MODE_READ_ONLY);
openFileTask.continueWithTask(new Continuation<DriveContents, Task<Void>>() {
#Override
public Task<Void> then(#NonNull Task<DriveContents> task) throws Exception {
DriveContents contents = task.getResult();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(contents.getInputStream()))) {
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line).append("\n");
}
Log.e("result ", builder.toString());
}
Task<Void> discardTask = MainActivity.this.getDriveResourceClient().discardContents(contents);
// [END drive_android_discard_contents]
return discardTask;
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
public void retrieveContents(DriveFile file) {
Task<DriveContents> openFileTask =
getDriveResourceClient().openFile(file, DriveFile.MODE_READ_ONLY);
openFileTask.continueWithTask(new Continuation<DriveContents, Task<Void>>() {
#Override
public Task<Void> then(#NonNull Task<DriveContents> task) throws Exception {
DriveContents contents = task.getResult();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(contents.getInputStream()))) {
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line).append("\n");
}
Log.e("result ", builder.toString());
}
Task<Void> discardTask = MainActivity.this.getDriveResourceClient().discardContents(contents);
// [END drive_android_discard_contents]
return discardTask;
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
to get all the file in app data try the code
private void listFiles() {
Query query =
new Query.Builder()
.addFilter(Filters.or(Filters.eq(SearchableField.MIME_TYPE, "text/html"),
Filters.eq(SearchableField.MIME_TYPE, "text/plain")))
.build();
getDriveResourceClient()
.query(query)
.addOnSuccessListener(this,
new OnSuccessListener<MetadataBuffer>() {
#Override
public void onSuccess(MetadataBuffer metadataBuffer) {
//mResultsAdapter.append(metadataBuffer);
for (int i = 0; i <metadataBuffer.getCount() ; i++) {
retrieveContents(metadataBuffer.get(i).getDriveId().asDriveFile());
}
}
}
)
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "Error retrieving files", e);
MainActivity.this.finish();
}
});
}
also you can download the content of file bye the following code
public void retrieveContents(DriveFile file) {
Task<DriveContents> openFileTask =
getDriveResourceClient().openFile(file, DriveFile.MODE_READ_ONLY);
openFileTask.continueWithTask(new Continuation<DriveContents, Task<Void>>() {
#Override
public Task<Void> then(#NonNull Task<DriveContents> task) throws Exception {
DriveContents contents = task.getResult();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(contents.getInputStream()))) {
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line).append("\n");
}
Log.e("result ", builder.toString());
}
Task<Void> discardTask = MainActivity.this.getDriveResourceClient().discardContents(contents);
// [END drive_android_discard_contents]
return discardTask;
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}

Zend database connection failure

Ok I am having real difficulty solving this. I'm trying to connect to a mysql database from a zend application and i receive the following error:
Message: No database adapter present
I have checked and double checked the connection credentials and they should be fine. The code should be fine too as it works ok in the development environment. If I deliberately change the password to be incorrect in the development environment, I get exactly the same error, which leads me to believe that maybe this is the case, despite my checking!
Any thoughts would be very welcome. If there's nothing obviously wrong here then maybe I need to look at the server/db/php settings?
Thanks!
Bootstrap code:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initPlaceholders(){
Zend_Session::start();
$this->bootstrap('View');
$view = $this->getResource('View');
$view->doctype('XHTML1_STRICT');
// Set the initial stylesheet:
$view->headLink()->appendStylesheet('/css/global.css');
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->registerNamespace('Pog_');
Zend_Controller_Action_HelperBroker::addPath(
APPLICATION_PATH . '/controllers/helpers',
'Application_Controller_Action_Helper_');
}
}
Config file:
[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0
resources.view[] =
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/"
resources.view.helperPath.View_Helper = APPLICATION_PATH "/views/helpers"
database.adapter = pdo_mysql
database.params.host = localhost
database.params.username = user
database.params.password = password
database.params.dbname = test
DB connection helper:
/**
* Constructor: initialize plugin loader
*
* #return void
*/
public function __construct()
{
try{
$config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', 'production');
$dbAdapter = Zend_Db::factory($config->database);
$dbAdapter->getConnection();
$this->connection = $dbAdapter;
} catch (Zend_Db_Adapter_Exception $e) {
echo 'perhaps a failed login credential, or perhaps the RDBMS is not running';
} catch (Zend_Exception $e) {
echo 'perhaps factory() failed to load the specified Adapter class';
}
}
public function getDbConnection(){
return $this->connection;
}
}
Index:
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . '/../library'),
get_include_path(),
)));
/** Zend_Application */
require_once 'Zend/Application.php';
// Create application, bootstrap, and run
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap()
->run();
Define your database as a resource
resources.db.adapter = pdo_mysql
resources.db.params.host = localhost
resources.db.params.username = user
resources.db.params.password = password
resources.db.params.dbname = test
In your main files you then need to do nothing but initiate a query without having to worry about assigning the database fvrom your config - its done in the inside, the DB resource is always chosen as the default adapter for your database transactions