Can't connect custom script to cosmos db using brightzone gremlin-php - php

I'm trying to build an app around the brightzone gremlin php api for cosmos db (free tier). I can get the api to work through the console (with the provided app) but when I try to use my own custom functions to call the exact same methods available in the API class – practically copying the code, which worked through the console) – I get this...
Fatal error: Uncaught TypeError: fwrite(): Argument #1 ($stream) must be of type resource, null given {...}
on line 174 in vendor/brightzone/gremlin-php/src/Connection.php
I'm new to Gremlin in general, and have limited experience using APIs.
Is this some limitation to the free tier, or have I completely misunderstood something?
edit
I decided to test the api with varying degrees of extra setup on my part...
Running the PHP CLI script: connect.php (included in cosmos graph php getting started quickstart) from a browser through xampp gave no errors. I'm seeing a spike in requests in cosmos' dashboard when I do this, so I know it's hitting the database.
The same test through a vhost alias also gave no errors, while hitting the database.
Creating my own function that calls the class and methods results in the fwrite error above.
Initializing the object
This is the same on both the CLI version and my script.
<?php
require_once('define.php');
require_once('vendor/autoload.php');
use \Brightzone\GremlinDriver\Connection;
$db = new Connection([
'host' => HOST,
'username' => USER,
'password' => PASS
,'port' => PORT
// Required parameter
,'ssl' => TRUE
]);
code comparison
Here's the provided CLI script I'm trying to emulate...
function countVertices($db)
{
$query = "g.V().count()";
printf("\t%s\n\tQuery: %s\n", "Counting all the vertices.", $query);
$result = $db->send($query);
if($result)
{
printf("\tNumber of vertices in this graph: %s\n\n", $result[0]);
}
}
This results in an instant readout of the printf commands meant for command line responses, with correct data from the result property of the object, showing it was initialized, and then functioned properly.
but
Here's how I'm trying to call the method...
$query = "g.V().count()";
$result = $db->send($query);
var_dump($result);
The object initializes fine, but calling the send method throws the fwrite error.
Seriously... what am I missing?

I failed to check the END of the CLI php script, which had a "try" catch statement running all the functions. If I had checked, I'd have seen that the open and close methods...
$db->open();
//<--whatever querying here-->
$db->close();
are necessary to get the gremlin driver connected.
It's all working now with:
<?php
require_once('define.php'); //custom script defining credentials as constants
require_once('vendor/autoload.php');
use \Brightzone\GremlinDriver\Connection;
error_reporting(E_ALL ^ E_WARNING);
$db = new Connection([
'host' => HOST,
'username' => USER,
'password' => PASS,
'port' => '443'
// Required parameter
,'ssl' => TRUE
]);
$db->timeout = 0.5;
$db->open();
$query = "g.V().count()";
var_dump($db->send($query));
$db->close();
?>
This prints the correct response.

Related

Symfony2 - Error on prod - Cannot use object of type Symfony\Component\HttpFoundation\Request as array

I have just uploaded my Symfony (2.7) project online and I have a 500 error happening only online in prod environnement (app.php). I have set $kernel = new AppKernel('prod', true); in app.php file in order to see the error message:
Error: Cannot use object of type Symfony\Component\HttpFoundation\Request as array
in vendor/symfony/symfony/src/Symfony/Component/HttpKernel/EventListener/RouterListener.php at line 143
}
if (null !== $this->logger) {
// Below is line 143
$this->logger->info(sprintf('Matched route "%s".', isset($parameters['_route']) ? $parameters['_route'] : 'n/a'), array(
'route_parameters' => $parameters,
'request_uri' => $request->getUri(),
));
(This file is part of Symfony, see complete code here.)
In local (WAMP), I have no issue using app.php or app_dev.php .
Online, app_dev.php is working well but when try to access http://mydomain.fr/web/, I have this error.
I am a bit lost here, if you need more information, just ask me which file or else I should copy in this question.
Just to see what happens I commented the logger line in RouterListener.php, I have another different error showing. I guess there's something wrong with my server's config or something like that... but I have no idea what I should look at.
Some controller code is trying to access values by keys on an object as if it were an Array;
<?php
$moo = (object) ['foo' => 'bar' ];
/* run-time error below: */
$moo['foo'];
This happens when you upgrade "the library" or API without updating client code. It happens also when client code (your code) confuses the order of parameters in function invocations.

DynamoDB PHP Return Value

I am studying how to write php code of DynamoDB now.
I have encounter some problems.
1) How can I know when connect to db fail
$aws = Aws::factory('config.php');
$client = $aws->get('DynamoDb');
Return client is a object, but i don't know how to check connect success or fail in my php code.
2) Same question when i try to putItem, updateItem and deleteItem
$result = $client->putItem(array(
...
));
I read the AWS SDK of PHP document, but I can't find solution.
These function return value is a array(?) and no attribute is mean success or fail.
Only queryItem() can check by 'Count' attribute.
How should I do in my php code to check these ?
Thanks in advance.
Regarding #1, the "connection" should not be treated the same way as a connection to a MySQL database. Requests to DynamoDB are made over HTTP(S), and this does not require that you establish an upfront connection. When you create the client object, you are not making a connection to DynamoDB, you are just configuring an HTTP client that will make requests to DynamoDB.
Regarding #2, I think you should read the SDK's Getting Started Guide, especially the sections on Working with modeled responses and Detecting and handling errors. Basically, if a request succeeds you get a Guzzle\Service\Resource\Model object, which behaves like an array (i.e., implements PHP's ArrayAccess and Traversable interfaces). If the request fails, an exception is thrown. For DynamoDB, that exception will be Aws\DynamoDb\Exception\DynamoDbException.
try {
$result = $client->putItem(array(
'Table' => 'my-table',
// ...
));
} catch (DynamoDbException $e) {
// The PutItem operation failed.
echo $e->getMessage();
}

XML parsing error while installing aws sdk

I am working on installing the aws sdk for PHP on my Windows machine (Win7 64 bit) PHP v 5.5.12.
I tried using all the 3 methods viz Composer,zip and PHAR mentioned here.All the 3 ways give me the same error as below.
Warning: SimpleXMLElement::__construct(): Entity: line 1: parser error : Space required after the Public Identifier in C:\wamp\www\aws-sdk-php-master\src\Aws\Common\Exception\Parser\DefaultXmlExceptionParser.php on line 41
Here's the function which givess the error
public function parse(RequestInterface $request, Response $response)
{
$data = array(
'code' => null,
'message' => null,
'type' => $response->isClientError() ? 'client' : 'server',
'request_id' => null,
'parsed' => null
);
if ($body = $response->getBody(true)) {
$this->parseBody(new \SimpleXMLElement($body), $data); //THIS LINE GIVES ERROR
} else {
$this->parseHeaders($request, $response, $data);
}
return $data;
}
Here is how I try to use it.
error_reporting(E_ALL);
define('AWS_KEY', 'MyAWSKEY');
define('AWS_SECRET_KEY', 'MYSECRETKEY');
define('HOST', 'http://localhost'); //tried changing host to diff values,but don't
//think thats the issue
// require the AWS SDK for PHP library
require 'aws-autoloader.php';
//require '../../aws.phar';
use Aws\S3\S3Client;
// Establish connection with an S3 client.
$client = S3Client::factory(array(
'base_url' => HOST,
'key' => AWS_KEY,
'secret' => AWS_SECRET_KEY
));
$o_iter = $client->getIterator('ListObjects', array(
'Bucket' => 'mybucketname'
));
foreach ($o_iter as $o) {
echo "{$o['Key']}\t{$o['Size']}\t{$o['LastModified']}\n";
}
Heres the stacktrace
[17-Jul-2014 04:19:01 Europe/Paris] PHP Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in C:\wamp\www\aws-sdk-php-master\src\Aws\Common\Exception\Parser\DefaultXmlExceptionParser.php:41
Stack trace:
#0 C:\wamp\www\aws-sdk-php- master\src\Aws\Common\Exception\Parser\DefaultXmlExceptionParser.php(41): SimpleXMLElement- >__construct('<!DOCTYPE HTML ...')
#1 C:\wamp\www\aws-sdk-php-master\src\Aws\S3\Exception\Parser\S3ExceptionParser.php(33): Aws\Common\Exception\Parser\DefaultXmlExceptionParser->parse(Object(Guzzle\Http\Message\Request), Object(Guzzle\Http\Message\Response))
#2 C:\wamp\www\aws-sdk-php-master\src\Aws\Common\Client\ExpiredCredentialsChecker.php(61): Aws\S3\Exception\Parser\S3ExceptionParser->parse(Object(Guzzle\Http\Message\Request), Object(Guzzle\Http\Message\Response))
#3 C:\wamp\www\aws-sdk-php-master\vendor\guzzle\guzzle\src\Guzzle\Plugin\Backoff\AbstractBackoffStrategy.php(39): Aws\Common\Client\ExpiredCredentialsChecker->getDelay(0, Object(Guzzle\Http\Message\Request), Object(Guzzle\Http\Message\Resp in C:\wamp\www\aws-sdk-php-master\src\Aws\Common\Exception\Parser\DefaultXmlExceptionParser.php on line 41
Tried googling it and learnt might be due to magic_quotes in php.ini to be on,but thats not the case,actually I don't have magic_quotes itself in my ini file.
Checked the stack trace and it shows the same error.I am not able to figure out if its a system issue or some configuration problem as I get it for all the methods.
Is this a issue with some configuration? OR I am missing something?
Oh, I see what's going on. You should not be setting the base_url parameter. By setting that value you are telling the SDK to send the requests to your localhost, instead of the actual S3 service. Your localhost is returning HTML, not a XML, which is why SimpleXML is throwing parse errors.
To use S3, you should provide your credentials (key and secret), and optionally a region if you are intentionally not using S3's default region. Do not override the base_url value, which is something that the SDK resolves internally based on its knowledge of the service endpoints.
Note: we also encourage users to use a credential profile profile instead of explicit credentials (key and secret) so you can store your credentials in a file outside of your code and project, in order to prevent accidental credential leaks (e.g., committing credentials into version control). The S3 page in the User Guide walks you through how to properly create the client and provides a link to learn more about the credential file/profile.

Object reference not set to an instance of an object error when trying SOAP call

I am trying to connect to and authenticate with a webservice using SOAP / wsdl, but I constantly get the error:
<b>Fatal error</b>: Uncaught SoapFault exception: [a:InternalServiceFault] Object reference not set to an instance of an object. in /path/install.php:16
Below is my current code:
<?php
header("Content-Type: text/plain");
$userinfo = array(
'Username'=>'test',
'Password'=>'test'
);
$wsdl_url = 'https://ws-e-distribution.kmd.dk/standard/ServiceAutorisation/ServiceAutorisation.svc?wsdl';
$client = new SoapClient($wsdl_url);
print_r($client->__getFunctions());
print_r($client->__getTypes());
//This is the problematic line:
$response = $client->__soapCall('LogOn', array('LogOn' => $userinfo));
var_dump($response);
I have tried every possible way of wrapping the username and password parameters that I could conceive of or find anyone suggesting:
using a custom class
using a stdClass
using SoapVar
using SoapParam
using a simple array
double wrapped array
A lot of combinations of the above.
And I've tried calling the function like $client->__soapCall('LogOn', [milliontries]) as well as $client->LogOn([milliontries])
...nothing works, please help.
Update:
I finally managed to get a different error (that suggests at least I hit upon something slightly less wrong). My code now looks like this:
$response = $client->LogOn(array('logon' => array('Username' => 'test','Password' => 'test')));
Which gives me an error about the LogOnType being unsupported (in Danish, which suggests to me that at least I have some sort of connection to the server now). The username and password array has no effect, I can substitute an empty string and get the same result, the thing that makes the difference is the lowercase logon.
If anyone can set up a working example that gives the error incorrect username or password I will be forever grateful... but any pointers will be much appreciated.
As far as I understand the wsdl gives all the information needed to do this, I'm just too much of a [your_pick] to get it...?
Unbelievable ! It only took nine hours to write these 16 lines of code.
<?php
header("Content-Type: text/plain");
$userinfo = array(
'Username'=>'test',
'Password'=>'test'
);
$wsdl_url = 'https://ws-e-distribution.kmd.dk/standard/ServiceAutorisation/ServiceAutorisation.svc?wsdl';
$client = new SoapClient($wsdl_url, array('trace' => 1, "exception" => 0));
print_r($client->__getFunctions());
print_r($client->__getTypes());
//This actually works ! :) :) :)
$response = $client->LogOn(array('logon' => new SoapVar($userinfo, SOAP_ENC_OBJECT, 'LogOnUsername', 'http://schemas.datacontract.org/2004/07/WebServiceAutorisation.BL')));
var_dump($response);
I was so close several times, and it turned out the namespace (the URL) was the magic bit I was missing. I had been using the namespace from the main wsdl (or no namespace at all) in every attempt at using SoapVar's.
Well now, on to the actual purpose of logging in, probably won't be any easier

How can I confirm PHP MongoDB connection is properly recognizing replica sets?

Using the example from the manual:
$mongo = new Mongo("mongodb://sf2.example.com,ny1.example.com", array("replicaSet" => "myReplSet"));
When I check $mongo, it says it is indeed connected. I thought I could then call $mongo->isMaster() to get replica set details, but that doesn't work. Is that not a proper way of doing this?
isMaster isn't a PHP function (see http://www.php.net/manual/en/class.mongo.php for a list of functions available in the Mongo class). You can do:
$result = $mongo->myDb->command(array("isMaster" => 1));
This runs the isMaster command on the myDb database (it doesn't matter what db you run it on).

Categories