Jump To …

OpenCalaisService.js

src/service/
VIE - Vienna IKS Editables
(c) 2011 Henri Bergius, IKS Consortium
(c) 2011 Sebastian Germesin, IKS Consortium
(c) 2011 Szaby Gr├╝nwald, IKS Consortium
VIE may be freely distributed under the MIT license.
For all details and documentation:
http://viejs.org/

VIE - OpenCalaisService service

The OpenCalaisService ...

(function(){

VIE.OpenCalaisService(options)

This is the constructor to instantiate a new service to collect properties of an entity from OpenCalais. Parameters: {object} options Optional set of fields, namespaces, rules, url, or name. Throws: nothing Returns: {VIE.OpenCalaisService} : A new VIE.OpenCalaisService instance. Example usage:

var service = new vie.OpenCalaisService({<some-configuration>});
VIE.prototype.OpenCalaisService = function(options) {
    var defaults = {

the default name of this service

        name : 'opencalais',

you can pass an array of URLs which are then tried sequentially

        url: ["http://api.opencalais.com/enlighten/rest/"],
        timeout : 60000, /* 60 seconds timeout */
        namespaces : {
            opencalaisc:  "http://s.opencalais.com/1/pred/",
            opencalaiscr: "http://s.opencalais.com/1/type/er/",
            opencalaiscm: "http://s.opencalais.com/1/type/em/e/"
        },

default rules that are shipped with this service

        rules : []
    };

the options are merged with the default options

    this.options = jQuery.extend(true, defaults, options ? options : {});

    this.vie = null; /* will be set via VIE.use(); */

overwrite options.name if you want to set another name

    this.name = this.options.name;

basic setup for the ajax connection

    jQuery.ajaxSetup({
        converters: {"text application/rdf+json": function(s){return JSON.parse(s);}},
        timeout: this.options.timeout
    });
};

VIE.prototype.OpenCalaisService.prototype = {

init()

This method initializes certain properties of the service and is called via VIE.use(). Parameters: nothing Throws: nothing Returns: {VIE.StanbolService} : The VIE.StanbolService instance itself. Example usage:

var service = new vie.OpenCalaisService({<some-configuration>});
service.init();
    init: function(){

        for (var key in this.options.namespaces) {
            var val = this.options.namespaces[key];
            this.vie.namespaces.add(key, val);
        }

        this.rules = jQuery.extend([], VIE.Util.transformationRules(this));

this.rules = jQuery.extend(this.rules, [{
'left' : [
'?subject a opencalaiscm:Person',
'?subject opencalaisc:name ?name'
],
'right': function(ns) {
return function() {
return
jQuery.rdf.triple(this.subject.toString(),
'a',
'<' + ns.base() + 'Person>', {
namespaces: ns.toObj()
}),
jQuery.rdf.triple(this.subject.toString(),
'<' + ns.base() + 'name>',
this.label, {
namespaces: ns.toObj()
})
;
};
}(this.vie.namespaces)
}]);

        this.rules = jQuery.merge(this.rules, (this.options.rules) ? this.options.rules : []);

this.rules = [];

        this.connector = new this.vie.OpenCalaisConnector(this.options);
    },

analyze(analyzable)

This method extracts text from the jQuery element and sends it to OpenCalais for analysis. Parameters: {VIE.Analyzable} analyzable The analyzable. Throws: {Error} if an invalid VIE.Findable is passed. Returns: {VIE.OpenCalaisService} : The VIE.OpenCalaisService instance itself. Example usage:

var service = new vie.OpenCalaisService({<some-configuration>});
service.analyzable(
    new vie.Analyzable({element : jQuery("#foo")})
);
    analyze: function(analyzable) {
        var service = this;

        var correct = analyzable instanceof this.vie.Analyzable;
        if (!correct) {throw "Invalid Analyzable passed";}

        var element = analyzable.options.element ? analyzable.options.element : jQuery('body');

        var text = service._extractText(element);

        if (text.length > 0) {

query enhancer with extracted text

            var success = function (results) {
                _.defer(function(){
                    var entities = VIE.Util.rdf2Entities(service, results);
                    analyzable.resolve(entities);
                });
            };
            var error = function (e) {
                analyzable.reject(e);
            };

            this.connector.analyze(text, success, error);

        } else {
            console.warn("No text found in element.");
            analyzable.resolve([]);
        }

    },

this private method extracts text from a jQuery element

    _extractText: function (element) {
        if (element.get(0) &&
            element.get(0).tagName &&
            (element.get(0).tagName == 'TEXTAREA' ||
            element.get(0).tagName == 'INPUT' && element.attr('type', 'text'))) {
            return element.get(0).val();
        }
        else {
            var res = element
                .text()    /* get the text of element */
                .replace(/\s+/g, ' ') /* collapse multiple whitespaces */
                .replace(/\0\b\n\r\f\t/g, ''); /* remove non-letter symbols */
            return jQuery.trim(res);
        }
    }
};

VIE.OpenCalaisConnector(options)

The OpenCalaisConnector is the connection between the VIE OpenCalais service and the actual ajax calls. Parameters: {object} options The options. Throws: nothing Returns: {VIE.OpenCalaisService} : The new VIE.OpenCalaisService instance. Example usage:

var conn = new vie.OpenCalaisConnector({<some-configuration>});
VIE.prototype.OpenCalaisConnector = function (options) {
    this.options = options;
    this.baseUrl = (_.isArray(options.url))? options.url : [ options.url ];
    this.enhancerUrlPrefix = "/";
};

VIE.prototype.OpenCalaisConnector.prototype = {

analyze(text, success, error, options)

This method sends the given text to OpenCalais returns the result by the success callback. Parameters: {string} text The text to be analyzed. {function} success The success callback. {function} error The error callback. {object} options Options, like the format. Throws: nothing Returns: {VIE.OpenCalaisConnector} : The VIE.OpenCalaisConnector instance itself. Example usage:

var conn = new vie.OpenCalaisConnector(opts);
conn.analyze("This is some text.",
            function (res) { ... },
            function (err) { ... });
    analyze: function(text, success, error, options) {
        if (!options) { options = { urlIndex : 0}; }
        if (options.urlIndex >= this.baseUrl.length) {
            error("Could not connect to the given OpenCalais endpoints! Please check for their setup!");
            return;
        }

        var enhancerUrl = this.baseUrl[options.urlIndex].replace(/\/$/, '');
        enhancerUrl += this.enhancerUrlPrefix;

        var format = options.format || "application/rdf+json";

        var retryErrorCb = function (c, t, s, e, o) {

in case a OpenCalais backend is not responding and
multiple URLs have been registered

            return  function () {
                console.error("OpenCalais connection error", arguments);
                c.analyze(t, s, e, _.extend(o, {urlIndex : o.urlIndex+1}));
            };
        }(this, text, success, error, options);

        var data = this._prepareData(text);

        if (typeof exports !== "undefined" && typeof process !== "undefined") {

We're on Node.js, don't use jQuery.ajax

            return this._analyzeNode(enhancerUrl, data, success, retryErrorCb, options, format);
        }

        jQuery.ajax({
            success: function(a, b, c){
                var responseData = c.responseText.replace(/<!--[\s\S]*?-->/g, '');
                success(responseData);
            },
            error: retryErrorCb,
            type: "POST",
            url: enhancerUrl,
            data: data,
            accept: "text/plain"
        });
    },

    _analyzeNode: function(url, text, success, errorCB, options, format) {
        var request = require('request');
        var r = request({
            method: "POST",
            uri: url,
            body: text,
            headers: {
                Accept: format
            }
        }, function(error, response, body) {
            try {
                success({results: JSON.parse(body)});
            } catch (e) {
                errorCB(e);
            }
        });
        r.end();
    },

    _prepareData : function (text) {
        return {
            licenseID: this.options.api_key,
            calculareRelevanceScore: "true",
            enableMetadataType: "GenericRelations,SocialTags",
            contentType: "text/html",
            content: text

for more options check http://developer.opencalais.com/docs/suggest/

        };
    }
};
})();

generated Wed Dec 05 2012 19:56:01 GMT+0100 (CET)
VIE