Skip to content
Snippets Groups Projects
ServerConnector.js 54.7 KiB
Newer Older
"use strict";

/* exported logger */

var Promise = require("bluebird");

var logger = require('./logger');

var request = require('request');

var HttpStatus = require('http-status-codes');

var Alias = require('./map/data/Alias');
var Annotation = require('./map/data/Annotation');
var Chemical = require('./map/data/Chemical');
var Comment = require('./map/data/Comment');
var Configuration = require('./Configuration');
var Drug = require('./map/data/Drug');
var ConfigurationType = require('./ConfigurationType');
var IdentifiedElement = require('./map/data/IdentifiedElement');
var InvalidCredentialsError = require('./InvalidCredentialsError');
var LayoutAlias = require('./map/data/LayoutAlias');
var LayoutData = require('./map/data/LayoutData');
var LayoutReaction = require('./map/data/LayoutReaction');
var MapModel = require('./map/data/MapModel');
var Mesh = require('./map/data/Mesh');
var MiRna = require('./map/data/MiRna');
var NetworkError = require('./NetworkError');
var Project = require('./map/data/Project');
var ProjectStatistics = require('./map/data/ProjectStatistics');
var Reaction = require('./map/data/Reaction');
var ReferenceGenome = require('./map/data/ReferenceGenome');
var SbmlFunction = require('./map/data/SbmlFunction');
var SbmlParameter = require('./map/data/SbmlParameter');
var SecurityError = require('./SecurityError');
var SessionData = require('./SessionData');
var User = require('./map/data/User');

var GuiConnector = require('./GuiConnector');

var ObjectWithListeners = require('./ObjectWithListeners');

/**
 * This object contains methods that will communicate with server.
 */
var ServerConnector = new ObjectWithListeners();
ServerConnector.init = function () {
  var self = this;

  self._configurationParam = [];
  self._projects = [];
  self._projectsById = [];

  self._users = [];
  self._usersByLogin = [];

  self._customMap = null;
  self._sessionData = undefined;
  self._configuration = undefined;
  self._loggedUser = undefined;
  self._serverBaseUrl = undefined;

  var i;
  var listeners = self.getListeners("onDataLoadStart");
  for (i = 0; i < listeners.length; i++) {
    self.removeListener("onDataLoadStart", listeners[i]);
  }

  listeners = self.getListeners("onDataLoadStop");
  for (i = 0; i < listeners.length; i++) {
    self.removeListener("onDataLoadStop", listeners[i]);
  }

};
ServerConnector.registerListenerType("onDataLoadStart");
ServerConnector.registerListenerType("onDataLoadStop");
ServerConnector.init();

ServerConnector.getMinOverlayColorInt = function () {
  var self = this;
  return self.getLoggedUser().then(function (user) {
    var userColor = user.getMinColor();
    return self.returnUserOrSystemColor(userColor, self.getConfigurationParam(ConfigurationType.MIN_COLOR_VAL));
  });
};

ServerConnector.returnUserOrSystemColor = function (userColor, systemPromisedColor) {
  return systemPromisedColor.then(function (systemColor) {
    var color = userColor;
    if (userColor === null || userColor === undefined || userColor === "") {
      color = systemColor;
    }
    color = parseInt(color, 16);
    /* jslint bitwise: true */
    color = (color & 0xFFFFFF);
    return color;
  });
};

ServerConnector.getSimpleOverlayColorInt = function () {
  var self = this;
  return self.getLoggedUser().then(function (user) {
    var userColor = user.getSimpleColor();
    return self.returnUserOrSystemColor(userColor, self.getConfigurationParam(ConfigurationType.SIMPLE_COLOR_VAL));
  });
};

ServerConnector.getMaxOverlayColorInt = function () {
  var self = this;
  return self.getLoggedUser().then(function (user) {
    var userColor = user.getMaxColor();
    return self.returnUserOrSystemColor(userColor, self.getConfigurationParam(ConfigurationType.MAX_COLOR_VAL));
  });
};

ServerConnector.getNeutralOverlayColorInt = function () {
  var self = this;
  return self.getLoggedUser().then(function (user) {
    var userColor = user.getNeutralColor();
    return self.returnUserOrSystemColor(userColor, self.getConfigurationParam(ConfigurationType.NEUTRAL_COLOR_VAL));
  });
};

ServerConnector.sendGetRequest = function (url, description) {
  return this.sendRequest({
    url: url,
    description: description,
    method: "GET"
  });
};

ServerConnector.sendRequest = function (params) {
  var self = this;
  if (arguments.length > 1) {
    return Promise.reject(new Error("Only two arguments are supported"));
  }

  if (self.getSessionData().getToken() === undefined) {
    self.getSessionData().setLogin(undefined);
    window.location.reload(false);
  }

  var description = params.url;
  if (params.description !== undefined) {
    description = params.description;
    params.description = undefined;
  }

  var content;
  return self.callListeners("onDataLoadStart", description).then(function () {
    return self._sendRequest(params);
  }).then(function (result) {
    content = result;
    return self.callListeners("onDataLoadStop", description);
  }, function (error) {
    return self.callListeners("onDataLoadStop", description).then(function () {
      return Promise.reject(error);
    });
  }).then(function () {
    return content;
  }, function (error) {
    if (error instanceof NetworkError) {
      if (error.statusCode === HttpStatus.FORBIDDEN && error.content.indexOf('"reason":"Invalid token"') >= 0) {
        self.getSessionData().setToken(undefined);
        if (self.getSessionData().getLogin() === "anonymous") {
          window.location.reload(false);
        } else {
          window.location.href = ServerConnector.getServerBaseUrl() + "login.xhtml?from=" + encodeURI(window.location.href);
        }
      }
    }
    return Promise.reject(error);
  });

};

ServerConnector._sendRequest = function (params) {
  return new Promise(function (resolve, reject) {
    request(params, function (error, response, body) {
      if (error) {
        reject(new NetworkError(error.message, {
          content: body,
          url: params.url
        }));
      } else if (response.statusCode !== 200) {
        reject(new NetworkError(params.url + " rejected with status code: " + response.statusCode, {
          content: body,
          url: params.url,
          statusCode: response.statusCode
        }));
      } else {
        // for some reason sometimes result is an object not a string
        if (typeof body === 'string' || body instanceof String) {
          resolve(body);
        } else {
          resolve(JSON.stringify(body));
        }
      }
    });
  });
};

ServerConnector.sendPostRequest = function (url, params) {
  return this.sendRequest({
    method: "POST",
    url: url,
    form: params
  });
};

ServerConnector.sendDeleteRequest = function (url, json) {
  return this.sendRequest({
    method: "DELETE",
    url: url,
    json: json
  });
};

ServerConnector.sendPatchRequest = function (url, json) {
  return this.sendRequest({
    method: "PATCH",
    url: url,
    json: json
  });
};

ServerConnector.getToken = function () {
  var self = this;

  var login = self.getSessionData(null).getLogin();
  var token = self.getSessionData(null).getToken();
  if (token === undefined || login === undefined) {
    return self.login();
  } else {
    // if the project is not initialized then check if we can download data
    // using current token
    if (self.getSessionData().getProject() === null) {
      return self.getConfiguration().then(function () {
        return token;
        // if there was an error accessing configuration it means our token is
        // invalid
      }, function () {
        return self.login();
      });
    } else {
      return Promise.resolve(token);
    }
  }
};

ServerConnector.getApiBaseUrl = function () {
  return this.getServerBaseUrl() + "/api/";
};

ServerConnector.getServerBaseUrl = function () {
  if (this._serverBaseUrl === undefined) {
    var url = "" + window.location.href;
    if (url.indexOf("?") >= 0) {
      url = url.substr(0, url.indexOf("?"));
    }
    if (!url.endsWith("/")) {
      url = url.substr(0, url.lastIndexOf("/") + 1);
    }
    this._serverBaseUrl = url;
  }
  return this._serverBaseUrl;
};

ServerConnector.createGetParams = function (params, prefix) {
  var sorted = [], key;

  for (key in params) {
    if (params.hasOwnProperty(key)) {
      sorted.push(key);
    }
  }
  sorted.sort();

  var result = "";
  for (var i = 0; i < sorted.length; i++) {
    key = sorted[i];
    var value = params[key];
    if (prefix !== undefined) {
      key = prefix + "." + key;
    }

    if (value instanceof google.maps.Point) {
      value = this.pointToString(value);
    } else if (Object.prototype.toString.call(value) === '[object Array]') {
      value = this.idsToString(value);
    } else if (typeof value === 'string' || value instanceof String || !isNaN(value)) {

    } else {
      result += this.createGetParams(value, key);
      value = undefined;
    }

    if (value !== undefined && value !== "") {
      result += key + "=" + value + "&";
    }
  }
  return result;
};

ServerConnector.getApiUrl = function (paramObj) {
  var type = paramObj.type;
  var params = this.createGetParams(paramObj.params);

  var result = paramObj.url;
  if (result === undefined) {
    result = this.getApiBaseUrl() + "/" + type;
  }
  if (params !== "") {
    result += "?" + params;
  }
  return result;
};

ServerConnector.getProjectsUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    type: "projects/",
    params: filterParams
  });
};

ServerConnector.getProjectUrl = function (queryParams, filterParams) {
  var id = this.getIdOrAsterisk(queryParams.projectId);
  return this.getApiUrl({
    url: this.getProjectsUrl(queryParams) + id + "/",
    params: filterParams
  });
};

ServerConnector.getProjectStatisticsUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getProjectUrl(queryParams) + "statistics/",
    params: filterParams
  });
};

ServerConnector.getPublicationsUrl = function (queryParams, filterParams) {
  filterParams.start = filterParams.start || 0;
  filterParams.length = filterParams.length || 10;

  return this.getApiUrl({
    url: this.getModelsUrl(queryParams) + "publications/",
    params: filterParams
  });
};
ServerConnector.getProjectLogsUrl = function (queryParams, filterParams) {
  filterParams.start = filterParams.start || 0;
  filterParams.length = filterParams.length || 10;

  return this.getApiUrl({
    url: this.getProjectUrl(queryParams) + "logs/",
    params: filterParams
  });
};
ServerConnector.getMeshUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    type: "mesh/" + queryParams.id,
    params: filterParams
  });
};
ServerConnector.getSbmlFunctionUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getModelsUrl(queryParams) + "functions/" + queryParams.functionId,
    params: filterParams
  });
};
ServerConnector.getSbmlParameterUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getModelsUrl(queryParams) + "parameters/" + queryParams.parameterId,
    params: filterParams
  });
};

ServerConnector.getReferenceGenomeUrl = function (queryParams, filterParams) {
  var version = this.getIdOrAsterisk(queryParams.version);

  return this.getApiUrl({
    type: "genomics/taxonomies/" + queryParams.organism + "/genomeTypes/" + queryParams.type + "/versions/" + version
    + "/",
    params: filterParams
  });
};

ServerConnector.loginUrl = function () {
  return this.getApiUrl({
    type: "/doLogin"
  });
};

ServerConnector.logoutUrl = function () {
  return this.getApiUrl({
    type: "/doLogout"
  });
};

ServerConnector.getSuggestedQueryListUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getBioEntitiesUrl(queryParams) + "suggestedQueryList/",
    params: filterParams
  });
};
ServerConnector.getChemicalSuggestedQueryListUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getProjectUrl(queryParams) + "chemicals/suggestedQueryList",
    params: filterParams
  });
};
ServerConnector.getDrugSuggestedQueryListUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getProjectUrl(queryParams) + "drugs/suggestedQueryList",
    params: filterParams
  });
};
ServerConnector.getMiRnaSuggestedQueryListUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getProjectUrl(queryParams) + "miRnas/suggestedQueryList",
    params: filterParams
  });
};

ServerConnector.addCommentUrl = function (queryParams) {
  return this.getApiUrl({
    url: this.getCommentsUrl(queryParams)
  });
};

ServerConnector.addOverlayUrl = function (queryParams) {
  return this.getApiUrl({
    url: this.getOverlaysUrl(queryParams)
  });
};

ServerConnector.updateOverlayUrl = function (queryParams) {
  return this.getApiUrl({
    url: this.getOverlayByIdUrl(queryParams)
  });
};

ServerConnector.updateModelUrl = function (queryParams) {
  return this.getApiUrl({
    url: this.getModelsUrl(queryParams)
  });
};

451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
ServerConnector.deleteOverlayUrl = function (queryParams) {
  return this.getApiUrl({
    url: this.getOverlayByIdUrl(queryParams)
  });
};

ServerConnector.deleteCommentUrl = function (queryParams) {
  return this.getApiUrl({
    url: this.getProjectUrl(queryParams) + "comments/" + queryParams.commentId + "/"
  });
};

ServerConnector.getOverlaysUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getProjectUrl(queryParams) + "overlays/",
    params: filterParams
  });
};

ServerConnector.getCommentsUrl = function (queryParams, filterParams) {
  var modelId = this.getIdOrAsterisk(queryParams.modelId);
  var url = this.getProjectUrl(queryParams) + "comments/models/" + modelId + "/";
  if (queryParams.elementType !== undefined) {
    if (queryParams.elementType === "ALIAS") {
      url += "bioEntities/elements/" + queryParams.elementId;
    } else if (queryParams.elementType === "REACTION") {
      url += "bioEntities/reactions/" + queryParams.elementId;
    } else if (queryParams.elementType === "POINT") {
      url += "points/" + queryParams.coordinates;
    } else {
      throw new Error("Unknown element type: " + queryParams.elementType);
    }
  }
  return this.getApiUrl({
    url: url,
    params: filterParams
  });
};

ServerConnector.getOverlayByIdUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getOverlaysUrl(queryParams) + queryParams.overlayId + "/",
    params: filterParams
  });

};

ServerConnector.getOverlayElementsUrl = function (queryParams, filterParams) {

  return this.getApiUrl({
    url: this.getModelsUrl(queryParams) + "bioEntities/",
    params: filterParams
  });

};

ServerConnector.getFullOverlayElementUrl = function (queryParams, filterParams) {

  return this.getApiUrl({
    url: this.getAliasesUrl(queryParams) + queryParams.id + "/",
    params: filterParams
  });

};

ServerConnector.idsToString = function (ids) {
  var result = "";
  if (ids !== undefined) {
    ids.sort(function (a, b) {
      if (typeof a === "string") {
        return a.localeCompare(b);
      } else {
        return a - b;
      }
    });
    for (var i = 0; i < ids.length; i++) {
      if (result !== "") {
        if (ids[i - 1] !== ids[i]) {
          result = result + "," + ids[i];
        } // we ignore duplicates
      } else {
        result = ids[i];
      }
    }
  }
  return result;
};

ServerConnector.pointToString = function (point) {
  return point.x.toFixed(2) + "," + point.y.toFixed(2);
};

ServerConnector.getModelsUrl = function (queryParams) {
  var modelId = this.getIdOrAsterisk(queryParams.modelId);
  var overlayId = queryParams.overlayId;
  var url = this.getProjectUrl(queryParams);
  if (overlayId !== undefined) {
    url = this.getOverlayByIdUrl(queryParams);
  }

  return this.getApiUrl({
    url: url + "models/" + modelId + "/"
  });
};

ServerConnector.getBioEntitiesUrl = function (queryParams) {
  return this.getApiUrl({
    url: this.getModelsUrl(queryParams) + "bioEntities/"
  });
};

ServerConnector.getIdOrAsterisk = function (id) {
  if (id === undefined || id === "" || id === null) {
    return "*";
  } else {
    return id;
  }
};

ServerConnector.getReactionsUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getBioEntitiesUrl(queryParams) + "reactions/",
    params: filterParams
  });
};

ServerConnector.getAliasesUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getBioEntitiesUrl(queryParams) + "elements/",
    params: filterParams
  });
};

ServerConnector.getConfigurationUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    type: "configuration/",
    params: filterParams
  });
};

ServerConnector.getConfigurationOptionUrl = function (queryParams, filterParams) {
  var self = this;
  return self.getApiUrl({
    url: self.getConfigurationUrl() + "options/" + queryParams.type,
    params: filterParams
  });
};


ServerConnector.getSearchUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getModelsUrl(queryParams) + "bioEntities:search",
    params: filterParams
  });
};

ServerConnector.getSearchDrugsUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getProjectUrl(queryParams) + "drugs:search",
    params: filterParams
  });
};

ServerConnector.getSearchMiRnasUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getProjectUrl(queryParams) + "miRnas:search",
    params: filterParams
  });
};

ServerConnector.getSearchChemicalsUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getProjectUrl(queryParams) + "chemicals:search",
    params: filterParams
  });
};

ServerConnector.getOverlaySourceUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getOverlaysUrl(queryParams) + queryParams.overlayId + ":downloadSource",
    params: filterParams
  });
};

ServerConnector.getImageUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getProjectUrl(queryParams) + "models/" + queryParams.modelId + ":downloadImage",
    params: filterParams
  });
};

ServerConnector.getModelPartUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getProjectUrl(queryParams) + "models/" + queryParams.modelId + ":downloadModel",
    params: filterParams
  });
};

ServerConnector.getProjectSourceUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    type: "projects/" + queryParams.projectId + ":downloadSource",
    params: filterParams
  });
};


ServerConnector.getFilesUrl = function () {
  return this.getApiUrl({
    type: "files/"
  });
};

ServerConnector.getCreateFileUrl = function () {
  return this.getApiUrl({
    url: this.getFilesUrl()
  });
};
ServerConnector.getFileUrl = function (queryParams) {
  return this.getApiUrl({
    url: this.getFilesUrl() + "/" + queryParams.id
  });
};
ServerConnector.getUploadFileUrl = function (queryParams) {
  return this.getApiUrl({
    url: this.getFileUrl(queryParams) + ":uploadContent"
  });
};


ServerConnector.getUsersUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    type: "users/",
    params: filterParams
  });
};

ServerConnector.getUserUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getUsersUrl() + queryParams.login,
    params: filterParams
  });
};

ServerConnector.getUpdateUserPrivilegesUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getUserUrl(queryParams) + ":updatePrivileges",
    params: filterParams
  });
};
ServerConnector.getUpdateUserPreferencesUrl = function (queryParams, filterParams) {
  return this.getApiUrl({
    url: this.getUserUrl(queryParams) + ":updatePreferences",
    params: filterParams
  });
};

ServerConnector.getConfiguration = function () {
  var self = this;
  if (this._configuration === undefined) {
    return self.sendGetRequest(self.getConfigurationUrl()).then(function (content) {
      self._configuration = new Configuration(JSON.parse(content));
      return Promise.resolve(self._configuration);
    });
  } else {
    return Promise.resolve(self._configuration);
  }
};

ServerConnector.getConfigurationParam = function (paramId) {
  if (paramId === undefined) {
    return Promise.reject(new Error("Unknown param type"));
  }
  var self = this;
  return self.getConfiguration().then(function (configuration) {
    var option = configuration.getOption(paramId);
    if (option.getValue !== undefined) {
      return option.getValue();
    } else {
      return option;
    }
  });
};
ServerConnector.updateConfigurationOption = function (option) {
  var self = this;
  var queryParams = {
    type: option.getType()
  };
  var filterParams = {
    option: {
      type: option.getType(),
      value: option.getValue()
    }
  };
  return self.sendPatchRequest(self.getConfigurationOptionUrl(queryParams), filterParams);
};

ServerConnector.getModels = function (projectId) {
  var queryParams = {};
  var filterParams = {};
  var self = this;
  return self.getProjectId(projectId).then(function (result) {
    queryParams.projectId = result;
    return self.sendGetRequest(self.getModelsUrl(queryParams, filterParams));
  }).then(function (content) {
    var models = [];
    var parsedJson = JSON.parse(content);
    for (var i = 0; i < parsedJson.length; i++) {
      models.push(new MapModel(parsedJson[i]));
    }
    return models;
  });
};

ServerConnector.getProject = function (projectId) {
  var queryParams = {};
  var filterParams = {};
  var project;
  var self = this;
  return self.getProjectId(projectId).then(function (result) {
    projectId = result;
    queryParams.projectId = result;
    return self.sendGetRequest(self.getProjectUrl(queryParams, filterParams));
  }).then(function (content) {
    var downloadedProject = new Project(content);
    if (self._projectsById[projectId] !== undefined) {
      self._projectsById[projectId].update(downloadedProject);
    } else {
      self._projectsById[projectId] = downloadedProject;
    }
    project = self._projectsById[projectId];
    return self.getModels(projectId);
  }).then(function (models) {
    project.setModel(models[0]);
    return self.getLoggedUser();
  }).then(function (user) {
    return self.getOverlays({
      projectId: projectId,
      creator: user.getLogin(),
      publicOverlay: false
    });
  }).then(function (overlays) {
    if (project.getModel() !== undefined) {
      project.getModel().addLayouts(overlays);
    } else {
      if (overlays.length > 0) {
        logger.warn("Cannot add overlays to the project: " + project.getProjectId());
      }
    }
    return project;
  }).then(null, function (error) {
    if ((error instanceof NetworkError)) {
      switch (error.statusCode) {
        case HttpStatus.NOT_FOUND:
          return null;
        case HttpStatus.FORBIDDEN:
          return Promise.reject(new SecurityError("Access denied."));
        default:
          return Promise.reject(error);
      }
    } else {
      return Promise.reject(error);
    }
  });
};

ServerConnector.updateProject = function (project) {
  var self = this;
  var queryParams = {
    projectId: project.getProjectId()
  };
  var filterParams = {
    project: {
      name: project.getName(),
      version: project.getVersion(),
      notifyEmail: project.getNotifyEmail(),
      organism: self.serialize(project.getOrganism()),
      disease: self.serialize(project.getDisease())
    }
  };
  return self.sendPatchRequest(self.getProjectUrl(queryParams), filterParams).then(function (content) {
    var downloadedProject = new Project(content);
    project.update(downloadedProject);
    return project;
  }).then(null, function (error) {
    if ((error instanceof NetworkError)) {
      switch (error.statusCode) {
        case HttpStatus.FORBIDDEN:
          return Promise.reject(new SecurityError("Access denied."));
        default:
          return Promise.reject(error);
      }
    } else {
      return Promise.reject(error);
    }
  });
};

ServerConnector.removeProject = function (projectId) {
  var self = this;
  var queryParams = {
    projectId: projectId
  };
  return self.sendDeleteRequest(self.getProjectUrl(queryParams)).then(function (content) {
    var project = new Project(content);
    if (self._projectsById[project.getProjectId()] !== undefined) {
      self._projectsById[project.getProjectId()].update(project);
    } else {
      self._projectsById[project.getProjectId()] = project;
    }
    return self._projectsById[project.getProjectId()];
  }).then(null, function (error) {
    if ((error instanceof NetworkError)) {
      switch (error.statusCode) {
        case HttpStatus.FORBIDDEN:
          return Promise.reject(new SecurityError("Access denied."));
        default:
          return Promise.reject(error);
      }
    } else {
      return Promise.reject(error);
    }
  });
};

ServerConnector.addProject = function (options) {
  var self = this;
  var queryParams = {
    projectId: options.projectId
  };
  return self.sendPostRequest(self.getProjectUrl(queryParams), options).then(function (content) {
    var project = new Project(content);
    if (self._projectsById[project.getProjectId()] !== undefined) {
      self._projectsById[project.getProjectId()].update(project);
    } else {
      self._projectsById[project.getProjectId()] = project;
    }
    return project;
  }).then(null, function (error) {
    if ((error instanceof NetworkError)) {
      switch (error.statusCode) {
        case HttpStatus.FORBIDDEN:
          return Promise.reject(new SecurityError("Access denied."));
        default:
          return Promise.reject(error);
      }
    } else {
      return Promise.reject(error);
    }
  });
};

ServerConnector.serialize = function (object) {
  var result = {};
  if (object instanceof Annotation) {
    result.type = object.getType();
    result.resource = object.getResource();
  } else if (object === undefined) {
    result = undefined;
  } else {
    throw new Error("Unhandled object type: " + (typeof object));
  }
  return result;
};

ServerConnector.getProjects = function (reload) {
  var self = this;
  if (self._projects.length > 0 && !reload) {
    return Promise.resolve(self._projects);
  } else {
    return self.sendGetRequest(self.getProjectsUrl()).then(function (content) {
      var parsedData = JSON.parse(content);
      self._projects.length = 0;
      for (var i = 0; i < parsedData.length; i++) {
        var project = new Project(JSON.stringify(parsedData[i]));
        if (self._projectsById[project.getProjectId()] !== undefined) {
          self._projectsById[project.getProjectId()].update(project);
        } else {
          self._projectsById[project.getProjectId()] = project;
        }
        self._projects.push(self._projectsById[project.getProjectId()]);
      }
      return self._projects;
    });
  }
};

ServerConnector.getProjectStatistics = function (projectId) {
  var queryParams = {};
  var filterParams = {};
  var self = this;
  var content;
  return self.getProjectId(projectId).then(function (result) {
    queryParams.projectId = result;
    return self.sendGetRequest(self.getProjectStatisticsUrl(queryParams, filterParams));
  }).then(function (result) {
    content = JSON.parse(result);
    return self.getConfiguration();
  }).then(function (configuration) {
    return new ProjectStatistics(content, configuration);
  });
};

ServerConnector.getLoggedUser = function () {
  var self = this;
  if (self._loggedUser !== undefined) {
    return Promise.resolve(self._loggedUser);
  } else {
    return self.getUser(self.getSessionData().getLogin()).then(function (user) {
      self._loggedUser = user;
      return self._loggedUser;
    });
  }
};

ServerConnector.getUser = function (login) {
  var self = this;
  var queryParams = {
    login: login
  };
  var filterParams = {};

  return self.sendGetRequest(self.getUserUrl(queryParams, filterParams)).then(function (content) {
    var obj = JSON.parse(content);
    var user = new User(obj);
    if (self._usersByLogin[user.getLogin()] !== undefined) {
      self._usersByLogin[user.getLogin()].update(user);
    } else {
      self._usersByLogin[user.getLogin()] = user;
    }
    return self._usersByLogin[user.getLogin()];
  }).then(null, function (error) {
    return self.processNetworkError(error);
  });
};

ServerConnector.updateUser = function (user) {
  var self = this;
  var queryParams = {
    login: user.getLogin()
  };
  var filterParams = {
    user: {
      name: user.getName(),
      surname: user.getSurname(),
      password: user.getPassword(),
      email: user.getEmail()
    }
  };
  return self.sendPatchRequest(self.getUserUrl(queryParams), filterParams).then(function () {
    return self.getConfiguration();