/*
   * (non-Javadoc)
   *
   * @see
   * org.societies.api.internal.servicelifecycle.IServiceDiscovery#getServices
   * ()
   */
  @Override
  @Async
  public Future<List<Service>> getServices(String jid) throws ServiceDiscoveryException {

    Future<List<Service>> asyncResult = null;
    List<Service> result = null;

    try {

      asyncResult = this.getServices(commMngr.getIdManager().fromJid(jid));

      result = asyncResult.get();

    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvalidFormatException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return new AsyncResult<List<Service>>(result);
  }
  @Override
  public IActivityFeed getOrCreateFeed(String owner, String feedId, Boolean bPubSub) {
    LOG.debug("In getOrCreateFeed .. ");
    for (IActivityFeed feed : feeds) {
      if (((ActivityFeed) feed).getId().contentEquals(feedId)) {
        if (!((ActivityFeed) feed).getOwner().contentEquals(owner)) {
          LOG.debug("right feedid but wrong owner");
          return null;
        }
        return feed;
      }
    }
    LOG.info("did not find feedid creating new..");
    IIdentity identity = null;
    try {
      identity = commManager.getIdManager().fromJid(owner);
    } catch (InvalidFormatException e) {
      LOG.error("Invalid Format of owner jid when creating or getting activityfeed: ", e);
    }
    // not existing, making a new one..
    ActivityFeed ret = new ActivityFeed(feedId, owner);
    if (bPubSub) {
      ret.setPubSubEnabled(true);
      ret.setPubSubcli(this.pubSubClient);
    }

    ret.startUp(this.sessionFactory);
    if (bPubSub) {
      ret.connectPubSub(identity);
    }

    feeds.add(ret);
    persistNewFeed(ret);
    return ret;
  }
  @Autowired(required = true)
  CtxBootLoader(ICommManager commMgr, IUserCtxDBMgr userCtxDBMgr, ICtxEventMgr ctxEventMgr)
      throws Exception {

    if (LOG.isInfoEnabled()) LOG.info(this.getClass() + " instantiated");

    this.commMgr = commMgr;
    this.userCtxDBMgr = userCtxDBMgr;
    this.ctxEventMgr = ctxEventMgr;

    final INetworkNode localCssNodeId = commMgr.getIdManager().getThisNetworkNode();
    LOG.info("Found local CSS node ID " + localCssNodeId);
    final IIdentity localCssId = commMgr.getIdManager().fromJid(localCssNodeId.getBareJid());
    LOG.info("Found local CSS ID " + localCssId);

    final IndividualCtxEntity cssOwnerEnt =
        createIndividualEntity(
            localCssId, CtxEntityTypes.PERSON); // TODO don't hardcode the cssOwner type
    this.createCssNode(cssOwnerEnt, localCssNodeId);
  }
  /*
   * (non-Javadoc)
   * @see org.societies.api.internal.privacytrust.privacyprotection.IPrivacyAgreementManager#getAgreement(org.societies.api.identity.Requestor)
   */
  @Override
  public AgreementEnvelope getAgreement(Requestor requestor) throws PrivacyException {
    // -- Verify
    if (null == requestor || null == requestor.getRequestorId()) {
      throw new PrivacyException(
          "Not enought information to search a privacy policy agreement. Requestor needed.");
    }
    // Dependency injection not ready
    if (!isDepencyInjectionDone()) {
      throw new PrivacyException("[Dependency Injection] PrivacyPolicyAgreementManager not ready");
    }

    try {
      List<CtxIdentifier> agreementIdList =
          ctxBroker
              .lookup(
                  CtxModelType.ATTRIBUTE, PrivacyAgreementManagerInternal.getRequestorId(requestor))
              .get();
      if (null == agreementIdList || agreementIdList.size() <= 0) {
        return null;
      }
      CtxIdentifier agreementId = agreementIdList.get(0);
      CtxAttribute agreementData = (CtxAttribute) ctxBroker.retrieve(agreementId).get();
      org.societies.api.internal.schema.privacytrust.privacyprotection.model.privacypolicy
              .AgreementEnvelope
          agreementTmp =
              (org.societies.api.internal.schema.privacytrust.privacyprotection.model.privacypolicy
                      .AgreementEnvelope)
                  SerialisationHelper.deserialise(
                      agreementData.getBinaryValue(),
                      this.getClass().getClassLoader()); // ClassLoader.getSystemClassLoader());
      if (null == agreementTmp) {
        throw new NullPointerException("NullPointerException Deserialized agreement is null");
      }
      AgreementEnvelope agreement =
          AgreementEnvelopeUtils.toAgreementEnvelope(agreementTmp, commManager.getIdManager());
      return agreement;
    } catch (CtxException e) {
      LOG.error("[Error getAgreement] Can't find the agreement. Context error.", e);
    } catch (IOException e) {
      LOG.error("[Error getAgreement] Can't find the agreement. IO error.", e);
    } catch (ClassNotFoundException e) {
      LOG.error("[Error getAgreement] Can't find the agreement. ClassNotFound error.", e);
    } catch (InterruptedException e) {
      LOG.error("[Error getAgreement] Can't find the agreement.", e);
    } catch (ExecutionException e) {
      LOG.error("[Error getAgreement] Can't find the agreement.", e);
    } catch (InvalidFormatException e) {
      LOG.error(
          "[Error getAgreement] Can't transform the agreement into a bean for serialization.", e);
    }
    return null;
  }
 private boolean isDepencyInjectionDone(int level) {
   if (null == ctxBroker) {
     LOG.info("[Dependency Injection] Missing ICtxBorker");
     return false;
   }
   if (level == 0 || level == 1) {
     if (null == commManager) {
       LOG.info("[Dependency Injection] Missing ICommManager");
       return false;
     }
     if (null == commManager.getIdManager()) {
       LOG.info("[Dependency Injection] Missing IIdentityManager");
       return false;
     }
   }
   return true;
 }
 public static boolean isDepencyInjectionDone(int level) {
   if (null == commManager) {
     LOG.info("[Dependency Injection] Missing ICommManager");
     return false;
   }
   if (null == commManager.getIdManager()) {
     LOG.info("[Dependency Injection] Missing IIdentityManager");
     return false;
   }
   if (null == privacyPolicyManager) {
     LOG.info("[Dependency Injection] Missing IPrivacyPolicyManager");
     return false;
   }
   if (null == privacyAgreementManager) {
     LOG.info("[Dependency Injection] Missing IPrivacyAgreementManager");
     return false;
   }
   return true;
 }
  @Autowired(required = true)
  public CtxEventExample(ICtxEventMgr ctxEventMgr, ICommManager commMgr) throws Exception {

    if (LOG.isInfoEnabled()) LOG.info("*** " + this.getClass() + " instantiated");
    this.ctxEventMgr = ctxEventMgr;
    final String localIdentity = commMgr.getIdManager().getThisNetworkNode().getBareJid();
    final CtxEntityIdentifier scope =
        new CtxEntityIdentifier(localIdentity, ENTITY_TYPE, SCOPE_OBJECT_NUMBER);
    this.ctxAttrId = new CtxAttributeIdentifier(scope, ATTRIBUTE_TYPE, ATTRIBUTE_OBJECT_NUMBER);
    this.ctxAttrId2 = new CtxAttributeIdentifier(scope, ATTRIBUTE_TYPE2, ATTRIBUTE_OBJECT_NUMBER2);
    this.registerListenerByCtxId();
    this.registerListenerByScope();
    this.registerListenerByScopeAttrType();
    this.sendLocalEvent();
    this.sendLocalEvent2();
    this.sendRemoteEvent();
    this.sendRemoteEvent2();
    this.sendBroadcastEvent();
    this.sendBroadcastEvent2();
  }
  /* (non-Javadoc)
   * @see org.societies.api.internal.servicelifecycle.IServiceDiscovery#getServices()
   */
  @Override
  @Async
  public Future<List<Service>> getLocalServices() throws ServiceDiscoveryException {

    // TODO : Fix this up!
    INetworkNode currentNode = commMngr.getIdManager().getThisNetworkNode();

    Future<List<Service>> asyncResult = null;
    List<Service> result = null;

    asyncResult = this.getServices(currentNode);

    try {
      result = asyncResult.get();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return new AsyncResult<List<Service>>(result);
  }
 @Override
 public Result run() {
   identityManager = commManager.getIdManager();
   return super.run();
 }
  /*
   * (non-Javadoc)
   *
   * @see
   * org.societies.api.internal.servicelifecycle.IServiceDiscovery#getServices
   * (org.societies.api.comm.xmpp.datatypes.Identity)
   */
  @Override
  @Async
  public Future<List<Service>> getServices(IIdentity node) throws ServiceDiscoveryException {
    List<Service> serviceList = new ArrayList<Service>();

    if (logger.isDebugEnabled())
      logger.debug("getServices(Identity node) for node: " + node.getJid());

    boolean myNode;
    boolean myCIS = false;
    INetworkNode currentNode = commMngr.getIdManager().getThisNetworkNode();
    if (!currentNode.getJid().contentEquals(node.getJid())) myNode = false;
    else myNode = true;

    try {
      // Is it our node? If so, local search
      if (myNode) {
        if (logger.isDebugEnabled()) logger.debug("We're dealing with our own node!");
        serviceList = getServiceReg().retrieveServicesSharedByCSS(node.getJid());
      } else {
        // Is it one of my CIS? If so, local search
        ICisOwned localCis = getCisManager().getOwnedCis(node.getJid());
        if (localCis != null) {
          if (logger.isDebugEnabled()) logger.debug("We're dealing with our CIS! Local search!");
          serviceList = getServiceReg().retrieveServicesSharedByCIS(node.getJid());
          myCIS = true;
        }
      }
      /*
      switch (node.getType())
      {
      case CSS:
      case CSS_RICH:
      case CSS_LIGHT:
      	serviceList = getServiceReg().retrieveServicesSharedByCSS(node.getJid());
      	break;
      case CIS:
      	if(logger.isDebugEnabled()) logger.debug("Retrieving services of a CIS");
      	ICisOwned myCis = getCisManager().getOwnedCis(node.getJid());
      	if(myCis != null){
      		if(logger.isDebugEnabled()) logger.debug("We're dealing with our CIS! Local search!");
      		serviceList = getServiceReg().retrieveServicesSharedByCIS(node.getJid());
      	}
      	break;
      default:
      	logger.warn("Unknown node!");
      	break;
      }
      */
    } catch (ServiceRetrieveException e) {

      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (Exception e) {

      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    if (serviceList == null || serviceList.isEmpty()) {
      if (logger.isDebugEnabled()) logger.debug("No services retrieved from local node...");

      // IIdentity currentNode = commMngr.getIdManager().getThisNetworkNode();

      if (!myNode && !myCIS) {

        if (logger.isDebugEnabled())
          logger.debug("Attempting to retrieve services from remote node: " + node.getJid());

        ServiceDiscoveryRemoteClient callback = new ServiceDiscoveryRemoteClient();
        getServiceDiscoveryRemote().getServices(node, callback);
        serviceList = callback.getResultList();
      }
    }

    // Quick log message
    if (logger.isDebugEnabled()) {

      if (serviceList.isEmpty()) logger.debug("getServices: no services found!");
      else {
        Iterator<Service> it = serviceList.iterator();
        String logStuff = "getServices: ";

        while (it.hasNext()) {
          logStuff += it.next().getServiceName() + "; \n";
        }

        logger.debug(logStuff);
      }
    }

    return new AsyncResult<List<Service>>(serviceList);
  }
  public void initialiseRelevantCommunityAnalyser() {
    // getCommManager().register(this);
    identityManager = commManager.getIdManager();

    new RelevantCommunityAnalyser(linkedCss, "CSS");
  }
  @Before
  public void setUp() {
    this.userId = new MyIdentity(IdentityType.CSS, "xcmanager", "societies.local");
    CtxEntityIdentifier ctxId = new CtxEntityIdentifier(userId.getJid(), "Person", new Long(1));
    this.userCtxEntity = new CtxEntity(ctxId);
    hasPrivacyPreferences =
        new CtxAssociation(
            new CtxAssociationIdentifier(
                userId.getJid(), CtxTypes.HAS_PRIVACY_PREFERENCES, new Long(3)));
    CtxEntityIdentifier preferenceEntityId_ppnp1 =
        new CtxEntityIdentifier(userId.getJid(), CtxTypes.PRIVACY_PREFERENCE, new Long(2));
    this.privacyPreferenceEntity = new CtxEntity(preferenceEntityId_ppnp1);
    this.ppnp_1_CtxAttribute =
        new CtxAttribute(
            new CtxAttributeIdentifier(
                this.privacyPreferenceEntity.getId(), "ppnp_preference_1", new Long(5)));
    this.registryCtxAttribute =
        new CtxAttribute(
            new CtxAttributeIdentifier(
                userCtxEntity.getId(), CtxTypes.PRIVACY_PREFERENCE_REGISTRY, new Long(1)));
    Mockito.when(commsManager.getIdManager()).thenReturn(identityManager);
    privPrefMgr.setCtxBroker(ctxBroker);
    privPrefMgr.setCommsMgr(commsManager);
    privPrefMgr.setprivacyDataManagerInternal(privacyDataManager);
    privPrefMgr.setTrustBroker(trustBroker);
    privPrefMgr.setMyMessageBox(myMsgBox);

    try {
      Mockito.when(ctxBroker.lookup(CtxModelType.ATTRIBUTE, CtxTypes.PRIVACY_PREFERENCE_REGISTRY))
          .thenReturn(new AsyncResult<List<CtxIdentifier>>(new ArrayList<CtxIdentifier>()));
      Mockito.when(ctxBroker.lookup(CtxModelType.ENTITY, CtxTypes.PRIVACY_PREFERENCE))
          .thenReturn(new AsyncResult<List<CtxIdentifier>>(new ArrayList<CtxIdentifier>()));
      Mockito.when(ctxBroker.lookup(CtxModelType.ASSOCIATION, CtxTypes.HAS_PRIVACY_PREFERENCES))
          .thenReturn(new AsyncResult<List<CtxIdentifier>>(new ArrayList<CtxIdentifier>()));
      IndividualCtxEntity weirdPerson = new IndividualCtxEntity(userCtxEntity.getId());
      Mockito.when(ctxBroker.retrieveCssOperator())
          .thenReturn(new AsyncResult<IndividualCtxEntity>(weirdPerson));

      Mockito.when(ctxBroker.createAssociation(CtxTypes.HAS_PRIVACY_PREFERENCES))
          .thenReturn(new AsyncResult<CtxAssociation>(this.hasPrivacyPreferences));
      Mockito.when(ctxBroker.createEntity(CtxTypes.PRIVACY_PREFERENCE))
          .thenReturn(new AsyncResult<CtxEntity>(privacyPreferenceEntity));
      Mockito.when(ctxBroker.createAttribute(privacyPreferenceEntity.getId(), "ppnp_preference_1"))
          .thenReturn(new AsyncResult<CtxAttribute>(ppnp_1_CtxAttribute));
      Mockito.when(
              ctxBroker.createAttribute(
                  userCtxEntity.getId(), CtxTypes.PRIVACY_PREFERENCE_REGISTRY))
          .thenReturn(new AsyncResult<CtxAttribute>(registryCtxAttribute));

      Mockito.when(
              myMsgBox.showConfirmDialog(
                  Mockito.anyString(), Mockito.anyString(), Mockito.eq(JOptionPane.YES_NO_OPTION)))
          .thenReturn(JOptionPane.YES_OPTION);
      Mockito.when(
              ctxBroker.updateAttribute(
                  Mockito.eq(ppnp_1_CtxAttribute.getId()), (Serializable) Mockito.anyObject()))
          .thenReturn(new AsyncResult<CtxAttribute>(ppnp_1_CtxAttribute));

    } catch (CtxException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    privPrefMgr.initialisePrivacyPreferenceManager();
  }