pax_global_header00006660000000000000000000000064120730143630014511gustar00rootroot0000000000000052 comment=91abdec96a53acb7173684d8d6594ec7b640a39b node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/000077500000000000000000000000001207301436300211235ustar00rootroot00000000000000node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/.gitignore000066400000000000000000000000331207301436300231070ustar00rootroot00000000000000build deps/* .lock-wscript node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/LICENSE000066400000000000000000000261361207301436300221400ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/Makefile000066400000000000000000000026441207301436300225710ustar00rootroot00000000000000RAPTOR_VERSION=2.0.6 RM=rm -rf WAF=node-waf DEPS_DIR=$(CURDIR)/deps RAPTOR_NAME=raptor2-$(RAPTOR_VERSION) RAPTOR_DIR=$(DEPS_DIR)/$(RAPTOR_NAME) RAPTOR_TARBALL_NAME=$(RAPTOR_NAME).tar.gz RAPTOR_TARBALL=$(DEPS_DIR)/$(RAPTOR_TARBALL_NAME) RAPTOR_URL=http://download.librdf.org/source/$(RAPTOR_TARBALL_NAME) RAPTOR_PREFIX?=$(RAPTOR_DIR)/dist RAPTOR_STATIC_LIB:=$(RAPTOR_PREFIX)/lib/libraptor2.a CFLAGS?=-g -Wall CXXFLAGS?=-g -Wall CFLAGS+=-fPIC CXXFLAGS+=-fPIC export RAPTOR_PREFIX CFLAGS CXXFLAGS # export for waf WGET=@-$(shell command -v curl > /dev/null 2>&1) ifeq ($(WGET),) WGET=wget else WGET=curl -O endif all: bindings bindings: raptor cd src \ && $(WAF) configure \ && $(WAF) build $(RAPTOR_TARBALL): -mkdir $(DEPS_DIR) cd $(DEPS_DIR) \ && $(WGET) $(RAPTOR_URL) $(RAPTOR_DIR): $(RAPTOR_TARBALL) cd $(DEPS_DIR) \ && tar -xzf $(RAPTOR_TARBALL) $(RAPTOR_STATIC_LIB): $(RAPTOR_DIR) cd $(RAPTOR_DIR) \ && ./configure \ --prefix=$(RAPTOR_DIR)/dist \ --enable-static \ --disable-shared \ --disable-gtk-doc-html make install -C $(RAPTOR_DIR) ifeq ($(wildcard $(RAPTOR_STATIC_LIB)),) raptor: $(RAPTOR_STATIC_LIB) else raptor: endif .PHONY: clean clean: clean-bindings clean-raptor clean-bindings: -cd src \ && $(WAF) distclean > /dev/null 2>&1 -$(RM) build > /dev/null 2>&1 clean-raptor: -$(RM) $(RAPTOR_TARBALL) > /dev/null 2>&1 -$(RM) $(RAPTOR_DIR) > /dev/null 2>&1 -$(RM) $(DEPS_DIR) > /dev/null 2>&1 node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/NOTICE000066400000000000000000000002641207301436300220310ustar00rootroot00000000000000This product includes Redland software (http://librdf.org/) developed at the Institute for Learning and Research Technology, University of Bristol, UK (http://www.bristol.ac.uk/). node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/README.mdown000066400000000000000000000067631207301436300231420ustar00rootroot00000000000000Raptor RDF parser and serializer bindings for Node.js ===================================================== Experimental, use at own risk! [Raptor](http://librdf.org/raptor/) is a mature RDF parsing and serializing library written in C by Dave Beckett. It is part of Redland, the RDF handling and storage library. These bindings support [raptor 2](http://librdf.org/raptor/api/) only (v1.9.0 or greater). Building ======== A version of `libraptor2` is downloaded, compiled and statically linked against automatically. If you prefer to use a version of `libraptor2` already installed on your system (e. g. under `/usr/local`), just export RAPTOR_PREFIX=/usr/local General Usage ============= Include raptor bindings with var raptor = require('raptor'); You can create parsers or serializers for certain syntax types like so: var parser = raptor.newParser('rdfxml'); var serializer = raptor.newSerializer('turtle'); API === Parser ------ * `parser.parseFile(pathName [, base]);` Parses file at path `pathName` using optional base URI `base`. * `parser.parseURI(uri [, base]);` Parses RDF date retrieved from `uri` using optional base URI `base`. * `parser.parseStart([base]);` Starts parsing in buffer mode using optional base URI `base`. Buffers can be sent to the parser via `parser.parseBuffer(buffer)`. Calling `parseBuffer()` with no parameter ends buffer parsing mode. * `parser.setOption(optionName, optionValue);` Sets several parsing options (not implemented yet). * `parser.abort();` Aborts the parsing process; 'end' will be emitted. * `parser.name` holds the syntax name that was used with `raptor.newParser` (e. g. 'rdfxml'). Serializer ---------- Emitted Events -------------- On the following conditions, events are emitted: A new statement was parsed -------------------------- parser.on('statement', function (statement) { // do something with statement }); Statements are exposed with the following structure: var statement = { subject: { type: 'uri', /* 'uri' or 'bnode' */ value: 'http://example.com/exampleResource' }, predicate: { type: 'uri', /* always 'uri' */ value: 'http://example.com/exampleProperty' }, object: { type: 'typed-literal', /* 'uri', 'literal', 'typed-literal', or 'bnode' */ value: 'An example literal value', datatype: 'http://www.w3.org/2001/XMLSchema#string' }, toString: function () { /* return statement as N-triples string */ } } A new resource was parsed ------------------------- parser.on('resource', function (r) { // do something with resource }); The resource ### Parsing has ended Either by reaching `EOF`, or by interruption due to `parser.abort()` being called. parser.on('end', function () { // handle end event }); ### A namespace has been declared parser.on('namespace', function (prefix, namespaceURI) { // handle namespace event }); ### A message has been retrieved parser.on('message', function (type, message, code) { // log errors and warnings synchronously if (type == 'error' || type == 'warning') { util.log(type.toUpperCase() + ': ' + message + ' (' + code + ')'); } }); node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/index.js000066400000000000000000000015631207301436300225750ustar00rootroot00000000000000var events = require('events'); var bindings = require(__dirname + '/build/Release/bindings'); function inherits(target, source) { for (var k in source.prototype) target[k] = source.prototype[k]; } exports.newParser = function(mimeType, cb) { if (undefined == cb) { var parser = bindings.newParser(mimeType); inherits(parser, events.EventEmitter); return parser; } else { var res = bindings.newParser(mimeType, function(parser) { inherits(parser, events.EventEmitter); cb(parser); }); } } exports.newSerializer = function(mimeType) { var serializer = null; if (undefined == mimeType) { serializer = bindings.newSerializer(); } else { serializer = bindings.newSerializer(mimeType); } inherits(serializer, events.EventEmitter); return serializer; } node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/package.json000066400000000000000000000012221207301436300234060ustar00rootroot00000000000000{ "name": "raptor", "version": "0.1.0-1", "description": "Node bindings for libraptor2.", "keywords": ["rdf", "turtle", "rdfxml", "libraptor"], "author": { "name": "Norman Heino", "email": "norman.heino@gamil.com" }, "contributors": ["Antonio Garrote"], "bugs": { "url": "http://github.com/0xfeedface/node_raptor/issues" }, "repository": { "type": "git", "url" : "http://github.com/0xfeedface/node_raptor.git" }, "engines": { "node": ">=0.5.0" }, "main": "raptor", "directories": { "lib": "." }, "scripts": { "preinstall": "make", "preuninstall": "make clean" }, "preferGlobal": true } node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/src/000077500000000000000000000000001207301436300217125ustar00rootroot00000000000000node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/src/bindings.cc000066400000000000000000000017211207301436300240170ustar00rootroot00000000000000/* * Copyright 2010 Norman Heino * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "parser.h" #include "serializer.h" using namespace v8; using namespace node; /* extern "C" to prevent name mangling */ extern "C" void init(Handle target) { NODE_SET_METHOD(target, "newParser", Parser::Initialize); NODE_SET_METHOD(target, "newSerializer", Serializer::Initialize); } node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/src/parser.cc000066400000000000000000000357501207301436300235270ustar00rootroot00000000000000/* * Copyright 2010 Norman Heino * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include /* strlen, strcpy */ #include #include #include "statics.h" #include "statement.h" #include "parser.h" Handle Parser::Initialize(const Arguments& args) { HandleScope scope; Handle t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "parseFile", ParseFile); NODE_SET_PROTOTYPE_METHOD(t, "parseURI", ParseURI); NODE_SET_PROTOTYPE_METHOD(t, "parseStart", ParseStart); NODE_SET_PROTOTYPE_METHOD(t, "parseBuffer", ParseBuffer); NODE_SET_PROTOTYPE_METHOD(t, "abort", Abort); NODE_SET_PROTOTYPE_METHOD(t, "setOption", SetOption); t->InstanceTemplate()->SetAccessor(String::NewSymbol("name"), GetName, NULL, Handle(), DEFAULT, ReadOnly); Handle function = t->GetFunction(); Handle *arguments = new Handle [args.Length()]; ExtractArguments(args, arguments); Handle parser = function->NewInstance(args.Length(), arguments); delete arguments; if (args.Length() == 2 && args[1]->IsFunction()) { const int argc = 1; Handle argv[argc] = {parser}; Handle callback = Handle::Cast(args[1]); callback->Call(Context::GetCurrent()->Global(), argc, argv); } return scope.Close(parser); } Handle Parser::New(const Arguments& args) { HandleScope scope; Handle parser_name; if (args.Length() == 0) { parser_name = String::New("rdfxml"); } else { parser_name = args[0]->ToString(); } String::Utf8Value name(parser_name); Parser* parser = new Parser(*name); parser->Wrap(args.This()); return scope.Close(args.This()); } Handle Parser::ParseFile(const Arguments& args) { Parser* parser = ObjectWrap::Unwrap(args.This()); if (!args.Length() >= 1 || !args[0]->IsString()) { return ThrowException(Exception::Error( String::New("First parameter should be filename."))); } HandleScope scope; String::Utf8Value filename(args[0]->ToString()); if (args.Length() >= 2 && args[1]->IsString()) { String::Utf8Value base(args[1]->ToString()); parser->ParseFile(*filename, *base); } else { parser->ParseFile(*filename, NULL); } return Undefined(); } Handle Parser::ParseURI(const Arguments& args) { Parser* parser = ObjectWrap::Unwrap(args.This()); if (args.Length() == 0 || !args[0]->IsString()) { return ThrowException(Exception::Error( String::New("First parameter should be URI."))); } HandleScope scope; String::Utf8Value uri_string(args[0]->ToString()); if (args.Length() >= 2 && args[1]->IsString()) { String::Utf8Value base(args[1]->ToString()); parser->ParseURI(*uri_string, *base); } else { parser->ParseURI(*uri_string, NULL); } return Undefined(); } Handle Parser::ParseStart(const Arguments& args) { Parser* parser = ObjectWrap::Unwrap(args.This()); HandleScope scope; if (!parser->state_ == PARSER_STATE_INIT) { return ThrowException(Exception::Error( String::New("Parsing already started."))); } if (args.Length() >= 1 && args[0]->IsString()) { String::Utf8Value base(args[0]->ToString()); parser->ParseStart(*base); } else { parser->ParseStart(NULL); } parser->state_ = PARSER_STATE_STARTED; return Undefined(); } Handle Parser::ParseBuffer(const Arguments& args) { Parser* parser = ObjectWrap::Unwrap(args.This()); HandleScope scope; if (args.Length() >= 1) { if (!parser->state_ == PARSER_STATE_STARTED) { return ThrowException(Exception::Error( String::New("Parsing a buffer, parseStart needs to be called first."))); } // chunk Handle buffer_h = args[0]; if (!Buffer::HasInstance(buffer_h)) { return ThrowException(Exception::TypeError( String::New("Argument should be a buffer"))); } Handle buffer_obj = buffer_h->ToObject(); char* buffer_data = Buffer::Data(buffer_obj); size_t buffer_length = Buffer::Length(buffer_obj); parser->ParseBuffer(buffer_data, buffer_length, false); parser->state_ = PARSER_STATE_PARSING; } else { // end if (parser->state_ == PARSER_STATE_PARSING) { parser->ParseBuffer(NULL, 0, true); } parser->state_ = PARSER_STATE_INIT; } return Undefined(); } Handle Parser::Abort(const Arguments& args) { Parser* parser = ObjectWrap::Unwrap(args.This()); parser->Abort(); return Undefined(); } Handle Parser::SetOption(const Arguments& args) { if (args.Length() != 2 || !args[0]->IsString() || !(args[1]->IsBoolean() || args[1]->IsString())) { // TODO: exception return Undefined(); } Parser* parser = ObjectWrap::Unwrap(args.This()); String::Utf8Value optionName(args[0]->ToString()); if (args[1]->IsString()) { String::Utf8Value optionValue(args[1]->ToString()); parser->SetOption(*optionName, *optionValue); } else /* if (args[1]->IsBoolean()) */ { parser->SetOption(*optionName, NULL, args[1]->ToBoolean()->Value()); } } Handle Parser::GetName (Local property, const AccessorInfo& info) { Parser* parser = ObjectWrap::Unwrap(info.This()); HandleScope scope; Handle name = String::New(parser->GetName()); return scope.Close(name); } void Parser::CallbackWrapper(void* user_data, raptor_statement* statement) { Parser* p = static_cast(user_data); p->StatementHandler(statement); } void Parser::CallbackWrapper(void* user_data, raptor_namespace* nspace) { Parser* p = static_cast(user_data); p->NamespaceHandler(nspace); } void Parser::CallbackWrapper(void* user_data, raptor_log_message* message) { Parser* p = static_cast(user_data); p->LogMessageHandler(message); } Parser::Parser(const char* name) { if (raptor_world_is_parser_name(world, name)) { size_t name_len = strlen(name); syntax_name_ = new char[name_len+1]; memcpy(syntax_name_, const_cast(name), name_len); // set termination manually syntax_name_[name_len] = '\0'; } else { syntax_name_ = NULL; // will create default parser } raptor_parser* parser = raptor_new_parser(world, syntax_name_); assert(parser != NULL); raptor_parser_set_statement_handler(parser, this, Parser::CallbackWrapper); raptor_parser_set_namespace_handler(parser, this, Parser::CallbackWrapper); parser_ = parser; // log handling per world raptor_world_set_log_handler(world, this, Parser::CallbackWrapper); state_ = PARSER_STATE_INIT; } Parser::~Parser() { if (parser_) { raptor_free_parser(parser_); } if (syntax_name_) { delete syntax_name_; } raptor_world_set_log_handler(world, NULL, NULL); } void Parser::Abort() { if (parser_) { raptor_parser_parse_abort(parser_); } } void Parser::ParseFile(const char* filename, const char* base) { unsigned char* file_uri_string = NULL; file_uri_string = raptor_uri_filename_to_uri_string(filename); raptor_uri* file_uri = NULL; file_uri = raptor_new_uri(world, reinterpret_cast(file_uri_string)); if (file_uri_string) { raptor_free_memory(file_uri_string); } raptor_uri* base_uri = NULL; if (base) { base_uri = raptor_new_uri(world, reinterpret_cast(base)); } assert(parser_ != NULL); raptor_parser_parse_file(parser_, file_uri, base_uri); Local emit_v = this->handle_->Get(String::NewSymbol("emit")); assert(emit_v->IsFunction()); Local emit_f = emit_v.As(); Handle argv[1] = { String::New("end") }; TryCatch tc; emit_f->Call(this->handle_, 1, argv); //Emit(end_symbol, 0, NULL); if (base_uri) { raptor_free_uri(base_uri); } if (file_uri) { raptor_free_uri(file_uri); } if (tc.HasCaught()) FatalException(tc); } void Parser::ParseURI(const char* uri_string, const char* base) { raptor_uri* uri = NULL; uri = raptor_new_uri(world, reinterpret_cast(uri_string)); raptor_uri* base_uri = NULL; if (base) { base_uri = raptor_new_uri(world, reinterpret_cast(base)); } assert(parser_ != NULL); raptor_parser_parse_uri(parser_, uri, base_uri); Local emit_v = this->handle_->Get(String::NewSymbol("emit")); assert(emit_v->IsFunction()); Local emit_f = emit_v.As(); Handle argv[1] = { String::New("end") }; TryCatch tc; emit_f->Call(this->handle_, 1, argv); //Emit(end_symbol, 0, NULL); if (uri) { raptor_free_uri(uri); } if (base_uri) { raptor_free_uri(base_uri); } if (tc.HasCaught()) FatalException(tc); } void Parser::ParseStart(const char* base) { raptor_uri* base_uri = NULL; base_uri = raptor_new_uri(world, reinterpret_cast(base)); assert(parser_ != NULL); raptor_parser_parse_start(parser_, base_uri); if (base_uri) { raptor_free_uri(base_uri); } } void Parser::ParseBuffer(const char* buffer, size_t buffer_length, bool end) { assert(parser_ != NULL); raptor_parser_parse_chunk(parser_, reinterpret_cast(buffer), buffer_length, end); if (end) { Local emit_v = this->handle_->Get(String::NewSymbol("emit")); assert(emit_v->IsFunction()); Local emit_f = emit_v.As(); Handle argv[1] = { String::New("end") }; TryCatch tc; emit_f->Call(this->handle_, 1, argv); if (tc.HasCaught()) FatalException(tc); //Emit(end_symbol, 0, NULL); } } Handle* Parser::ExtractArguments(const Arguments& args, Handle* arguments) { for (int i = 0; i < args.Length(); ++i) { arguments[i] = args[i]; } return arguments; } const char* Parser::GetName() { return syntax_name_; } void Parser::SetOption(const char* option_name, const char* string_option_value) { // set option in parser } void Parser::SetOption(const char* option_name, const char* string_option_value, bool bool_option_value) { // set option in parser } void Parser::StatementHandler(raptor_statement* statement) { HandleScope scope; // unsigned char *s = raptor_term_to_string(statement->subject); // printf("New subject %p %s\n", reinterpret_cast(statement->subject), s); // get new statement object Handle statement_instance = Statement::NewInstance(); // external objects needs to be copied // FIXME: probably leaks raptor_statement* statement_copy = raptor_statement_copy(statement); Handle statement_instance_ptr = External::New(statement_copy); statement_instance->SetInternalField(0, statement_instance_ptr); //Handle args[1]; //args[0] = statement_instance; Local emit_v = this->handle_->Get(String::NewSymbol("emit")); assert(emit_v->IsFunction()); Local emit_f = emit_v.As(); Handle argv[2] = { String::New("statement"), statement_instance }; TryCatch tc; emit_f->Call(this->handle_, 2, argv); if (tc.HasCaught()) FatalException(tc); //Emit(stmt_symbol, 1, args); } void Parser::NamespaceHandler(raptor_namespace* nspace) { raptor_uri* namespace_uri = raptor_namespace_get_uri(nspace); unsigned char* namespace_uri_string = raptor_uri_to_string(namespace_uri); size_t length; const unsigned char* namespace_prefix = raptor_namespace_get_counted_prefix(nspace, &length); HandleScope scope; //Handle args[2]; //args[0] = String::New(reinterpret_cast(namespace_prefix), length); //args[1] = String::New(reinterpret_cast(namespace_uri_string)); if (namespace_uri_string) { raptor_free_memory(namespace_uri_string); } Local emit_v = this->handle_->Get(String::NewSymbol("emit")); assert(emit_v->IsFunction()); Local emit_f = emit_v.As(); Handle argv[3] = { String::New("namespace"), String::New(reinterpret_cast(namespace_prefix), length), String::New(reinterpret_cast(namespace_uri_string)) }; TryCatch tc; emit_f->Call(this->handle_, 3, argv); if (tc.HasCaught()) FatalException(tc); //Emit(nmspc_symbol, 2, args); } void Parser::LogMessageHandler(raptor_log_message* message) { HandleScope scope; Handle type; switch (message->level) { case RAPTOR_LOG_LEVEL_DEBUG: type = debug_symbol; break; case RAPTOR_LOG_LEVEL_INFO: type = info_symbol; break; case RAPTOR_LOG_LEVEL_WARN: type = warn_symbol; break; case RAPTOR_LOG_LEVEL_ERROR: type = error_symbol; break; case RAPTOR_LOG_LEVEL_FATAL: type = fatal_symbol; break; } //Handle args[3]; //args[0] = type; //args[1] = String::New(message->text); //args[2] = Integer::New(message->code); Local emit_v = this->handle_->Get(String::NewSymbol("emit")); assert(emit_v->IsFunction()); Local emit_f = emit_v.As(); Handle argv[4] = { String::New("namespace"), type, String::New(message->text), Integer::New(message->code) }; TryCatch tc; emit_f->Call(this->handle_, 4, argv); if (tc.HasCaught()) FatalException(tc); //Emit(message_symbol, 3, args); } node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/src/parser.h000066400000000000000000000052541207301436300233650ustar00rootroot00000000000000/* * Copyright 2010 Norman Heino * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef NODE_RAPTOR_PARSER_H_ #define NODE_RAPTOR_PARSER_H_ #include #include //#include #include #include "statics.h" enum parser_state { PARSER_STATE_INIT = 0, PARSER_STATE_STARTED, PARSER_STATE_PARSING, }; using namespace v8; using namespace node; //class Parser : public EventEmitter { class Parser : public ObjectWrap { public: static Handle Initialize(const Arguments& args); static Handle New(const Arguments& args); static Handle ParseFile(const Arguments& args); static Handle ParseURI(const Arguments& args); static Handle ParseStart(const Arguments& args); static Handle ParseBuffer(const Arguments& args); static Handle Abort(const Arguments& args); static Handle SetOption(const Arguments& args); static Handle GetName (Local property, const AccessorInfo& info); static void CallbackWrapper(void* user_data, raptor_statement* statement); static void CallbackWrapper(void* user_data, raptor_namespace *nspace); static void CallbackWrapper(void *user_data, raptor_log_message* message); Parser(const char* name); ~Parser(); protected: void Abort(); void ParseFile(const char* filename, const char* base); void ParseURI(const char* uri, const char* base); void ParseStart(const char* base); void ParseBuffer(const char* buffer, size_t buffer_length, bool end); static Handle* ExtractArguments(const Arguments& args, Handle* arguments); const char* GetName(); void SetOption(const char* option_name, const char* string_option_value); void SetOption(const char* option_name, const char* string_option_value, bool bool_option_value); void StatementHandler(raptor_statement* statement); void NamespaceHandler(raptor_namespace *nspace); void LogMessageHandler(raptor_log_message* message); raptor_parser* parser_; char* syntax_name_; parser_state state_; }; #endif node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/src/serializer.cc000066400000000000000000000270021207301436300243730ustar00rootroot00000000000000/* * Copyright 2010 Norman Heino * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include /* strlen, strcpy */ #include #include "serializer.h" #include "statement.h" #include "statics.h" Handle Serializer::Initialize(const Arguments& args) { HandleScope scope; Handle t = FunctionTemplate::New(New); //t->Inherit(EventEmitter::constructor_template); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "serializeToFile", SerializeToFile); NODE_SET_PROTOTYPE_METHOD(t, "serializeStart", SerializeStart); NODE_SET_PROTOTYPE_METHOD(t, "serializeEnd", SerializeEnd); NODE_SET_PROTOTYPE_METHOD(t, "setNamespace", SetNamespace); NODE_SET_PROTOTYPE_METHOD(t, "serializeStatement", SerializeStatement); // NODE_SET_PROTOTYPE_METHOD(t, "setOption", SetOption); t->InstanceTemplate()->SetAccessor(String::NewSymbol("name"), GetName, NULL, Handle(), DEFAULT, ReadOnly); Handle function = t->GetFunction(); Handle *arguments = new Handle [args.Length()]; ExtractArguments(args, arguments); Handle serializer = function->NewInstance(args.Length(), arguments); delete arguments; if (args.Length() == 2 && args[1]->IsFunction()) { const int argc = 1; Handle argv[argc] = {serializer}; Handle callback = Handle::Cast(args[1]); callback->Call(Context::GetCurrent()->Global(), argc, argv); } return scope.Close(serializer); } Handle Serializer::New(const Arguments& args) { HandleScope scope; Handle syntax_name; if (args.Length() == 0) { syntax_name = String::New("rdfxml"); } else { syntax_name = args[0]->ToString(); } String::Utf8Value name(syntax_name); Serializer* serializer = new Serializer(*name); serializer->Wrap(args.This()); return scope.Close(args.This()); } Handle Serializer::SerializeToFile(const Arguments& args) { Serializer* serializer = ObjectWrap::Unwrap(args.This()); HandleScope scope; if (serializer->state_ != SERIALIZER_STATE_INIT) { return ThrowException(Exception::Error( String::New("Previous serialization needs to be finished first."))); } if (!args.Length() >= 1 || !args[0]->IsString()) { return ThrowException(Exception::Error( String::New("First parameter should be filename."))); } String::Utf8Value filename(args[0]->ToString()); serializer->SerializeToFile(*filename); serializer->state_ = SERIALIZER_STATE_SERIALIZING; return Undefined(); } Handle Serializer::SerializeStart(const Arguments& args) { Serializer* serializer = ObjectWrap::Unwrap(args.This()); HandleScope scope; if (serializer->state_ != SERIALIZER_STATE_INIT) { return ThrowException(Exception::Error( String::New("Previous serialization needs to be finished first."))); } if (!args.Length() == 1 || !args[0]->IsString()) { // return ThrowException(Exception::Error( // String::New("First parameter should be base URI."))); serializer->SerializeStart(NULL); } else { Handle base_h = args[0]->ToString(); String::Utf8Value base(base_h); serializer->SerializeStart(*base); } serializer->state_ = SERIALIZER_STATE_SERIALIZING; return Undefined(); } Handle Serializer::SerializeEnd(const Arguments& args) { Serializer* serializer = ObjectWrap::Unwrap(args.This()); if (serializer->state_ != SERIALIZER_STATE_SERIALIZING) { return ThrowException(Exception::Error( String::New("Non serialization to end."))); } serializer->SerializeEnd(); serializer->state_ = SERIALIZER_STATE_INIT; return Undefined(); } Handle Serializer::SetNamespace(const Arguments& args) { Serializer* serializer = ObjectWrap::Unwrap(args.This()); HandleScope scope; if (!args.Length() == 2 || !args[0]->IsString() || !args[1]->IsString()) { return Undefined(); } Handle prefix = args[0]->ToString(); Handle nspace = args[1]->ToString(); String::Utf8Value prefix_s(prefix); String::Utf8Value nspace_s(nspace); serializer->SetNamespace(*prefix_s, *nspace_s); return Undefined(); } Handle Serializer::SerializeStatement(const Arguments& args) { Serializer* serializer = ObjectWrap::Unwrap(args.This()); if (serializer->state_ != SERIALIZER_STATE_SERIALIZING) { return ThrowException(Exception::Error( String::New("Serialization must be started first."))); } HandleScope scope; if (!args.Length() == 1 || !args[0]->IsObject()) { ThrowException(Exception::Error(String::New("First should be a JSON triples structure."))); return Undefined(); } Handle statement_object = args[0]->ToObject(); if (!statement_object->HasRealNamedProperty(subject_symbol)) { ThrowException(Exception::Error(String::New("Statement is missing 'subject' key."))); return Undefined(); } if (!statement_object->HasRealNamedProperty(pred_symbol)) { ThrowException(Exception::Error(String::New("Statement is missing 'predicate' key."))); return Undefined(); } if (!statement_object->HasRealNamedProperty(object_symbol)) { ThrowException(Exception::Error(String::New("Statement is missing 'object' key."))); return Undefined(); } raptor_statement* statement = Statement::ConvertObjectToRaptorStatement(statement_object); if (!statement) { ThrowException(Exception::Error(String::New("Unable to create statement."))); return Undefined(); } serializer->SerializeStatement(statement); raptor_free_statement(statement); return Undefined(); } Handle Serializer::GetName(Local property, const AccessorInfo& info) { Serializer* serializer = ObjectWrap::Unwrap(info.This()); HandleScope scope; Handle name = String::New(serializer->GetName()); return scope.Close(name); } Serializer::Serializer(const char* syntax_name) { // keep syntax name; actual serializer is created lazily if (raptor_world_is_serializer_name(world, syntax_name) > 0) { #pragma unused (syntax_name_len) size_t syntax_name_len = strlen(syntax_name); syntax_name_ = new char[strlen(syntax_name)+1]; strcpy(syntax_name_, const_cast(syntax_name)); } else { syntax_name_ = NULL; } state_ = SERIALIZER_STATE_INIT; } Serializer::~Serializer() { if (serializer_) { // FIXME: segfaults for some reason // raptor_free_serializer(serializer_); } if (syntax_name_) { delete syntax_name_; } // deregister log handler raptor_world_set_log_handler(world, NULL, NULL); } void Serializer::SerializeToFile(const char* filename) { assert(state_ == SERIALIZER_STATE_INIT); serializer_ = raptor_new_serializer(world, syntax_name_); assert(serializer_ != NULL); assert(filename != NULL); raptor_serializer_start_to_filename(serializer_, filename); } void Serializer::SerializeStart(const char* base) { assert(state_ == SERIALIZER_STATE_INIT); assert(world != NULL); assert(raptor_world_is_serializer_name(world, syntax_name_) > 0); serializer_ = raptor_new_serializer(world, syntax_name_); if (!serializer_) { ThrowException(Exception::Error( String::New("Could not create serializer for syntax name"))); return; } assert(serializer_ != NULL); raptor_iostream* iostream = NULL; iostream = raptor_new_iostream_to_string(world, reinterpret_cast(&statement_string_), &statement_string_length_, malloc); if (!iostream) { return;/* ThrowException(Exception::Error( String::New("Error creating serialization stream."))); */ } raptor_uri* base_uri = NULL; if (base) { base_uri = raptor_new_uri(world, reinterpret_cast(base)); } assert(iostream != NULL); raptor_serializer_start_to_iostream(serializer_, base_uri, iostream); if (base_uri) { raptor_free_uri(base_uri); } statement_stream_ = iostream; } void Serializer::SerializeEnd() { assert(state_ == SERIALIZER_STATE_SERIALIZING); assert(serializer_ != NULL); raptor_serializer_serialize_end(serializer_); if (statement_stream_) { raptor_free_iostream(statement_stream_); } HandleScope scope; // TODO: make external? Handle data; if (statement_string_) { data = String::New(reinterpret_cast(statement_string_), statement_string_length_); free(statement_string_); statement_string_ = NULL; } //Handle args[1]; //args[0] = data; // TODO: serialize in chunks w/ raptor_new_iostream_from_handler? Local emit_v = this->handle_->Get(String::NewSymbol("emit")); assert(emit_v->IsFunction()); Local emit_f = emit_v.As(); Handle argv[2] = { String::New("data"), data }; TryCatch tc; emit_f->Call(this->handle_, 2, argv); if (tc.HasCaught()) FatalException(tc); Handle argv2[1] = { String::New("end") }; TryCatch tc2; emit_f->Call(this->handle_, 1, argv2); if (tc2.HasCaught()) FatalException(tc); //Emit(data_symbol, 1, args); //Emit(end_symbol, 0, NULL); } void Serializer::SetNamespace(const char* prefix, const char* nspace) { raptor_uri* nspace_uri = raptor_new_uri(world, reinterpret_cast(nspace)); assert(serializer_ != NULL); raptor_serializer_set_namespace(serializer_, nspace_uri, reinterpret_cast(prefix)); } void Serializer::SerializeStatement(const raptor_statement* statement) { assert(state_ == SERIALIZER_STATE_SERIALIZING); assert(serializer_ != NULL); raptor_serializer_serialize_statement(serializer_, const_cast(statement)); } Handle *Serializer::ExtractArguments(const Arguments& args, Handle *arguments) { for (int i = 0; i < args.Length(); ++i) { arguments[i] = args[i]; } return arguments; } const char* Serializer::GetName() { return syntax_name_; } node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/src/serializer.h000066400000000000000000000043151207301436300242370ustar00rootroot00000000000000/* * Copyright 2010 Norman Heino * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef NODE_RAPTOR_SERIALIZER_H_ #define NODE_RAPTOR_SERIALIZER_H_ #include //#include #include #include using namespace v8; using namespace node; enum serializer_state { SERIALIZER_STATE_INIT = 0, SERIALIZER_STATE_SERIALIZING, }; class Serializer : public ObjectWrap { public: static Handle Initialize(const Arguments& args); static Handle New(const Arguments& args); static Handle SerializeToFile(const Arguments& args); static Handle SerializeStart(const Arguments& args); static Handle SerializeEnd(const Arguments& args); static Handle SetNamespace(const Arguments& args); static Handle SerializeStatement(const Arguments& args); // static Handle SerializeDescription(const Arguments& args); static Handle GetName(Local property, const AccessorInfo& info); Serializer(const char* syntax_name); ~Serializer(); protected: void SerializeToFile(const char* filename); void SerializeStart(const char* base); void SerializeEnd(); void SetNamespace(const char* prefix, const char* nspace); void SerializeStatement(const raptor_statement* statement); const char* GetName(); static Handle* ExtractArguments(const Arguments& args, Handle* arguments); raptor_serializer* serializer_; char* syntax_name_; serializer_state state_; raptor_iostream* statement_stream_; char* statement_string_; size_t statement_string_length_; }; #endif node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/src/statement.cc000066400000000000000000000330471207301436300242340ustar00rootroot00000000000000/* * Copyright 2010 Norman Heino * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include #include "statics.h" #include "statement.h" Handle Statement::template_; Handle Statement::NewInstance() { HandleScope scope; if (template_.IsEmpty()) { Handle f = FunctionTemplate::New(); Handle proto = f->PrototypeTemplate(); proto->Set(tostring_symbol, FunctionTemplate::New(ToString)); // Handle t = ObjectTemplate::New(); Handle t = f->InstanceTemplate(); t->SetInternalFieldCount(1); t->SetAccessor(subject_symbol, SubjectAccessor); t->SetAccessor(pred_symbol, PredicateAccessor); t->SetAccessor(object_symbol, ObjectAccessor); template_ = Persistent::New(t); } Handle i = template_->NewInstance(); return scope.Close(i); } Handle Statement::ToString(const Arguments& args) { HandleScope scope; // get raptor_statement out of info Handle field = Handle::Cast(args.Holder()->GetInternalField(0)); raptor_statement* statement = static_cast(field->Value()); raptor_iostream* iostream; void* statement_string = NULL; size_t statement_string_len; iostream = raptor_new_iostream_to_string(statement->world, &statement_string, &statement_string_len, malloc); if (!iostream) { return ThrowException(Exception::Error( String::New("Error serializing statement."))); } int ret_val; ret_val = raptor_statement_ntriples_write(statement, iostream, 0); raptor_free_iostream(iostream); if (ret_val > 0) { if (statement_string) { free(statement_string); statement_string = NULL; } // error return Undefined(); } Handle result; if (statement_string) { result = String::New(reinterpret_cast(statement_string), statement_string_len - 1 /* remove trailing newline */); free(statement_string); statement_string = NULL; } return scope.Close(result); } Handle Statement::SubjectAccessor(Local property, const AccessorInfo& info) { HandleScope scope; Handle result = Object::New(); // get raptor_statement out of info Handle field = Handle::Cast(info.Holder()->GetInternalField(0)); raptor_statement* statement = static_cast(field->Value()); // get value out of statement raptor_term_value* subject_term = &statement->subject->value; Handle type; Handle value; raptor_uri* uri_value; raptor_term_blank_value* blank_value; if (statement->subject->type == RAPTOR_TERM_TYPE_URI) { uri_value = subject_term->uri; value = String::New(reinterpret_cast(raptor_uri_as_string(uri_value))); type = uri_symbol; } else if (statement->subject->type == RAPTOR_TERM_TYPE_BLANK) { blank_value = &subject_term->blank; value = String::New(reinterpret_cast(blank_value->string), blank_value->string_len); type = bnode_symbol; } result->Set(type_symbol, type); result->Set(value_symbol, value); return scope.Close(result); } Handle Statement::PredicateAccessor(Local property, const AccessorInfo& info) { HandleScope scope; Handle result = Object::New(); // get raptor_statement out of info Handle field = Handle::Cast(info.Holder()->GetInternalField(0)); raptor_statement* statement = static_cast(field->Value()); // get value out of statement raptor_term_value* predicate_term = &statement->predicate->value; raptor_uri* uri_value = predicate_term->uri; Handle value = String::New(reinterpret_cast(raptor_uri_as_string(uri_value))); result->Set(type_symbol, uri_symbol); result->Set(value_symbol, value); return scope.Close(result); } Handle Statement::ObjectAccessor(Local property, const AccessorInfo& info) { HandleScope scope; Handle result = Object::New(); // get raptor_statement out of info Handle field = Handle::Cast(info.Holder()->GetInternalField(0)); raptor_statement* statement = static_cast(field->Value()); // get value out of statement raptor_term_value* object_term = &statement->object->value; Handle type; Handle value; raptor_uri* uri_value; raptor_term_literal_value* literal_value; raptor_term_blank_value* blank_value; switch (statement->object->type) { case RAPTOR_TERM_TYPE_URI: uri_value = object_term->uri; value = String::New(reinterpret_cast(raptor_uri_as_string(uri_value))); type = uri_symbol; break; case RAPTOR_TERM_TYPE_LITERAL: literal_value = &object_term->literal; value = String::New(reinterpret_cast(literal_value->string), literal_value->string_len); type = literal_symbol; if (literal_value->datatype) { raptor_uri* datatype_uri = literal_value->datatype; unsigned char* datatype_uri_string = raptor_uri_to_string(datatype_uri); result->Set(dtype_symbol, String::New(reinterpret_cast(datatype_uri_string))); if (datatype_uri_string) { raptor_free_memory(datatype_uri_string); datatype_uri_string = NULL; } type = tliteral_symbol; } else if (literal_value->language) { result->Set(lang_symbol, String::New(reinterpret_cast(literal_value->language), literal_value->language_len)); } break; case RAPTOR_TERM_TYPE_BLANK: blank_value = &object_term->blank; value = String::New(reinterpret_cast(blank_value->string), blank_value->string_len); type = bnode_symbol; break; } result->Set(type_symbol, type); result->Set(value_symbol, value); return scope.Close(result); } raptor_statement* Statement::ConvertObjectToRaptorStatement(Handle obj) { HandleScope scope; Handle subject = obj->Get(subject_symbol)->ToObject(); Handle subject_type = subject->Get(type_symbol)->ToString(); Handle subject_value = subject->Get(value_symbol)->ToString(); String::Utf8Value subject_string(subject_value); raptor_term* subject_term; if (subject_type->Equals(uri_symbol)) { // have URI raptor_uri* uri = raptor_new_uri_from_counted_string(world, reinterpret_cast(*subject_string), subject_value->Length()); if (uri) { subject_term = raptor_new_term_from_uri(world, uri); raptor_free_uri(uri); } } else if (subject_type->Equals(bnode_symbol)) { // have bnode subject_term = raptor_new_term_from_counted_blank(world, reinterpret_cast(*subject_string), subject_value->Length()); } else { // error } Handle predicate = obj->Get(pred_symbol)->ToObject(); Handle predicate_type = predicate->Get(type_symbol)->ToString(); Handle predicate_value = predicate->Get(value_symbol)->ToString(); String::Utf8Value predicate_string(predicate_value); raptor_term* predicate_term; if (predicate_type->Equals(uri_symbol)) { // have URI raptor_uri* uri = raptor_new_uri_from_counted_string(world, reinterpret_cast(*predicate_string), predicate_value->Length()); if (uri) { predicate_term = raptor_new_term_from_uri(world, uri); raptor_free_uri(uri); } } else { // error } Handle object = obj->Get(object_symbol)->ToObject(); Handle object_type = object->Get(type_symbol)->ToString(); Handle object_value = object->Get(value_symbol)->ToString(); String::Utf8Value object_string(object_value); raptor_term* object_term; if (object_type->Equals(uri_symbol)) { // have URI raptor_uri* uri = raptor_new_uri_from_counted_string(world, reinterpret_cast(*object_string), object_value->Length()); if (uri) { object_term = raptor_new_term_from_uri(world, uri); raptor_free_uri(uri); } } else if (object_type->Equals(bnode_symbol)) { // have bnode object_term = raptor_new_term_from_counted_blank(world, reinterpret_cast(*object_string), object_value->Length()); } else if (object_type->Equals(literal_symbol)) { // literal Handle object_language; if (object->Has(lang_symbol)) { object_language = object->Get(lang_symbol)->ToString(); String::Utf8Value lang_string(object_language); // if (!object_language.IsEmpty()) { object_term = raptor_new_term_from_counted_literal(world, reinterpret_cast(*object_string), object_value->Length(), NULL, reinterpret_cast(*lang_string), object_language->Length()); // } } else { object_term = raptor_new_term_from_counted_literal(world, reinterpret_cast(*object_string), object_value->Length(), NULL, NULL, 0); } } else if (object_type->Equals(tliteral_symbol)) { // typed literal Handle object_datatype; if (object->Has(dtype_symbol)) { object_datatype = object->Get(dtype_symbol)->ToString(); String::Utf8Value dtype_string(object_datatype); raptor_uri* dtype_uri = raptor_new_uri_from_counted_string(world, reinterpret_cast(*dtype_string), object_datatype->Length()); if (dtype_uri) { object_term = raptor_new_term_from_counted_literal(world, reinterpret_cast(*object_string), object_value->Length(), dtype_uri, NULL, NULL); raptor_free_uri(dtype_uri); } else { // error } } } else { // error return NULL; } raptor_statement* statement; if (subject_term && predicate_term && object_term) { raptor_statement* result = raptor_new_statement_from_nodes(world, subject_term, predicate_term, object_term, NULL); // raptor_free_term(subject_term); // raptor_free_term(predicate_term); // raptor_free_term(object_term); return result; } return NULL; } node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/src/statement.h000066400000000000000000000024331207301436300240710ustar00rootroot00000000000000/* * Copyright 2010 Norman Heino * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef NODE_RAPTOR_STATEMENT_H_ #define NODE_RAPTOR_STATEMENT_H_ #include using namespace v8; class Statement { public: static Handle NewInstance(); static Handle ToString(const Arguments& args); static Handle SubjectAccessor(Local property, const AccessorInfo& info); static Handle PredicateAccessor(Local property, const AccessorInfo& info); static Handle ObjectAccessor(Local property, const AccessorInfo& info); static raptor_statement* ConvertObjectToRaptorStatement(Handle obj); private: static Handle template_; }; #endif node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/src/statics.h000066400000000000000000000044561207301436300235460ustar00rootroot00000000000000/* * Copyright 2010 Norman Heino * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef NODE_RAPTOR_SYMBOLS_H_ #define NODE_RAPTOR_SYMBOLS_H_ #include #include #include using namespace v8; static Persistent subject_symbol = NODE_PSYMBOL("subject"); static Persistent pred_symbol = NODE_PSYMBOL("predicate"); static Persistent object_symbol = NODE_PSYMBOL("object"); static Persistent tostring_symbol = NODE_PSYMBOL("toString"); static Persistent type_symbol = NODE_PSYMBOL("type"); static Persistent value_symbol = NODE_PSYMBOL("value"); static Persistent uri_symbol = NODE_PSYMBOL("uri"); static Persistent literal_symbol = NODE_PSYMBOL("literal"); static Persistent tliteral_symbol = NODE_PSYMBOL("typed-literal"); static Persistent bnode_symbol = NODE_PSYMBOL("bnode"); static Persistent dtype_symbol = NODE_PSYMBOL("datatype"); static Persistent lang_symbol = NODE_PSYMBOL("lang"); static Persistent stmt_symbol = NODE_PSYMBOL("statement"); static Persistent nmspc_symbol = NODE_PSYMBOL("namespace"); static Persistent data_symbol = NODE_PSYMBOL("data"); static Persistent message_symbol = NODE_PSYMBOL("message"); static Persistent end_symbol = NODE_PSYMBOL("end"); static Persistent debug_symbol = NODE_PSYMBOL("debug"); static Persistent info_symbol = NODE_PSYMBOL("info"); static Persistent warn_symbol = NODE_PSYMBOL("warning"); static Persistent error_symbol = NODE_PSYMBOL("error"); static Persistent fatal_symbol = NODE_PSYMBOL("fatal"); static raptor_world* world = raptor_new_world(); #endif node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/src/wscript000066400000000000000000000025571207301436300233410ustar00rootroot00000000000000import os import Options srcdir='.' blddir='../build' # Check whether envinronment variable has been set by Makefile if 'RAPTOR_PREFIX' in os.environ: RAPTOR_PREFIX = os.environ['RAPTOR_PREFIX'] else: RAPTOR_PREFIX = '/usr/local' def set_options(ctx): ctx.add_option('--clang', action='store_true', default='', dest='use_clang', help='Uses the clang compiler') ctx.add_option('--analyze', action='store_true', default='', dest='analyze', help='Runs the clang static analyzer (implies --clang)') ctx.tool_options('compiler_cxx') def configure(ctx): print "libraptor2 prefix: " + RAPTOR_PREFIX if Options.options.analyze: ctx.env.ANALYZE = Options.options.analyze Options.options.use_clang = 1 if Options.options.use_clang: os.environ['CXX'] = '/usr/bin/clang' ctx.check_tool('compiler_cxx') ctx.check_tool('node_addon') def build(ctx): obj = ctx.new_task_gen('cxx', 'shlib', 'node_addon') # Analyze if ctx.env.ANALYZE: obj.cxxflags = ['-g', '-Wall', '--analyze'] else: obj.cxxflags = ['-g', '-Wall'] obj.find_sources_in_dirs('.') obj.target = 'bindings' obj.includes = RAPTOR_PREFIX + '/include/raptor2' obj.lib = 'raptor2' obj.libpath = RAPTOR_PREFIX + '/lib' node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/test/000077500000000000000000000000001207301436300221025ustar00rootroot00000000000000node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/test/parse.js000066400000000000000000000040601207301436300235520ustar00rootroot00000000000000/* * Copyright 2010 Norman Heino * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const MAX_STATEMENTS = Number.MAX_VALUE; var util = require('util'); var raptor = require('raptor'); var time; var parser = raptor.newParser('rdfxml'); // start parsing when all other callbacks are in place process.nextTick(function () { if (process.argv.length > 2) { time = Date.now(); parser.parseFile(process.argv[2]); } }); var subjectsMap = {}; var subjectCount = 0; var tripleCount = 0; parser.on('statement', function (statement) { // if (statement.subject.type == 'bnode') { // util.puts(statement); // } if (++tripleCount >= MAX_STATEMENTS) { parser.abort(); } }); parser.on('message', function (type, message, code) { if (type == 'error' || type == 'warning') { util.log(type.toUpperCase() + ': ' + message + ' (' + code + ')'); } }); var namespaces = {}; parser.on('namespace', function (prefix, uri) { if (!(prefix in namespaces)) { namespaces[prefix] = uri; } }); parser.on('end', function () { util.puts(tripleCount + ' statements parsed.'); util.puts('Parsing took ' + (Date.now() - time) + ' ms.'); // if (subjectsMap && subjectCount) { // util.puts(subjectCount + ' distinct predicates found.'); // } util.puts('Namespaces: ' + util.inspect(namespaces)); }); /* parser.on('description', function (description) { util.puts('New description: ' + util.inspect(description)); }); */ node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/test/parse_buffer.js000066400000000000000000000043421207301436300251060ustar00rootroot00000000000000/* * Copyright 2010 Norman Heino * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const MAX_STATEMENTS = Number.MAX_VALUE; var util = require('util'), fs = require('fs'), raptor = require('./../raptor.js'); var time; var filename = process.argv[2]; var fileStream = fs.createReadStream(filename); var parser = raptor.newParser('turtle'); var time = Date.now(); process.nextTick(function () { parser.parseStart('http://example.com/'); parser.parseBuffer(new Buffer(' a , .')); parser.parseBuffer(); }); var subjectsMap = {}; var subjectCount = 0; var tripleCount = 0; parser.on('statement', function (statement) { // if (statement.subject.type == 'bnode') { util.puts(statement); // } if (++tripleCount >= MAX_STATEMENTS) { parser.abort(); } }); parser.on('message', function (type, message, code) { if (type == 'error' || type == 'warning') { util.log(type.toUpperCase() + ': ' + message + ' (' + code + ')'); } }); var namespaces = {}; parser.on('namespace', function (prefix, uri) { if (!(prefix in namespaces)) { namespaces[prefix] = uri; } }); parser.on('end', function () { util.puts(tripleCount + ' statements parsed.'); util.puts('Parsing took ' + (Date.now() - time) + ' ms.'); // if (subjectsMap && subjectCount) { // util.puts(subjectCount + ' distinct predicates found.'); // } // util.puts('Namespaces: ' + util.inspect(namespaces)); }); /* parser.on('description', function (description) { util.puts('New description: ' + util.inspect(description)); }); */ node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/test/parse_uri.js000066400000000000000000000040651207301436300244360ustar00rootroot00000000000000/* * Copyright 2010 Norman Heino * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const fileURI = 'http://xmlns.com/foaf/spec/index.rdf'; const MAX_STATEMENTS = Number.MAX_VALUE; var util = require('util'), raptor = require('./../raptor'); var time; var parser = raptor.newParser('rdfxml'); // start parsing when all other callbacks are in place process.nextTick(function () { time = Date.now(); parser.parseURI(fileURI); }); var subjectsMap = {}; var subjectCount = 0; var tripleCount = 0; parser.on('statement', function (statement) { // if (statement.subject.type == 'bnode') { util.puts(statement); // } if (++tripleCount >= MAX_STATEMENTS) { parser.abort(); } }); parser.on('message', function (type, message, code) { if (type == 'error' || type == 'warning') { util.log(type.toUpperCase() + ': ' + message + ' (' + code + ')'); } }); var namespaces = {}; parser.on('namespace', function (prefix, uri) { if (!(prefix in namespaces)) { namespaces[prefix] = uri; } }); parser.on('end', function () { util.puts(tripleCount + ' statements parsed.'); util.puts('Parsing took ' + (Date.now() - time) + ' ms.'); // if (subjectsMap && subjectCount) { // util.puts(subjectCount + ' distinct predicates found.'); // } // util.puts('Namespaces: ' + util.inspect(namespaces)); }); /* parser.on('description', function (description) { util.puts('New description: ' + util.inspect(description)); }); */ node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/test/phil.rdf000066400000000000000000000225151207301436300235400ustar00rootroot00000000000000 ]> AKSW demo knowledge base about philosophers. It demonstrates various OntoWiki features such as arbitrary object hierarchies, geoinformation reasoning, semantic plug-ins adn blank node usage. $Id$ Philisopher Philisoph Greek Philosopher Griechischer Philisoph Classical Greek Philosopher Klassischer Griechischer Philisoph Muslim Philosopher Muslimischer Philisoph Mediaeval Philosopher Mittelalterlicher Philisoph Location Ort Ton Stadt Street Straße Street number Hausnummer comment Kommentar label Bezeichner was influenced by wurde beeinflusst durch was taught by wurde gelehrt von was born in wurde geboren in depiction Abbildung year of birth Geburtsjahr year of death Todesjahr latitude Geografische Breite latitude Geografische Länge Socrates Sokrates -470 -399 Plato Platon -423 -347 Aristotle Aristoteles -384 -322 Averroes Averroes 1126 1198 Thomas Aquinas Thomas von Aquin 1225 1275 40.530278 23.751389 37.883333 -4.766667 41.55 13.666667 node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/test/ser_test.rdf000066400000000000000000000005431207301436300244310ustar00rootroot00000000000000 Resource One node_raptor-91abdec96a53acb7173684d8d6594ec7b640a39b/test/serialize.js000066400000000000000000000042771207301436300244410ustar00rootroot00000000000000/* * Copyright 2010 Norman Heino * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var util = require('util'), raptor = require('./../raptor'), fs = require('fs'); var s = { subject: {value: 'http://example.com/resource1', type: 'uri'}, predicate: {value: 'http://xmlns.com/foaf/0.1/name', type: 'uri'}, object: {value: 'Resource One', language: 'en', type: 'literal'} } var s2 = { subject: {value: '_:123', type: 'bnode'}, predicate: {value: 'http://ns.aksw.org/scms#beginIndex', type: 'uri'}, object: {value: '31', datatype: 'http://www.w3.org/2001/XMLSchema#int', type:'typed-literal'} } /* var serializer = raptor.newSerializer('rdfxml'); // set syntax options // serializer.setOption('foo', 'bar'); serializer.start(__dirname + '/ser_test.rdf'); serializer.setNamespace('foaf', 'http://xmlns.com/foaf/0.1/'); // serialize statements serializer.serializeStatement(s); // close serializer serializer.end(); var s = fs.createReadStream(__dirname + '/ser_test.rdf'); s.on('data', function (d) { util.print(d); }); */ // ---------------------------------------------------------------------------- // the file we will be writing to var serializer = raptor.newSerializer('turtle'); process.nextTick(function () { serializer.serializeStart(); //serializer.serializeStatement(s); serializer.serializeStatement(s2); serializer.serializeEnd(); }); var triples = ''; serializer.on('data', function (data) { triples += data; }); serializer.on('end', function () { util.puts(triples); }); serializer.on('error', function (type, message, code) { util.puts(message); });