/** * Override this method in your own implementation to configure the Cassandra cluster instance. */ protected function initializeCluster() { // contact points can an array or a string, optionally having multiple // comma-separated node host names / IP addresses $contactPoints = $this->container->getParameter('cassandra_cluster.contact_points'); if (!is_array($contactPoints)) { $contactPoints = implode($contactPoints, ','); foreach ($contactPoints as &$contactPoint) { $contactPoint = trim($contactPoint); } } $cluster = \Cassandra::cluster(); if (PHP_VERSION_ID < 50600) { call_user_func_array(array($cluster, "withContactPoints"), $contactPoints); } else { // PHP > 5.6 implements variadic parameters $cluster->withContactPoints(...$contactPoints); } $cluster->withPersistentSessions(true); // always use persistent connections but be explicit about it if ($this->container->hasParameter('cassandra_cluster.credentials.username') && $this->container->hasParameter('cassandra_cluster.credentials.password')) { $username = $this->container->getParameter('cassandra_cluster.credentials.username'); $password = $this->container->getParameter('cassandra_cluster.credentials.password'); $cluster->withCredentials($username, $password); } $this->cluster = $cluster->build(); }
/** * Create the table and client side timestamp session for the timestamp * tests. */ public function setUp() { // Process parent setup steps parent::setUp(); // Create the table $query = "CREATE TABLE {$this->tableNamePrefix} (key int PRIMARY KEY, value_int int)"; $this->session->execute(new SimpleStatement($query)); // Generate the insert and select queries $this->insertQuery = "INSERT INTO {$this->tableNamePrefix} (key, value_int) VALUES (?, ?)"; $this->selectQuery = "SELECT writeTime(value_int) FROM {$this->tableNamePrefix} WHERE key = ?"; // Create the connection for client side timestamps $cluster = \Cassandra::cluster()->withContactPoints(Integration::IP_ADDRESS)->withTimestampGenerator(new TimestampGenerator\Monotonic())->build(); $this->clientSideTimestampSession = $cluster->connect($this->keyspaceName); }
public function testLoadedKeyIsReturned() { $this->cassandra->set('user.john', array('email' => '*****@*****.**', 'name' => 'John Smith', 'age' => 23)); $model = UserModel::load('john'); $this->assertEquals($model->key(), 'john'); }
/** * Prepare Cassandra required configuration and connect to node */ private function _LoadAndConnectToCass() { $cassConf = $this->_config['cassandra']; if (!$cassConf) { throw new Exception('Missing cassandra config'); } $this->_cassandraInst = Cassandra::createInstance(array(array('host' => $cassConf['host'], 'port' => $cassConf['port'], 'use-framed-transport' => $cassConf['use_framed_transport'], 'send-timeout-ms' => $cassConf['send_timeout_ms'], 'receive-timeout-ms' => $cassConf['receive_timeout_ms']))); $this->_cassandraInst->useKeyspace($this->_config['default']['keyspace']); $this->_cassandraInst->setMaxCallRetries(5); }
/** * Inserts a new row or updates an existing one. * * If a key already exists with some columns and you update it, any columns * not listed in the update statement will not be changed or deleted. * * If not set, default consistency level set in the constructor is used. * * You generally do not need to provide a timestamp, it is generated for * you. * * You may optionally provide the time-to-live period in seconds after which * the entry will appear deleted. * * @param string $key Key to set or update * @param array $columns Array of column names and their values * @param integer $consistency Consistency level to use * @param integer $timestamp Optional timestamp to use. * @param integer $timeToLiveSeconds Optional time-to-live period * @throws Exception If something goes wrong */ public function set($key, array $columns, $consistency = null, $timestamp = null, $timeToLiveSeconds = null) { if ($timestamp === null) { $timestamp = CassandraUtil::getTimestamp(); } if ($consistency === null) { $consistency = $this->defaultWriteConsistency; } $mutationMap = array($key => array($this->name => $this->createColumnMutations($columns, $timestamp, $timeToLiveSeconds))); $this->cassandra->call('batch_mutate', $mutationMap, $consistency); }
private function createCassandraDb(Cassandra $storage) { // create the cassandra keyspace and column family $sys = new \phpcassa\SystemManager('localhost:9160'); $sys->create_keyspace('oauth2_test', array("strategy_class" => \phpcassa\Schema\StrategyClass::SIMPLE_STRATEGY, "strategy_options" => array('replication_factor' => '1'))); $sys->create_column_family('oauth2_test', 'auth'); $cassandra = new \phpcassa\Connection\ConnectionPool('oauth2_test', array('127.0.0.1:9160')); $cf = new \phpcassa\ColumnFamily($cassandra, 'auth'); // populate the data $storage->setClientDetails("oauth_test_client", "testpass", "http://example.com", 'implicit password'); $storage->setAccessToken("testtoken", "Some Client", '', time() + 1000); $storage->setAuthorizationCode("testcode", "Some Client", '', '', time() + 1000); $storage->setScope('supportedscope1 supportedscope2 supportedscope3 supportedscope4'); $storage->setScope('defaultscope1 defaultscope2', null, 'default'); $storage->setScope('clientscope1 clientscope2', 'Test Client ID'); $storage->setScope('clientscope1 clientscope2', 'Test Client ID', 'default'); $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Client ID 2'); $storage->setScope('clientscope1 clientscope2', 'Test Client ID 2', 'default'); $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID'); $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID', 'default'); $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Default Scope Client ID 2'); $storage->setScope('clientscope3', 'Test Default Scope Client ID 2', 'default'); $storage->setClientKey('oauth_test_client', $this->getTestPublicKey(), 'test_subject'); $cf->insert("oauth_public_keys:ClientID_One", array('__data' => json_encode(array("public_key" => "client_1_public", "private_key" => "client_1_private", "encryption_algorithm" => "RS256")))); $cf->insert("oauth_public_keys:ClientID_Two", array('__data' => json_encode(array("public_key" => "client_2_public", "private_key" => "client_2_private", "encryption_algorithm" => "RS256")))); $cf->insert("oauth_public_keys:", array('__data' => json_encode(array("public_key" => $this->getTestPublicKey(), "private_key" => $this->getTestPrivateKey(), "encryption_algorithm" => "RS256")))); $cf->insert("oauth_users:testuser", array('__data' => json_encode(array("password" => "password", "email" => "*****@*****.**", "email_verified" => true)))); }
<?php require_once 'vendor/autoload.php'; use CfCommunity\CfHelper\CfHelper; $cfHelper = CfHelper::getInstance(); # Get Cassandra VCAP_SERVICES values $serviceManager = $cfHelper->getServiceManager(); #Cassandra service has to have cassandra in the name $cassandraService = $serviceManager->getService('.*cassandra.*'); $node_ips = $cassandraService->getValue('node_ips'); $username = $cassandraService->getValue('username'); $password = $cassandraService->getValue('password'); #Datastax driver will autoconnect to rest of nodes based off one node connection $node = current($node_ips); #Connects to the Cassandra service $cluster = Cassandra::cluster()->withCredentials($username, $password)->withContactPoints($node)->build(); $session = $cluster->connect(); #Print keyspaces and tables $keyspaces = $session->schema()->keyspaces(); echo "<table border=\"1\">"; echo "<tr><th>Keyspace</th><th>Table</th></tr>"; foreach ($keyspaces as $keyspace) { foreach ($keyspace->tables() as $table) { echo sprintf("<tr><td>%s</td><td>%s</td></tr>\n", $keyspace->name(), $table->name()); } } echo "</table>";
/** * Connects to a Cassandra node. * * @param string $host Host name/IP to connect to. * @param string $user Username in case authentication is needed. * @param string $passwd Password in case authentication is needed. * @param string $dbname Keyspace to use upon connection. * @param int $port Port to connect to. * * @return obj The created object. FALSE if unable to connect. */ function cassandra_connect($host, $user = '', $passwd = '', $dbname = '', $port = 9042) { $obj = new Cassandra(); if ($obj->connect($host, $user, $passwd, $dbname, $port)) { return $obj; } }
/** * Create a new connection instance with the provided configuration */ public function __construct() { // Set up connection details $builder = \Cassandra::cluster(); // Fetch configured port and set it, if it's provided $port = config('cassandra.port'); if (!empty($port)) { $builder->withPort($port); } // Fetch configured default page size and set it, if it's provided $defaultPageSize = config('cassandra.defaultPageSize'); if (!empty($defaultPageSize)) { $builder->withDefaultPageSize($defaultPageSize); } // Fetch configured default consistency level and set it, if it's provided $defaultConsistency = config('cassandra.withDefaultConsistency'); if (!empty($defaultConsistency)) { $builder->withDefaultConsistency($defaultConsistency); } // Set contact end points call_user_func_array([$builder, "withContactPoints"], config('cassandra.contactpoints')); // Connect to cluster $this->cluster = $builder->build(); // Create a connect to the keyspace on cluster $this->session = $this->cluster->connect(config('cassandra.keyspace')); }
public function start() { $this->run('start', '--wait-other-notice', '--wait-for-binary-proto'); $builder = Cassandra::cluster()->withPersistentSessions(false)->withContactPoints('127.0.0.1'); if ($this->ssl || $this->clientAuth) { $sslOptions = Cassandra::ssl()->withTrustedCerts(realpath(__DIR__ . '/ssl/cassandra.pem'))->withVerifyFlags(Cassandra::VERIFY_PEER_CERT)->withClientCert(realpath(__DIR__ . '/ssl/driver.pem'))->withPrivateKey(realpath(__DIR__ . '/ssl/driver.key'), 'php-driver')->build(); $builder->withSSL($sslOptions); } for ($retries = 1; $retries <= 10; $retries++) { try { $this->cluster = $builder->build(); $this->session = $this->cluster->connect(); break; } catch (Cassandra\Exception\RuntimeException $e) { unset($this->session); unset($this->cluster); sleep($retries * 0.4); } } if (!isset($this->session)) { throw new RuntimeException("Unable to initialize a Session, check cassandra logs"); } }
<?php if (!extension_loaded('cassandra')) { die("Unable to load cassandra extension\n"); } try { $cluster = Cassandra::cluster()->withContactPoints('127.0.0.1')->build(); $session = $cluster->connect(); echo "connection success\n"; } catch (Cassandra\Exception $e) { echo "connection failure\n"; echo get_class($e) . ": " . $e->getMessage() . "\n"; }
/** * Updates counter column by some amount defaulting to one. * * @param string $key Key name * @param string $column Column name * @param integer $amount By how much to change the counter value * @param string $superColumn Optional supercolumn name * @param integer $consistency Consistency level to use * @author Madhan Dennis <*****@*****.**> */ public function updateCounter($key, $column, $amount = 1, $superColumn = null, $consistency = null) { $columnParent = $this->createColumnParent($superColumn); $counter = new cassandra_CounterColumn(); $counter->name = CassandraUtil::pack($column, $this->getColumnNameType()); $counter->value = $amount; $this->cassandra->call('add', $key, $columnParent, $counter, $consistency); }
private function createCassandraDb(Cassandra $storage) { // create the cassandra keyspace and column family $sys = new \phpcassa\SystemManager('localhost:9160'); $sys->create_keyspace('oauth2_test', array("strategy_class" => \phpcassa\Schema\StrategyClass::SIMPLE_STRATEGY, "strategy_options" => array('replication_factor' => '1'))); $sys->create_column_family('oauth2_test', 'auth'); // populate the data $storage->setClientDetails("oauth_test_client", "testpass", "http://example.com", 'implicit password'); $storage->setAccessToken("testtoken", "Some Client", '', time() + 1000); $storage->setAuthorizationCode("testcode", "Some Client", '', '', time() + 1000); $storage->setUser("testuser", "password"); $storage->setScope('supportedscope1 supportedscope2 supportedscope3 supportedscope4'); $storage->setScope('defaultscope1 defaultscope2', null, 'default'); $storage->setScope('clientscope1 clientscope2', 'Test Client ID'); $storage->setScope('clientscope1 clientscope2', 'Test Client ID', 'default'); $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Client ID 2'); $storage->setScope('clientscope1 clientscope2', 'Test Client ID 2', 'default'); $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID'); $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID', 'default'); $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Default Scope Client ID 2'); $storage->setScope('clientscope3', 'Test Default Scope Client ID 2', 'default'); $storage->setClientKey('oauth_test_client', $this->getTestPublicKey(), 'test_subject'); }
session_start(); // the only file that needs including into your project require_once 'Cassandra.php'; require_once 'CassandraModel.php'; class UserModel extends CassandraModel { public $email; public $name; public $age; } // list of seed servers to randomly connect to // all the parameters are optional and default to given values $servers = array(array('host' => '127.0.0.1', 'port' => 9160, 'use-framed-transport' => true, 'send-timeout-ms' => 1000, 'receive-timeout-ms' => 1000)); // create a named singleton, the second parameter name defaults to "main" // you can have several named singletons with different server pools $cassandra = Cassandra::createInstance($servers); /* // drop the example keyspace and ignore errors should it not exist try { $cassandra->dropKeyspace('CassandraRowsPaginationExample'); } catch (Exception $e) {} */ // set the default connection for the model CassandraModel::setDefaultConnection($cassandra); try { // start using the created keyspace $cassandra->useKeyspace('CassandraRowsPaginationExample'); } catch (Exception $e) { // create a new keyspace, accepts extra parameters for replication options // normally you don't do it every time $cassandra->createKeyspace('CassandraRowsPaginationExample');
function retrieveRecord($id) { $cluster = Cassandra::cluster()->build(); $session = $cluster->connect('europeana'); $statement = new Cassandra\SimpleStatement(sprintf("SELECT content FROM edm WHERE id = '%s'", $id)); $future = $session->executeAsync($statement); $result = $future->get(); $json = null; foreach ($result as $row) { $json = $row['content']; } return json_decode($json); }
public function testKeysCanBeFetchedByRange2() { $expected = array(); $this->cassandra->truncate('user'); for ($i = ord('a'); $i < ord('z'); $i++) { $testData = array('age' => 50, 'email' => 'test' . $i . '@test.com', 'name' => 'Test #' . $i); $this->cassandra->set('user.test-' . chr($i), $testData); $expected['test-' . chr($i)] = $testData; } $data = $this->cassandra->cf('user')->getKeyRange(); $results = $data->getAll(); $this->assertEquals($expected, $results); }
/** * Create the integration helper instance. * * @param $className Name of the class for the executed test. * @param string $testName Name of the test being executed. * @param int $numberDC1Nodes Number of nodes in data center one * (DEFAULT: 1). * @param int $numberDC2Nodes Number of nodes in data center two * (DEFAULT: 0). * @param int $replicationFactor Replication factor override; default is * calculated based on number of data center * nodes; single data center is (nodes / 2) * rounded up. * @param bool $isClientAuthentication True if client authentication * should be enabled; false * otherwise (DEFAULT: false). * @param bool $isSSL True if SSL should be enabled; false otherwise * (DEFAULT: false). * @return Integration Instance of the Integration class created. */ public function __construct($className, $testName = "", $numberDC1Nodes = 1, $numberDC2Nodes = 0, $replicationFactor = -1, $isClientAuthentication = false, $isSSL = false) { // Generate the keyspace name for the test $this->keyspaceName = $this->getShortName($className); if (!empty($testName)) { $this->keyspaceName = $this->keyspaceName . "_" . $testName; } // Make all strings lowercase for case insensitive O/S (e.g. Windows) $this->keyspaceName = strtolower($this->keyspaceName); //Ensure the keyspace does not contain more to many characters if (strlen($this->keyspaceName) > self::KEYSPACE_MAXIMUM_LENGTH) { // Update the keyspace name with a unique ID $uniqueID = uniqid(); $this->keyspaceName = substr($this->keyspaceName, 0, self::KEYSPACE_MAXIMUM_LENGTH - strlen($uniqueID)) . $uniqueID; } // Create the Cassandra cluster for the test //TODO: Need to add the ability to switch the Cassandra version (command line) $this->ccm = new \CCM(self::CASSANDRA_VERSION, self::IS_CCM_SILENT); $this->ccm->setup($numberDC1Nodes, $numberDC2Nodes); if ($isClientAuthentication) { $this->ccm->setupClientVerification(); } if ($isSSL) { $this->ccm->setupSSL(); } $this->ccm->start(); // Determine replication strategy and generate the query $replicationStrategy = "'SimpleStrategy', 'replication_factor': "; if ($numberDC2Nodes > 0) { $replicationStrategy = "'NetworkTopologyStrategy', 'dc1': " . $numberDC1Nodes . ", " . "'dc2': " . $numberDC2Nodes; } else { if ($replicationFactor < 0) { $replicationFactor = $numberDC1Nodes % 2 == 0 ? $numberDC1Nodes / 2 : ($numberDC1Nodes + 1) / 2; } $replicationStrategy .= $replicationFactor; } $query = sprintf(Integration::SIMPLE_KEYSPACE_FORMAT, $this->keyspaceName, $replicationStrategy); if (self::isDebug() && self::isVerbose()) { fprintf(STDOUT, "Creating Keyspace: %s" . PHP_EOL, $query); } // Create the session and keyspace for the integration test $this->cluster = \Cassandra::cluster()->withContactPoints($this->getContactPoints(Integration::IP_ADDRESS, $numberDC1Nodes + $numberDC2Nodes))->withPersistentSessions(false)->build(); $this->session = $this->cluster->connect(); $statement = new SimpleStatement($query); $this->session->execute($statement); // Update the session to use the new keyspace by default $statement = new SimpleStatement("USE " . $this->keyspaceName); $this->session->execute($statement); // Get the server version the session is connected to $statement = new SimpleStatement(self::SELECT_SERVER_VERSION); $rows = $this->session->execute($statement); $this->serverVersion = $rows->first()["release_version"]; }
/** * Removes an supercolumn entry or some columns of it. * * If the columns is left to null, the entire row is deleted. * * Uses the currently set row key, you can change it with key() method. * * You can remove a row by calling removeSuper() statically. * * @param array $columns Optional columns to delete * @param integer $consistency Option override of default consistency level * @return boolean Was removing the entry successful */ public function deleteSuper($supercolumn, array $columns = null, $consistency = null) { $columnFamily = self::getColumnFamilyName(); $this->_connection->cf($columnFamily)->remove($this->_key, $columns, $supercolumn, $consistency); return true; }
// access column family, using the singleton syntax // there is shorter "cf" methid that is an alias to "columnFamily" $userColumnFamily = Cassandra::getInstance()->columnFamily('user'); echo 'Column family "user": <pre>' . print_r($userColumnFamily, true) . '</pre><hr/>'; // lets insert some test data using the convinience method "set" of Cassandra // the syntax is COLUMN_FAMILY_NAME.KEY_NAME $cassandra->set('user.john', array('email' => '*****@*****.**', 'name' => 'John Smith', 'age' => 34)); // when inserting data, it's ok if key name contains ".", no need to escape them $cassandra->set('user.jane.doe', array('email' => '*****@*****.**', 'name' => 'Jane Doe', 'age' => 24)); // longer way of inserting data, first getting the column family $cassandra->cf('user')->set('chuck', array('email' => '*****@*****.**', 'name' => 'Chuck Norris', 'age' => 24), Cassandra::CONSISTENCY_QUORUM); // lets fetch all the information about user john $john = $cassandra->get('user.john'); echo 'User "john": <pre>' . print_r($john, true) . '</pre><hr/>'; // since the jane key "jane.doe" includes a ".", we have to escape it $jane = $cassandra->get('user.' . Cassandra::escape('jane.doe')); echo 'User "jane.doe": <pre>' . print_r($jane, true) . '</pre><hr/>'; // there is some syntatic sugar on the query of Cassandra::get() allowing you // to fetch specific columns, ranges of them, limit amount etc. for example, // lets only fetch columns name and age $chuck = $cassandra->get('user.chuck:name,age'); echo 'User "chuck", name and age: <pre>' . print_r($chuck, true) . '</pre><hr/>'; // fetch all solumns from age to name (gets all columns in-between too) $chuck2 = $cassandra->get('user.chuck:age-name'); echo 'User "chuck", columns ago to name: <pre>' . print_r($chuck2, true) . '</pre><hr/>'; // the range columns do not need to exist, we can get character ranges $chuck3 = $cassandra->get('user.chuck:a-z'); echo 'User "chuck", columns a-z: <pre>' . print_r($chuck3, true) . '</pre><hr/>'; // when performing range queries, we can also limit the number of columns // returned (2); also the method accepts consistency level as second parameter $chuck4 = $cassandra->get('user.chuck:a-z|2', Cassandra::CONSISTENCY_ALL);
/** * Initialize the SQL datastore. */ protected function __construct() { $config = SimpleSAML_Configuration::getInstance(); $keyspace = $config->getString('store.cassandra.keyspace'); $nodes = $config->getArrayize('store.cassandra.nodes'); $use_ssl = $config->getBoolean('store.cassandra.use_ssl', false); $ssl_ca = $config->getString('store.cassandra.ssl_ca', null); $username = $config->getString('store.cassandra.username', null); $password = $config->getString('store.cassandra.password', null); $cluster = \Cassandra::cluster()->withContactPoints(implode(',', $nodes))->withDefaultConsistency(\Cassandra::CONSISTENCY_LOCAL_QUORUM); if (isset($username) && isset($password)) { $cluster = $cluster->withCredentials($username, $password); } if ($use_ssl) { $ssl = \Cassandra::ssl()->withVerifyFlags(\Cassandra::VERIFY_PEER_CERT); if ($ssl_ca) { $ssl = $ssl->withTrustedCerts($ssl_ca); } $ssl = $ssl->build(); $cluster = $cluster->withSSL($ssl); } $cluster = $cluster->build(); $this->db = $cluster->connect($keyspace); }
<?php // Debug mode ini_set('display_startup_errors', 1); ini_set('display_errors', 1); error_reporting(-1); // Connect to Cassandra $cluster = Cassandra::cluster()->withContactPoints('157.26.83.16')->withPort(9042)->build(); $keyspace = 'twitter'; $session = $cluster->connect($keyspace); // create session, optionally scoped to a keyspace // Default values $tValue = 1; $minVertices = 0; //*************************************/ // Change T //*************************************/ if (isset($_GET["value"])) { $tValue = $_GET["value"]; } //****************************************/ // Change minimum vertices in communities //****************************************/ if (isset($_GET["minVertices"])) { $minVertices = $_GET["minVertices"]; } $whereStatementForVertice = null; if ($minVertices > 0) { $whereStatementForVertice = "and nbv >= {$minVertices}"; } //*************************************/
/** * Schema metadata support can be disabled. * * This test will ensure that the PHP driver supports the ability to enable * and disable the schema metadata when creating a session object. * * @test * @ticket PHP-61 */ public function testDisableSchemaMetadata() { // Create a new session with schema metadata disabled $cluster = \Cassandra::cluster()->withContactPoints(Integration::IP_ADDRESS)->withSchemaMetadata(false)->build(); $session = $cluster->connect(); // Get the schema from the new session $schema = $session->schema(); // Ensure the new session has no schema metadata $this->assertCount(0, $schema->keyspaces()); $this->assertNotEquals($this->schema->keyspaces(), $schema->keyspaces()); }
<html> <head> <meta charset="utf-8"/> <title>Retrieve keyspaces</title> </head> <body> <?php $cluster = Cassandra::cluster()->withContactPoints('10.195.62.172', '10.195.62.173', '10.195.62.174', '10.195.62.175', '10.195.62.176')->build(); $session = $cluster->connect(); echo sprintf("<p>Connected to %s</p>", 'JAO CLUSTER'); $keyspaces = $session->schema()->keyspaces(); #echo "<table border=\"1\">"; #echo "<tr><th>Keyspace</th><th>Table</th></tr>"; #foreach ($keyspaces as $keyspace) { # foreach ($keyspace->tables() as $table) { # echo sprintf("<tr><td>%s</td><td>%s</td></tr>\n", $keyspace->name(), $table->name()); # } #} #echo "</table>"; //$sensores = array("temperature","humidity","dewpoint","windspeed"); // // $idsensor = array_shift($sensores); // foreach( $sensores as $sensor) { // $idsensor = $idsensor . ', ' . $sensor ; // } // unset($sensor); // echo sprintf("Sensores: %s", $idsensor); // echo '<br>'; $initial_year = '2015'; $initial_month = '04';
function getWeatherDataCassandra($start, $end, $format, $idweatherstation, $idsensor, $header = true) { $rawData = ""; $cluster = Cassandra::cluster()->withContactPoints('10.195.62.172', '10.195.62.173', '10.195.62.174', '10.195.62.175', '10.195.62.176')->build(); $session = $cluster->connect() or die("Error connecting to the database"); $access = date("Y/m/d H:i:s"); syslog(LOG_WARNING, "Connected to JAO CLUSTER: {$access} {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})"); $debug = 1; $carry_return = "\r\n"; $initial_year = substr($start, 0, 4); $initial_month = substr($start, 5, 2); $initial_day = substr($start, 8, 2); $final_year = substr($end, 0, 4); $final_month = substr($end, 5, 2); $final_day = substr($end, 8, 2); $keyspace = 'weatherstation'; if (!empty($idsensor) && is_array($idsensor)) { $sensors = array_shift($idsensor); foreach ($idsensor as $sensor) { $sensors = $sensors . ', ' . $sensor; } unset($sensor); } else { die("Sensors NULL"); } if (!empty($idweatherstation) && is_array($idweatherstation)) { foreach ($idweatherstation as $meteo) { $year = $initial_year; $month = round($initial_month, 1); $day = round($initial_day, 1); $less_year = $final_year - $initial_year; $table = "data_" . $year; $query = "SELECT date_full, {$sensors} FROM {$keyspace}.{$table} WHERE weatherstation_id = ? AND date = ?"; $select = $session->prepare("{$query}"); $time_start = microtime(true); while ($less_year >= 0) { if ($month == 13) { $month = 1; } while ($month <= 12) { if ($day == 32) { $day = 1; } while ($day <= 31) { ####################### If month and day < 10 #################### if ($month < 10 && $day < 10) { $date = 0 . $month . '-' . 0 . $day; $options = new Cassandra\ExecutionOptions(array('arguments' => array($meteo, $date))); $result = $session->execute($select, $options); $access = date("Y/m/d H:i:s"); syslog(LOG_WARNING, "CQL executed: {$access} {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})"); foreach ($result as $row) { $rawData .= sprintf("%s; %s; %0.3f; %0.3f; %0.3f; %0.3f; %0.3f; %0.3f\r\n", $meteo, $row['date_full'], $row['temperature'], $row['humidity'], $row['dewpoint'], $row['windspeed'], $row['winddirection'], $row['pressure']); } $access = date("Y/m/d H:i:s"); syslog(LOG_WARNING, "Data retrieved and formatted: {$access} {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})"); } elseif ($month < 10) { $date = 0 . $month . '-' . $day; $options = new Cassandra\ExecutionOptions(array('arguments' => array($meteo, $date))); $result = $session->execute($select, $options); $access = date("Y/m/d H:i:s"); syslog(LOG_WARNING, "CQL executed: {$access} {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})"); foreach ($result as $row) { $rawData .= sprintf("%s; %s; %0.3f; %0.3f; %0.3f; %0.3f; %0.3f; %0.3f\r\n", $meteo, $row['date_full'], $row['temperature'], $row['humidity'], $row['dewpoint'], $row['windspeed'], $row['winddirection'], $row['pressure']); } $access = date("Y/m/d H:i:s"); syslog(LOG_WARNING, "Data retrieved and formatted: {$access} {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})"); } elseif ($day < 10) { $date = $month . '-' . 0 . $day; $options = new Cassandra\ExecutionOptions(array('arguments' => array($meteo, $date))); $result = $session->execute($select, $options); $access = date("Y/m/d H:i:s"); syslog(LOG_WARNING, "CQL executed: {$access} {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})"); foreach ($result as $row) { $rawData .= sprintf("%s; %s; %0.3f; %0.3f; %0.3f; %0.3f; %0.3f; %0.3f\r\n", $meteo, $row['date_full'], $row['temperature'], $row['humidity'], $row['dewpoint'], $row['windspeed'], $row['winddirection'], $row['pressure']); } $access = date("Y/m/d H:i:s"); syslog(LOG_WARNING, "Data retrieved and formatted: {$access} {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})"); } else { $date = $month . '-' . $day; $options = new Cassandra\ExecutionOptions(array('arguments' => array($meteo, $date))); $result = $session->execute($select, $options); $access = date("Y/m/d H:i:s"); syslog(LOG_WARNING, "CQL executed: {$access} {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})"); foreach ($result as $row) { $rawData .= sprintf("%s; %s; %0.3f; %0.3f; %0.3f; %0.3f; %0.3f; %0.3f\r\n", $meteo, $row['date_full'], $row['temperature'], $row['humidity'], $row['dewpoint'], $row['windspeed'], $row['winddirection'], $row['pressure']); } $access = date("Y/m/d H:i:s"); syslog(LOG_WARNING, "Data retrieved and formatted: {$access} {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})"); } $day = $day + 1; if ($month == $final_month) { if ($day == $final_day + 1) { $day = 32; } } } $month = $month + 1; if ($year == $final_year) { if ($month == $final_month + 1) { $month = 13; } } } $year = $year + 1; $less_year = $less_year - 1; } $time_end = microtime(true); } } else { die("WeatherStation NULL"); } $weatherstationName = array_shift($idweatherstation); foreach ($idweatherstation as $weatherstation) { $weatherstationName = $weatherstationName . ', ' . $weatherstation; } unset($weatherstation); $headerData = "# weather station data of : " . $weatherstationName . $carry_return; if ($debug) { $headerData .= "# CQL= " . "SELECT " . $sensors . " FROM weatherstation.data_2015 WHERE weatherstationid = " . $weatherstationName . " AND date >= " . $start . " AND date <= " . $end . $carry_return; } $headerData .= "#" . $carry_return; $headerData .= "# WeatherStation; Date ; Humidity [%]; Temperature [celsius]; Dewpoint [celsius]; Wind Direction [degree]; Wind Speed [m/s]; Pressure [hPa]" . $carry_return; $headerData .= "#" . $carry_return; $execution_time = round($time_end - $time_start, 3); $access = date("Y/m/d H:i:s"); syslog(LOG_WARNING, "Execution Time: {$execution_time} [s], {$access} {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})"); if ($header) { return $headerData . $rawData; } else { return $rawData; } }