public function getErrorsProvider()
 {
     $stringSchema = AvroSchema::parse(json_encode(array('type' => 'string')));
     $recordSchema = AvroSchema::parse(json_encode(array('type' => 'record', 'name' => 'ut', 'fields' => array(array('name' => 'id', 'type' => 'int', 'required' => true)))));
     $enumSchema = AvroSchema::parse(json_encode(array('type' => 'record', 'name' => 'ut', 'fields' => array(array('name' => 'count', 'type' => array('int', 'null'))))));
     return array(array('No errors with a simple string serialization', $stringSchema, 'foobar', array()), array('Cannot serialize integer into string', $stringSchema, 5, 'Expected string, but recieved integer'), array('Cannot serialize array into string', $stringSchema, array(), 'Expected string, but recieved array'), array('allows and ignores extra fields', $recordSchema, array('id' => 4, 'foo' => 'bar'), array()), array('detects missing fields', $recordSchema, array(), array('id' => 'Missing expected field')), array('handles first element in enum', $enumSchema, array('count' => 4), array()), array('handles second element in enum', $enumSchema, array('count' => null), array()), array('rejects element not in union', $enumSchema, array('count' => 'invalid'), array('count' => array('Expected any one of these to be true', array('Expected integer, but recieved string', 'Expected null, but recieved string')))));
 }
예제 #2
0
 public function generateAvroCseMessage()
 {
     $collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*');
     $cse_product_details = array();
     foreach ($collection as $p) {
         //$message = array("Items" => array(array("sku" => $p->getSku(), "title" => $p->getName(),"price" => $p->getPrice())) );
         //Mage::log($p);
         // $message = array("Items" => array(array("sku" => $p->getSku(), "title" => $p->getName(),"price" => $p->getPrice())) );
         // 			Mage::log($message);
         $cse_product_detail = array("sku" => $p->getSku(), "title" => $p->getName(), "description" => $p->getDescription(), "manufacturer" => "NA", "MPN" => "NA", "GTIN" => "NA", "brand" => "NA", "category" => "NA", "images" => array(), "link" => $p->getUrlPath(), "condition" => "New", "salePrice" => array("amount" => floatval($p->getPrice()), "code" => "USD"), "originalPrice" => array("amount" => floatval($p->getPrice()), "code" => "USD"), "availability" => "InStock", "taxRate" => array("country" => "US", "region" => "TX", "rate" => 8.5, "taxShipping" => false), "shipping" => array("country" => "US", "region" => "TX", "service" => "UPS", "price" => array("amount" => 3.99, "code" => "USD")), "shippingWeight" => floatval($p->getWeight()), "attributes" => array(), "variations" => array(), "offerId" => "NA", "cpc" => array("amount" => 0.0, "code" => "USD"));
         // Push the product info for the current product into the the $cse_product_details array
         array_push($cse_product_details, $cse_product_detail);
         //Mage::log($cse_product_details);
     }
     $content = file_get_contents("http://workshop.dev/fabric_post/contracts/cse.avpr");
     if ($content == false) {
         echo "Error reading schema!\n";
     }
     // Parse the CSE Avro schema and place results in an AvroSchema object
     $schema = AvroSchema::parse($content);
     // Create an AvroIODataWriter object for the supplied AvroSchema.
     // An AvroIODataWriter object handles schema-specific writing of data to the encoder and
     // ensures that each datum written is consistent with the writer's schema.
     $datum_writer = new AvroIODatumWriter($schema);
     // Create an AvroStringIO object - this is an AvroIO wrapper for string I/O
     $write_io = new AvroStringIO();
     // Create an AvroIOBinaryEncoder object.
     // This object encodes and writes Avro data to the supplied AvroIO object using Avro binary encoding.
     $encoder = new AvroIOBinaryEncoder($write_io);
     // The result is stored in the AvroStringIO object $write_io created above
     $message = array("products" => $cse_product_details, "productFeedType" => "Full");
     $datum_writer->write($message, $encoder);
     Mage::log($message);
     return $write_io->string();
 }
예제 #3
0
 public function saveInventoryData($observer)
 {
     $p = $observer->getEvent()->getProduct();
     // Load the Avro protocol definition
     //shown as an example. we are using the same contract from innovate demo.
     $schema = AvroSchema::parse(file_get_contents("/tmp/innovate_sample.avpr"));
     $datum_writer = new AvroIODatumWriter($schema);
     $write_io = new AvroStringIO();
     $encoder = new AvroIOBinaryEncoder($write_io);
     $attributes = $p->toArray();
     // Set up an item
     $message = array("Items" => array(array("sku" => $p->getSku(), "title" => $p->getName(), "currentPrice" => $p->getPrice(), "url" => $p->getProductUrl(), "dealOfTheDay" => $attributes["deal_of_the_day"])));
     $datum_writer->write($message, $encoder);
     $ch = curl_init();
     // The URL is the host:port for the XFabric, plus the topic
     curl_setopt($ch, CURLOPT_URL, "https://localhost:8080/inventory/updated");
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_HEADER, true);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_TIMEOUT, 10);
     curl_setopt($ch, CURLOPT_POST, 1);
     //note that we are defining schema uri ourselves here for the listening capability
     //for a standard contract message this will be automatically created.
     curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: avro/binary", "Authorization: Bearer QVVUSElELTEA/u4OWAoV2/U2vinS0mC8B22S/ejfKnXRz8tKqtscwB4=", "X-XC-SCHEMA-VERSION: 1.0.0", "X-XC-SCHEMA-URI: http://localhost/Items.avsc"));
     // Our message
     curl_setopt($ch, CURLOPT_POSTFIELDS, $write_io->string());
     $response = curl_exec($ch);
     Mage::log($response);
     $error = curl_error($ch);
     $result = array('header' => '', 'body' => '', 'curl_error' => '', 'http_code' => '', 'last_url' => '');
     if ($error != "") {
         $result['curl_error'] = $error;
     }
     curl_close($ch);
 }
예제 #4
0
 public function getErrorsProvider()
 {
     $stringSchema = AvroSchema::parse(json_encode(['type' => 'string']));
     $stringArraySchema = AvroSchema::parse(json_encode(['type' => 'array', 'items' => 'string']));
     $recordSchema = AvroSchema::parse(json_encode(['type' => 'record', 'name' => 'ut', 'fields' => [['name' => 'id', 'type' => 'int', 'required' => true]]]));
     $enumSchema = AvroSchema::parse(json_encode(['type' => 'record', 'name' => 'ut', 'fields' => [['name' => 'count', 'type' => ['int', 'null']]]]));
     return [['No errors with a simple string serialization', $stringSchema, 'foobar', []], ['Cannot serialize integer into string', $stringSchema, 5, 'Expected string, but recieved integer'], ['Cannot serialize array into string', $stringSchema, [], 'Expected string, but recieved array'], ['allows and ignores extra fields', $recordSchema, ['id' => 4, 'foo' => 'bar'], []], ['detects missing fields', $recordSchema, [], ['id' => 'Missing expected field']], ['handles first element in enum', $enumSchema, ['count' => 4], []], ['handles second element in enum', $enumSchema, ['count' => null], []], ['rejects element not in union', $enumSchema, ['count' => 'invalid'], ['count' => ['Expected any one of these to be true', ['Expected integer, but recieved string', 'Expected null, but recieved string']]]], ['Empty array is accepted', $stringArraySchema, [], []], ['correct array element accepted', $stringArraySchema, ['fizzbuzz'], []], ['incorrect array element rejected', $stringArraySchema, ['12', 34], ['Expected string, but recieved integer']]];
 }
예제 #5
0
    public function testSchemaMatching()
    {
        $writers_schema = <<<JSON
      { "type": "map",
        "values": "bytes" }
JSON;
        $readers_schema = $writers_schema;
        $this->assertTrue(AvroIODatumReader::schemas_match(AvroSchema::parse($writers_schema), AvroSchema::parse($readers_schema)));
    }
예제 #6
0
 /**
  * Decode avro data
  *
  * @param string $text
  * @param string $rawSchema
  * @return mixed
  */
 public function decodeText($text, $rawSchema)
 {
     $schema = AvroSchema::parse($rawSchema);
     $datum_reader = new AvroIODatumReader($schema, $schema);
     $read_io = new AvroStringIO($text);
     $decoder = new AvroIOBinaryDecoder($read_io);
     $results = $datum_reader->read($decoder);
     return $results;
 }
예제 #7
0
function sendPing($message)
{
    // Get variables
    include 'variables.php';
    // Get Avro and encode the message
    include_once 'avro.php';
    $content = file_get_contents($schema_uri);
    $schema = AvroSchema::parse($content);
    $datum_writer = new AvroIODatumWriter($schema);
    $write_io = new AvroStringIO();
    $encoder = new AvroIOBinaryEncoder($write_io);
    $current = "<h2>Sending Ping</h2>" . date('Y-m-d h:i:s') . "\n";
    try {
        $datum_writer->write($message, $encoder);
        $message = $write_io->string();
        try {
            // Set up cURL
            $curl = curl_init();
            // Initiate it
            // Send a header
            curl_setopt($curl, CURLOPT_HEADER, TRUE);
            // Send as POST
            curl_setopt($curl, CURLOPT_POST, TRUE);
            // Don't worry about ssl stuff for now
            // (You'll want to when you've got a full capability up and running)
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            // Stop cURL if it takes longer than 5 seconds
            curl_setopt($curl, CURLOPT_TIMEOUT, 5);
            // Give returned information back to cURL
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
            // Craft cURL data
            // Address XFabric and topic
            curl_setopt($curl, CURLOPT_URL, $fabricURL . "/message/ping");
            // Set message as POST
            curl_setopt($curl, CURLOPT_POSTFIELDS, $message);
            // Set the headers
            curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: " . $authToken, "X-XC-SCHEMA-VERSION: " . $version, "Content-Type: " . $type, "X-XC-DESTINATION-ID: " . $destID, "Content-Length: " . strlen($message)));
            // Send the message
            $result = curl_exec($curl) . "\n";
            // Check that it worked
            if (substr($result, 0, 15) == "HTTP/1.1 200 OK") {
                $current .= "Ping successfully sent! \nMessage:\n" . $message;
            } else {
                $current .= "Error in sending ping. \nResponse: " . $result;
            }
        } catch (Exception $e) {
            // Oh no!  An exception!
            $current .= "Error in script: " . $e;
        }
    } catch (Exception $e) {
        // Oh, no!  An exception!
        $current .= "Message is not able to be avro-encoded!";
    }
    // Write to log file
    file_put_contents($file, $current);
}
예제 #8
0
function cse()
{
    // Open the log file to which to write outputs
    $fp = fopen('test.log', 'at');
    // Get all http headers in the received message
    $headers = getallheaders();
    // Get the posted message body
    // NOTE: The message body is currently in Avro binary form
    $post_data = file_get_contents("php://input");
    // Get the URI of the Avro schema on the OCL server that adheres to the /cse/offer/create contract
    $schema_uri = $headers['X-XC-SCHEMA-URI'];
    // Get the contents of the Avro schema identified by the URI retrieved above
    $content = file_get_contents($schema_uri);
    // Parse the CSE Avro schema and place results in an AvroSchema object
    $schema = AvroSchema::parse($content);
    //fwrite($fp, $schema);
    //fwrite($fp, "\n");
    // Use Avro to decode and deserialize the binary-encoded message body.
    // The result is the plain text version of the message body
    // The message sender used Avro to binary-encode the text version of the message body before sending the message.
    // Create an AvroIODatumReader object for the supplied AvroSchema.
    // An AvroIODatumReader object handles schema-specific reading of data from the decoder and
    // ensures that each datum read is consistent with the reader's schema.
    $datum_reader = new AvroIODatumReader($schema);
    // Create an AvroStringIO object and assign it the encoded message body
    $read_io = new AvroStringIO($post_data);
    // Create an AvroIOBinaryDecoder object and assign it the $read_io object
    $decoder = new AvroIOBinaryDecoder($read_io);
    // Decode and deserialize the data using the CSE schema and the supplied decoder
    // The data is retrieved from the AvroStringIO object $read_io created above
    // Upon return, $message contains the plain text version of the X.commerce message sent by the publisher
    $message = $datum_reader->read($decoder);
    //fwrite($fp, $post_data);
    fwrite($fp, "\n");
    //fwrite($fp, print_r($message, true));
    fwrite($fp, print_r($headers, true));
    // Connect to the Mongo server running on your machine
    // NOTE: you must start the Mongo server prior to running this web application
    $conn = new Mongo('localhost');
    // Access the cse_data database
    // If this database does not exist, Mongo creates it
    $db = $conn->cse_data;
    // Access the google collection
    // If this collection does not exist, Mongo creates it
    $collection = $db->google;
    // Insert a new document into the google collection
    $item = $message["products"];
    $collection->insert($item);
    // Write to log file
    fwrite($fp, print_r($item, true));
    fwrite($fp, "Inserted document with ID: " . $item['_id']);
    fclose($fp);
    // Disconnect from the MongoDB server
    $conn->close();
}
예제 #9
0
 function real_parse($avro)
 {
     $this->protocol = $avro["protocol"];
     $this->namespace = $avro["namespace"];
     $this->schemata = new AvroNamedSchemata();
     $this->name = $avro["protocol"];
     if (!is_null($avro["types"])) {
         $types = AvroSchema::real_parse($avro["types"], $this->namespace, $this->schemata);
     }
     if (!is_null($avro["messages"])) {
         foreach ($avro["messages"] as $messageName => $messageAvro) {
             $message = new AvroProtocolMessage($messageName, $messageAvro, $this);
             $this->messages[$messageName] = $message;
         }
     }
 }
예제 #10
0
 public function test_string_rep()
 {
     $writers_schema_json = '"null"';
     $writers_schema = AvroSchema::parse($writers_schema_json);
     $datum_writer = new AvroIODatumWriter($writers_schema);
     $strio = new AvroStringIO();
     $this->assertEquals('', $strio->string());
     $dw = new AvroDataIOWriter($strio, $datum_writer, $writers_schema_json);
     $dw->close();
     $this->assertEquals(57, strlen($strio->string()), AvroDebug::ascii_string($strio->string()));
     $read_strio = new AvroStringIO($strio->string());
     $datum_reader = new AvroIODatumReader();
     $dr = new AvroDataIOReader($read_strio, $datum_reader);
     $read_data = $dr->data();
     $datum_count = count($read_data);
     $this->assertEquals(0, $datum_count);
 }
예제 #11
0
// Get the headers out of the HTTP request message
$headers = getallheaders();
// Open the log file
$fp = fopen('Twitter_Capability.log', 'at');
// Verify the message came from the Fabric
if ($headers['Authorization'] != FABRIC_CRED_TWITTER) {
    fwrite($fp, "\n\nFATAL ERROR: Authorization header does not contain correct Fabric credentials.\n\n");
    fclose($fp);
    die;
    // terminate this script
}
// Get the URI of the Avro schema from the OCL server. This URI is in the request header X-XC-SCHEMA-URI
$schema_uri = $headers['X-XC-SCHEMA-URI'];
// Deserialize the data in the Middleman's message's body
$content = file_get_contents($schema_uri);
$schema = AvroSchema::parse($content);
$datum_reader = new AvroIODatumReader($schema);
$read_io = new AvroStringIO($post_data);
$decoder = new AvroIOBinaryDecoder($read_io);
$message = $datum_reader->read($decoder);
print $message . "\n\n\n";
//Here process the message and do the Twitter API stuff
/*
        ini_set('max_execution_time', 123456);
system('"C:\wamp\bin\php\php5.3.13\php.exe" -f "C:\wamp\www\filter-track.php" -- "#love" "50" "24"', $retValue);
echo $retValue . "\n";
*/
// Get the full request URI
$request_uri = $_SERVER['REQUEST_URI'];
// Get the topic out of the request URI
if (!($topic = strstr($request_uri, "/com.x.hashtagsale.v1/experimental/StartHTS"))) {
예제 #12
0
 /**
  * @dataProvider schema_examples_provider
  */
 function test_parse($example)
 {
     $schema_string = $example->schema_string;
     try {
         $normalized_schema_string = $example->normalized_schema_string;
         $schema = AvroSchema::parse($schema_string);
         $this->assertTrue($example->is_valid, sprintf("schema_string: %s\n", $schema_string));
         $this->assertEquals($normalized_schema_string, strval($schema));
     } catch (AvroSchemaParseException $e) {
         $this->assertFalse($example->is_valid, sprintf("schema_string: %s\n%s", $schema_string, $e->getMessage()));
     }
 }
예제 #13
0
 /**
  * @param AvroSchema $schema The rules to conform to.
  * @param mixed $datum The value to validate against $schema.
  * @return string|string[] An error or list of errors in the
  *  provided $datum. When no errors exist the empty array is
  *  returned.
  */
 public static function getErrors(AvroSchema $schema, $datum)
 {
     switch ($schema->type) {
         case AvroSchema::NULL_TYPE:
             if (!is_null($datum)) {
                 return self::wrongType('null', $datum);
             }
             return array();
         case AvroSchema::BOOLEAN_TYPE:
             if (!is_bool($datum)) {
                 return self::wrongType('boolean', $datum);
             }
             return array();
         case AvroSchema::STRING_TYPE:
         case AvroSchema::BYTES_TYPE:
             if (!is_string($datum)) {
                 return self::wrongType('string', $datum);
             }
             return array();
         case AvroSchema::INT_TYPE:
             if (!is_int($datum)) {
                 return self::wrongType('integer', $datum);
             }
             if (AvroSchema::INT_MIN_VALUE > $datum || $datum > AvroSchema::INT_MAX_VALUE) {
                 return self::outOfRange(AvroSchema::INT_MIN_VALUE, AvroSchema::INT_MAX_VALUE, $datum);
             }
             return array();
         case AvroSchema::LONG_TYPE:
             if (!is_int($datum)) {
                 return self::wrongType('integer', $datum);
             }
             if (AvroSchema::LONG_MIN_VALUE > $datum || $datum > AvroSchema::LONG_MAX_VALUE) {
                 return self::outOfRange(AvroSchema::LONG_MIN_VALUE, AvroSchema::LONG_MAX_VALUE, $datum);
             }
             return array();
         case AvroSchema::FLOAT_TYPE:
         case AvroSchema::DOUBLE_TYPE:
             if (!is_float($datum) && !is_int($datum)) {
                 return self::wrongType('float or integer', $datum);
             }
             return array();
         case AvroSchema::ARRAY_SCHEMA:
             if (!is_array($datum)) {
                 return self::wrongType('array', $datum);
             }
             $errors = array();
             foreach ($datum as $d) {
                 $result = $this->validate($schema->items(), $d);
                 if ($result) {
                     $errors[] = $result;
                 }
             }
             if ($errors) {
                 return $errors;
             }
             return array();
         case AvroSchema::MAP_SCHEMA:
             if (!is_array($datum)) {
                 return self::wrongType('array', $datum);
             }
             $errors = array();
             foreach ($datum as $k => $v) {
                 if (!is_string($k)) {
                     $errors[] = self::wrongType('string key', $k);
                 }
                 $result = self::getErrors($schema->values(), $v);
                 if ($result) {
                     $errors[$k] = $result;
                 }
             }
             return $errors;
         case AvroSchema::UNION_SCHEMA:
             $errors = array();
             foreach ($schema->schemas() as $schema) {
                 $result = self::getErrors($schema, $datum);
                 if (!$result) {
                     return array();
                 }
                 $errors[] = $result;
             }
             if ($errors) {
                 return array("Expected any one of these to be true", $errors);
             }
             return "No schemas provided to union";
         case AvroSchema::ENUM_SCHEMA:
             if (!in_array($datum, $schema->symbols())) {
                 $symbols = implode(', ', $schema->symbols);
                 return "Expected one of {$symbols} but recieved {$datum}";
             }
             return array();
         case AvroSchema::FIXED_SCHEMA:
             if (!is_string($datum)) {
                 return self::wrongType('string', $datum);
             }
             $len = strlen($datum);
             if ($len !== $schema->size()) {
                 return "Expected string of length {$schema->size()}, " . "but recieved one of length {$len}";
             }
             return array();
         case AvroSchema::RECORD_SCHEMA:
         case AvroSchema::ERROR_SCHEMA:
         case AvroSchema::REQUEST_SCHEMA:
             if (!is_array($datum)) {
                 return self::wrongType('array', $datum);
             }
             $errors = array();
             foreach ($schema->fields() as $field) {
                 $name = $field->name();
                 if (!array_key_exists($name, $datum)) {
                     $errors[$name] = 'Missing expected field';
                     continue;
                 }
                 $result = self::getErrors($field->type(), $datum[$name]);
                 if ($result) {
                     $errors[$name] = $result;
                 }
             }
             return $errors;
         default:
             return "Unknown avro schema type: {$schema->type}";
     }
 }
예제 #14
0
파일: datum.php 프로젝트: wikimedia/avro
 /**
  * @param AvroSchema $writers_schema
  * @param AvroIOBinaryDecoder $decoder
  * @return
  * @throws AvroException
  */
 private function skip_data($writers_schema, $decoder)
 {
     switch ($writers_schema->type()) {
         case AvroSchema::NULL_TYPE:
             return $decoder->skip_null();
         case AvroSchema::BOOLEAN_TYPE:
             return $decoder->skip_boolean();
         case AvroSchema::INT_TYPE:
             return $decoder->skip_int();
         case AvroSchema::LONG_TYPE:
             return $decoder->skip_long();
         case AvroSchema::FLOAT_TYPE:
             return $decoder->skip_float();
         case AvroSchema::DOUBLE_TYPE:
             return $decoder->skip_double();
         case AvroSchema::STRING_TYPE:
             return $decoder->skip_string();
         case AvroSchema::BYTES_TYPE:
             return $decoder->skip_bytes();
         case AvroSchema::ARRAY_SCHEMA:
             return $decoder->skip_array($writers_schema, $decoder);
         case AvroSchema::MAP_SCHEMA:
             return $decoder->skip_map($writers_schema, $decoder);
         case AvroSchema::UNION_SCHEMA:
             return $decoder->skip_union($writers_schema, $decoder);
         case AvroSchema::ENUM_SCHEMA:
             return $decoder->skip_enum($writers_schema, $decoder);
         case AvroSchema::FIXED_SCHEMA:
             return $decoder->skip_fixed($writers_schema, $decoder);
         case AvroSchema::RECORD_SCHEMA:
         case AvroSchema::ERROR_SCHEMA:
         case AvroSchema::REQUEST_SCHEMA:
             return $decoder->skip_record($writers_schema, $decoder);
         default:
             throw new AvroException(sprintf('Uknown schema type: %s', $writers_schema->type()));
     }
 }
예제 #15
0
 /**
  * @param AvroIO $io
  * @param AvroIODatumWriter $datum_writer
  * @param AvroSchema $writers_schema
  */
 public function __construct($io, $datum_writer, $writers_schema = null)
 {
     if (!$io instanceof AvroIO) {
         throw new AvroDataIOException('io must be instance of AvroIO');
     }
     $this->io = $io;
     $this->encoder = new AvroIOBinaryEncoder($this->io);
     $this->datum_writer = $datum_writer;
     $this->buffer = new AvroStringIO();
     $this->buffer_encoder = new AvroIOBinaryEncoder($this->buffer);
     $this->block_count = 0;
     $this->metadata = array();
     if ($writers_schema) {
         $this->sync_marker = self::generate_sync_marker();
         $this->metadata[AvroDataIO::METADATA_CODEC_ATTR] = AvroDataIO::NULL_CODEC;
         $this->metadata[AvroDataIO::METADATA_SCHEMA_ATTR] = strval($writers_schema);
         $this->write_header();
     } else {
         $dfr = new AvroDataIOReader($this->io, new AvroIODatumReader());
         $this->sync_marker = $dfr->sync_marker;
         $this->metadata[AvroDataIO::METADATA_CODEC_ATTR] = $dfr->metadata[AvroDataIO::METADATA_CODEC_ATTR];
         $schema_from_file = $dfr->metadata[AvroDataIO::METADATA_SCHEMA_ATTR];
         $this->metadata[AvroDataIO::METADATA_SCHEMA_ATTR] = $schema_from_file;
         $this->datum_writer->writers_schema = AvroSchema::parse($schema_from_file);
         $this->seek(0, SEEK_END);
     }
 }
예제 #16
0
// Tidy up
$data_writer->close();
// Open $file_name (by default for reading) using the writer's schema
// included in the file
$data_reader = AvroDataIO::open_file($file_name);
echo "from file:\n";
// Read each datum
foreach ($data_reader->data() as $datum) {
    echo var_export($datum, true) . "\n";
}
$data_reader->close();
// Create a data string
// Create a string io object.
$io = new AvroStringIO();
// Create a datum writer object
$writers_schema = AvroSchema::parse($writers_schema_json);
$writer = new AvroIODatumWriter($writers_schema);
$data_writer = new AvroDataIOWriter($io, $writer, $writers_schema);
foreach ($data as $datum) {
    $data_writer->append($datum);
}
$data_writer->close();
$binary_string = $io->string();
// Load the string data string
$read_io = new AvroStringIO($binary_string);
$data_reader = new AvroDataIOReader($read_io, new AvroIODatumReader());
echo "from binary string:\n";
foreach ($data_reader->data() as $datum) {
    echo var_export($datum, true) . "\n";
}
/** Output
예제 #17
0
 public function setUp()
 {
     $interop_schema_file_name = AVRO_INTEROP_SCHEMA;
     $this->projection_json = file_get_contents($interop_schema_file_name);
     $this->projection = AvroSchema::parse($this->projection_json);
 }
예제 #18
0
 public function to_avro()
 {
     $avro = array();
     if (!is_null($this->doc)) {
         $avro["doc"] = $this->doc;
     }
     $avro["request"] = $this->request->to_avro();
     if ($this->is_one_way()) {
         $avro["response"] = "null";
         $avro["one-way"] = true;
     } else {
         if (!is_null($this->response)) {
             $response_type = $this->response->type();
             if (AvroSchema::is_named_type($response_type)) {
                 $response_type = $this->response->qualified_name();
             } else {
                 $response_type = $this->response->to_avro();
             }
             $avro["response"] = $response_type;
         } else {
             throw new AvroProtocolParseException("Message '" . $this->name . "' has no declared response but is not a one-way message.");
         }
         if (!is_null($this->errors)) {
             $avro["errors"] = array();
             foreach ($this->errors->schemas() as $error) {
                 $error_type = $error->type();
                 if (AvroSchema::is_named_type($error_type)) {
                     $error_type = $error->qualified_name();
                 }
                 $avro["errors"][] = $error_type;
             }
             array_shift($avro["errors"]);
             if (count($avro["errors"]) == 0) {
                 unset($avro["errors"]);
             }
         }
     }
     return $avro;
 }
예제 #19
0
    echo $response;
    //handle the message like following.
    // list($headers, $content) = explode("\r\n\r\n", $response, 2);
    //  $schema_uri = F3::get('host_uri')."/sync_schema";
    // // // Deserialize the data in the Ping message's body
    // $content = Web::http('GET '.$schema_uri);
    // $schema = AvroSchema::parse($content);
    // $datum_reader = new AvroIODatumReader($schema);
    // $read_io = new AvroStringIO($content);
    // $decoder = new AvroIOBinaryDecoder($read_io);
    // $message = $datum_reader->read($decoder);
    // echo $message;
});
F3::route('POST /shipper_to_cart', function () {
    $json_schema = Web::http('GET ' . F3::get('SESSION.ship_uri'));
    $avro_schema = AvroSchema::parse($json_schema);
    $datum_writer = new AvroIODatumWriter($avro_schema);
    $write_io = new AvroStringIO();
    $encoder = new AvroIOBinaryEncoder($write_io);
    $ch = curl_init();
    //get around php magic quotes if needed
    //for json_decode to work
    if (get_magic_quotes_gpc()) {
        $d = stripslashes($_POST['json_message']);
    } else {
        $d = $_POST['json_message'];
    }
    $message = json_decode($d, true);
    //$message = array("order" => array("orderID" => "123", "orderType" => "InHouse"));
    $datum_writer->write($message, $encoder);
    curl_setopt($ch, CURLOPT_URL, F3::get('SESSION.ship_topic'));
예제 #20
0
 /**
  * Creates a new AvroNamedSchemata instance of this schemata instance
  * with the given $schema appended.
  * @param AvroNamedSchema schema to add to this existing schemata
  * @returns AvroNamedSchemata
  */
 public function clone_with_new_schema($schema)
 {
     $name = $schema->fullname();
     if (AvroSchema::is_valid_type($name)) {
         throw new AvroSchemaParseException(sprintf('Name "%s" is a reserved type name', $name));
     } else {
         if ($this->has_name($name)) {
             throw new AvroSchemaParseException(sprintf('Name "%s" is already in use', $name));
         }
     }
     $schemata = new AvroNamedSchemata($this->schemata);
     $schemata->schemata[$name] = $schema;
     return $schemata;
 }
예제 #21
0
 public function __construct(AvroProtocol $local_protocol)
 {
     $this->local_protocol = $local_protocol;
     $this->local_hash = $local_protocol->md5();
     $this->protocol_cache[$this->local_hash] = $this->local_protocol;
     $this->handshake_responder_writer = new AvroIODatumWriter(AvroSchema::parse(HANDSHAKE_RESPONSE_SCHEMA_JSON));
     $this->handshake_responder_reader = new AvroIODatumReader(AvroSchema::parse(HANDSHAKE_REQUEST_SCHEMA_JSON));
     $this->meta_writer = new AvroIODatumWriter(AvroSchema::parse('{"type": "map", "values": "bytes"}'));
     $this->meta_reader = new AvroIODatumReader(AvroSchema::parse('{"type": "map", "values": "bytes"}'));
     $this->system_error_schema = AvroSchema::parse('["string"]');
 }