<commit_before>/**
* Copyright 2016 PT Inovação e Sistemas SA
* Copyright 2016 INESC-ID
* Copyright 2016 QUOBIS NETWORKS SL
* Copyright 2016 FRAUNHOFER-GESELLSCHAFT ZUR FOERDERUNG DER ANGEWANDTEN FORSCHUNG E.V
* Copyright 2016 ORANGE SA
* Copyright 2016 Deutsche Telekom AG
* Copyright 2016 Apizee
* Copyright 2016 TECHNISCHE UNIVERSITAT BERLIN
*
* 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.
**/

import {divideURL, convertToUserURL} from '../utils/utils';

/**
* Discovered Object interface
*/
class DiscoveredObject {

  get data() {
    return this._data;
  }

  constructor(data, runtimeURL, discoveryURL, msgBus) {
    this._data = data;
    this._registryObjectURL = data.hypertyID || data.url;
    this._runtimeURL = runtimeURL;
    this._domain = divideURL(runtimeURL).domain;
    this._discoveredObjectURL = discoveryURL;
    this._messageBus = msgBus;
    this._subscriptionSet = false;
    this._subscribers = {
      live: {},
      disconnected: {}
    };
  }

  onLive(subscriber, callback) {

    return new Promise((resolve, reject) => {

      if (!this._subscriptionSet) {
        this._subscribe()
        .then(() => {
          this._subscribers.live[subscriber] = callback;
          resolve();
        })
        .catch((err) => reject(err));
      } else {
        this._subscribers.live[subscriber] = callback;
        resolve();
      }
    });
  }

  onDisconnected(subscriber, callback) {

    return new Promise((resolve, reject) => {

      if (!this._subscriptionSet) {
        this._subscribe()
        .then(() => {
          this._subscribers.disconnected[subscriber] = callback;
          resolve();
        })
        .catch((err) => reject(err));
      } else {
        this._subscribers.disconnected[subscriber] = callback;
        resolve();
      }
    });
  }

  _subscribe() {

    const msg = {
      type: 'subscribe',
      from: this._discoveredObjectURL,
      to: this._runtimeURL + '/subscriptions',
      body: {
        resources: [this._registryObjectURL + '/registration']
      }
    };

    return new Promise((resolve, reject) => {

      this._messageBus.postMessage(msg, (reply) => {
        console.log(`[DiscoveredObject.subscribe] ${this._registryObjectURL} rcved reply `, reply);

        if (reply.body.code === 200) {
          this._generateListener(this._registryObjectURL + '/registration');
          this._subscriptionSet = true;
          resolve();
        } else {
          console.error('Error subscribing ', this._registryObjectURL);
          reject('Error subscribing ' + this._registryObjectURL);
        }
      });
    });
  }

  _generateListener(notificationURL) {

    this._messageBus.addListener(notificationURL, (msg) => {
      console.log(`[DiscoveredObject.notification] ${this._registryObjectURL}: `, msg);
      this._processNotification(msg);
    });
  }

  _processNotification(msg) {
    const status = msg.body.value

    Object.keys(this._subscribers[status]).forEach(
      subscriber => this._subscribers[status][subscriber]()
    );
  }

  _unsubscribe() {

    const msg = {
      type: 'unsubscribe',
      from: this._discoveredObjectURL,
      to: this._runtimeURL + '/subscriptions',<commit_msg>discovery: when not found an empty array is resolved and the promise is not rejected<commit_after>/**
* Copyright 2016 PT Inovação e Sistemas SA
* Copyright 2016 INESC-ID
* Copyright 2016 QUOBIS NETWORKS SL
* Copyright 2016 FRAUNHOFER-GESELLSCHAFT ZUR FOERDERUNG DER ANGEWANDTEN FORSCHUNG E.V
* Copyright 2016 ORANGE SA
* Copyright 2016 Deutsche Telekom AG
* Copyright 2016 Apizee
* Copyright 2016 TECHNISCHE UNIVERSITAT BERLIN
*
* 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.
**/

import {divideURL, convertToUserURL} from '../utils/utils';

/**
* Discovered Object interface
*/
class DiscoveredObject {

  get data() {
    return this._data;
  }

  constructor(data, runtimeURL, discoveryURL, msgBus) {
    this._data = data;
    this._registryObjectURL = data.hypertyID || data.url;
    this._runtimeURL = runtimeURL;
    this._domain = divideURL(runtimeURL).domain;
    this._discoveredObjectURL = discoveryURL;
    this._messageBus = msgBus;
    this._subscriptionSet = false;
    this._subscribers = {
      live: {},
      disconnected: {}
    };
  }

  onLive(subscriber, callback) {

    return new Promise((resolve, reject) => {

      if (!this._subscriptionSet) {
        this._subscribe()
        .then(() => {
          this._subscribers.live[subscriber] = callback;
          resolve();
        })
        .catch((err) => reject(err));
      } else {
        this._subscribers.live[subscriber] = callback;
        resolve();
      }
    });
  }

  onDisconnected(subscriber, callback) {

    return new Promise((resolve, reject) => {

      if (!this._subscriptionSet) {
        this._subscribe()
        .then(() => {
          this._subscribers.disconnected[subscriber] = callback;
          resolve();
        })
        .catch((err) => reject(err));
      } else {
        this._subscribers.disconnected[subscriber] = callback;
        resolve();
      }
    });
  }

  _subscribe() {

    const msg = {
      type: 'subscribe',
      from: this._discoveredObjectURL,
      to: this._runtimeURL + '/subscriptions',
      body: {
        resources: [this._registryObjectURL + '/registration']
      }
    };

    return new Promise((resolve, reject) => {

      this._messageBus.postMessage(msg, (reply) => {
        console.log(`[DiscoveredObject.subscribe] ${this._registryObjectURL} rcved reply `, reply);

        if (reply.body.code === 200) {
          this._generateListener(this._registryObjectURL + '/registration');
          this._subscriptionSet = true;
          resolve();
        } else {
          console.error('Error subscribing ', this._registryObjectURL);
          reject('Error subscribing ' + this._registryObjectURL);
        }
      });
    });
  }

  _generateListener(notificationURL) {

    this._messageBus.addListener(notificationURL, (msg) => {
      console.log(`[DiscoveredObject.notification] ${this._registryObjectURL}: `, msg);
      this._processNotification(msg);
    });
  }

  _processNotification(msg) {
    const status = msg.body.value

    setTimeout( ()=>{// Hack to give time for onLive Hyperties to get ready. To be removed when Hyperty State machaine is implemented
      Object.keys(this._subscribers[status]).forEach(
        subscriber => this._subscribers[status][subscriber]()
      );

    }, 500);

  }

  _unsubscribe() {

    const msg = {
      type: 'unsubscribe',
      from: this._discoveredObjectURL,
      to: this._runtimeURL + '/subscriptions',
{'fraction_non_alphanumeric': 0.11787870832239433, 'fraction_numerical': 0.010632711997899712, 'mean_word_length': 2.8694768918232607, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 24, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '799669', 'n_tokens_mistral': 2280, 'n_tokens_neox': 2153, 'n_words': 550}