예제 #1
0
  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext)
   */
  public void stop(final BundleContext context) throws Exception {
    // TODO-mkuppe here we should do something like a deregisterAll(), but see ungetService(...);
    if (serviceRegistration != null && serviceFactory.isActive()) {
      ServiceReference reference = serviceRegistration.getReference();
      IDiscoveryLocator aLocator = (IDiscoveryLocator) context.getService(reference);

      serviceRegistration.unregister();

      IContainer container = (IContainer) aLocator.getAdapter(IContainer.class);
      container.disconnect();
      container.dispose();

      serviceRegistration = null;
    }
    plugin = null;
    bundleContext = null;
    if (advertiserSt != null) {
      advertiserSt.close();
      advertiserSt = null;
    }
    if (locatorSt != null) {
      locatorSt.close();
      locatorSt = null;
    }
  }
예제 #2
0
 public void testGetContainerOne() throws Exception {
   IContainer[] c = createContainers(1);
   assertNotNull(c);
   IContainer container = containerManager.getContainer(c[0].getID());
   assertNotNull(container);
   assertTrue(container.getID().equals(c[0].getID()));
 }
예제 #3
0
 /*
  * (non-Javadoc)
  *
  * @see
  * org.eclipse.ecf.core.IContainerListener#handleEvent(org.eclipse.ecf
  * .core.events.IContainerEvent)
  */
 public void handleEvent(IContainerEvent event) {
   final IContainerManager containerManager =
       (IContainerManager) ContainerFactory.getDefault();
   if (containerManager == null) return;
   IContainer container = containerManager.getContainer(event.getLocalContainerID());
   if (container == null) return;
   if (event instanceof IContainerConnectedEvent
       || event instanceof IContainerDisconnectedEvent) {
     // connected
     IChannelContainerAdapter cca =
         (IChannelContainerAdapter) container.getAdapter(IChannelContainerAdapter.class);
     if (cca == null) return;
     ID containerID = container.getID();
     if (event instanceof IContainerConnectedEvent) {
       try {
         if (!TeamSynchronization.contains(containerID)) {
           TeamSynchronization.put(containerID, new WorkbenchAwareRemoteShare(cca));
         }
       } catch (ECFException e) {
         TeamSynchronization.log(
             "RemoteShare could not be added or created", e); // $NON-NLS-1$
       }
     } else if (event instanceof IContainerDisconnectedEvent) {
       // disconnected
       TeamSynchronization.removeShare(containerID);
     }
   } else if (event instanceof IContainerDisposeEvent) {
     containerManager.removeListener(containerManagerListener);
     container.removeListener(containerListener);
   }
 }
예제 #4
0
 public void testGetContainerN() throws Exception {
   IContainer[] c = createContainers(10);
   assertNotNull(c);
   for (int i = 0; i < 10; i++) {
     IContainer container = containerManager.getContainer(c[i].getID());
     assertNotNull(container);
     assertTrue(container.getID().equals(c[i].getID()));
   }
 }
  protected void addServiceListener(TestServiceListener serviceListener) {
    discoveryLocator.addServiceListener(serviceListener);
    addListenerRegisterAndWait(serviceListener, serviceInfo);
    discoveryLocator.removeServiceListener(serviceListener);

    // make sure we use a live container;
    final IContainer ic = (IContainer) serviceListener.getLocator();
    assertTrue(ic.getConnectedID() != null);

    // check if we received correct amount of events
    final IContainerEvent[] events = serviceListener.getEvent();
    assertNotNull("Test listener didn't receive any discovery events.", events);
    assertEquals(
        "Test listener received unexpected amount of discovery events: \n\t"
            + Arrays.asList(events),
        eventsToExpect,
        events.length);

    final List origContainers = new ArrayList();
    for (int i = 0; i < events.length; i++) {
      final CompositeServiceContainerEvent event = (CompositeServiceContainerEvent) events[i];

      // check if the local container is hidden correctly
      final ID localContainerId = event.getLocalContainerID();
      final ID connectedId = container.getConnectedID();
      assertEquals(localContainerId, connectedId);

      // check the IServiceInfo for correct fields/properties
      final IServiceInfo serviceInfo2 = ((IServiceEvent) event).getServiceInfo();
      assertTrue(
          "IServiceInfo should match, expected:\n\t" + serviceInfo + " but was \n\t" + serviceInfo2,
          comparator.compare(serviceInfo2, serviceInfo) == 0);

      // add the underlying discovery container the the result set
      origContainers.add(event.getOriginalLocalContainerID());
    }
    // check that all underlying containers fired an event
    assertEquals(
        "A nested container didn't send an event, but another multiple.",
        eventsToExpect,
        origContainers.size());
  }
예제 #6
0
  public void register(String zoodiscoveryServerIp)
      throws ContainerCreateException, ContainerConnectException {
    IContainerFactory containerFactory = ContainerFactory.getDefault();
    containerFactory.createContainer(DEFAULT_CONTAINER_TYPE);

    zooContainer = containerFactory.createContainer("ecf.discovery.zoodiscovery");

    if (zooContainer.getConnectedID() == null) {
      ID target =
          zooContainer
              .getConnectNamespace()
              .createInstance(
                  new String[] {"zoodiscovery.flavor.centralized=" + zoodiscoveryServerIp});
      zooContainer.connect(target, null);
      logger.info("ZooDiscovery connected");
    } else {
      logger.warn(
          "ZooDiscovery already connected: " + zooContainer.getConnectedID().toExternalForm());
    }
  }
  protected void createChannel() throws ECFException {
    // Get datashare adapter from new container
    datashareAdapter =
        (IChannelContainerAdapter) container.getAdapter(IChannelContainerAdapter.class);

    // Create channel listener for channel to be created
    IChannelListener channelListener = createChannelListener();
    // Create a channel with given channel listener
    testChannel =
        datashareAdapter.createChannel(
            IDFactory.getDefault().createStringID(Activator.class.getName()),
            channelListener,
            null);
  }
 protected void shutdown() {
   if (datashareAdapter != null) {
     datashareAdapter.removeChannel(testChannel.getID());
     testChannel = null;
     datashareAdapter = null;
   }
   if (container != null) {
     container.dispose();
     getContainerManager().removeAllContainers();
     container = null;
   }
   if (containerManagerTracker != null) {
     containerManagerTracker.close();
     containerManagerTracker = null;
   }
   synchronized (appLock) {
     done = true;
     appLock.notifyAll();
   }
   bundleContext = null;
 }
예제 #9
0
 /* (non-Javadoc)
  * @see org.eclipse.ecf.core.util.IContainerFilter#match(org.eclipse.ecf.core.IContainer)
  */
 public boolean match(IContainer containerToMatch) {
   result = containerToMatch.getAdapter(clazz);
   return result != null;
 }
예제 #10
0
 /*
  * (non-Javadoc)
  *
  * @see
  * org.eclipse.ecf.core.IContainerManagerListener#containerRemoved(org
  * .eclipse.ecf.core.IContainer)
  */
 public void containerRemoved(IContainer container) {
   container.removeListener(containerListener);
 }
예제 #11
0
 /*
  * (non-Javadoc)
  *
  * @see
  * org.eclipse.ecf.core.IContainerManagerListener#containerAdded(org
  * .eclipse.ecf.core.IContainer)
  */
 public void containerAdded(IContainer container) {
   IChannelContainerAdapter cca =
       (IChannelContainerAdapter) container.getAdapter(IChannelContainerAdapter.class);
   if (cca == null) return;
   container.addListener(containerListener);
 }
  @Override
  public InputStream createInputStream(URI uri, Map<?, ?> options) throws IOException {
    if (TEST_IO_EXCEPTION) {
      File folder = new File(CACHE_FOLDER.toFileString());
      if (folder.isDirectory()) {
        System.out.println("Deleting cache folder: " + folder);
        IOUtil.deleteBestEffort(folder);
      }

      throw new IOException("Simulated network problem");
    }

    CacheHandling cacheHandling = getCacheHandling(options);
    URIConverter uriConverter = getURIConverter(options);
    URI cacheURI = getCacheFile(uri);
    String eTag =
        cacheHandling == CacheHandling.CACHE_IGNORE ? null : getETag(uriConverter, cacheURI);
    String expectedETag = cacheHandling == CacheHandling.CACHE_IGNORE ? null : getExpectedETag(uri);
    if (expectedETag != null
        || cacheHandling == CacheHandling.CACHE_ONLY
        || cacheHandling == CacheHandling.CACHE_WITHOUT_ETAG_CHECKING) {
      if (cacheHandling == CacheHandling.CACHE_ONLY
              || cacheHandling == CacheHandling.CACHE_WITHOUT_ETAG_CHECKING
          ? eTag != null
          : expectedETag.equals(eTag)) {
        try {
          setExpectedETag(uri, expectedETag);
          return uriConverter.createInputStream(cacheURI, options);
        } catch (IOException ex) {
          // Perhaps another JVM is busy writing this file.
          // Proceed as if it doesn't exit.
        }
      }
    }

    String username;
    String password;

    String uriString = uri.toString();
    Proxy proxy = ProxySetupHelper.getProxy(uriString);
    if (proxy != null) {
      username = proxy.getUsername();
      password = proxy.getPassword();
    } else {
      username = null;
      password = null;
    }

    IContainer container = createContainer();

    AuthorizationHandler authorizatonHandler = getAuthorizatonHandler(options);
    Authorization authorization = getAuthorizaton(options);
    int triedReauthorization = 0;
    for (int i = 0; ; ++i) {
      IRetrieveFileTransferContainerAdapter fileTransfer =
          container.getAdapter(IRetrieveFileTransferContainerAdapter.class);

      if (proxy != null) {
        fileTransfer.setProxy(proxy);

        if (username != null) {
          fileTransfer.setConnectContextForAuthentication(
              ConnectContextFactory.createUsernamePasswordConnectContext(username, password));
        } else if (password != null) {
          fileTransfer.setConnectContextForAuthentication(
              ConnectContextFactory.createPasswordConnectContext(password));
        }
      }

      FileTransferListener transferListener = new FileTransferListener(eTag);

      try {
        FileTransferID fileTransferID =
            new FileTransferID(new FileTransferNamespace(), IOUtil.newURI(uriString));
        Map<Object, Object> requestOptions = new HashMap<Object, Object>();
        requestOptions.put(IRetrieveFileTransferOptions.CONNECT_TIMEOUT, 10000);
        requestOptions.put(IRetrieveFileTransferOptions.READ_TIMEOUT, 10000);
        if (authorization != null && authorization.isAuthorized()) {
          requestOptions.put(
              IRetrieveFileTransferOptions.REQUEST_HEADERS,
              Collections.singletonMap("Authorization", authorization.getAuthorization()));
        }

        fileTransfer.sendRetrieveRequest(fileTransferID, transferListener, requestOptions);
      } catch (IncomingFileTransferException ex) {
        throw new IOExceptionWithCause(ex);
      }
      try {
        transferListener.receiveLatch.await();
      } catch (InterruptedException ex) {
        throw new IOExceptionWithCause(ex);
      }

      if (transferListener.exception != null) {
        if (!(transferListener.exception instanceof UserCancelledException)) {
          if (transferListener.exception.getCause() instanceof SocketTimeoutException && i <= 2) {
            continue;
          }

          if (authorizatonHandler != null
              && transferListener.exception instanceof IncomingFileTransferException) {
            // We assume contents can be accessed via the github API
            // https://developer.github.com/v3/repos/contents/#get-contents
            // That API, for security reasons, does not return HTTP_UNAUTHORIZED, so we need this
            // special case for that host.
            IncomingFileTransferException incomingFileTransferException =
                (IncomingFileTransferException) transferListener.exception;
            int errorCode = incomingFileTransferException.getErrorCode();
            if (errorCode == HttpURLConnection.HTTP_UNAUTHORIZED
                || API_GITHUB_HOST.equals(getHost(uri))
                    && errorCode == HttpURLConnection.HTTP_NOT_FOUND) {
              if (authorization == null) {
                authorization = authorizatonHandler.authorize(uri);
                if (authorization.isAuthorized()) {
                  --i;
                  continue;
                }
              }

              if (!authorization.isUnauthorizeable() && triedReauthorization++ < 3) {
                authorization = authorizatonHandler.reauthorize(uri, authorization);
                if (authorization.isAuthorized()) {
                  --i;
                  continue;
                }
              }
            }
          }
        }

        if (!CacheHandling.CACHE_IGNORE.equals(cacheHandling)
            && uriConverter.exists(cacheURI, options)
            && (!(transferListener.exception instanceof IncomingFileTransferException)
                || ((IncomingFileTransferException) transferListener.exception).getErrorCode()
                    != HttpURLConnection.HTTP_NOT_FOUND)) {
          setExpectedETag(uri, transferListener.eTag == null ? eTag : transferListener.eTag);
          return uriConverter.createInputStream(cacheURI, options);
        }

        throw new IOExceptionWithCause(transferListener.exception);
      }

      byte[] bytes = transferListener.out.toByteArray();

      // In the case of the Github API, the bytes will be JSON that contains a "content" pair
      // containing the Base64 encoding of the actual contents.
      if (API_GITHUB_HOST.equals(getHost(uri))) {
        // Find the start tag in the JSON value.
        String value = new String(bytes, "UTF-8");
        int start = value.indexOf(CONTENT_TAG);
        if (start != -1) {
          // Find the ending quote of the encoded contents.
          start += CONTENT_TAG.length();
          int end = value.indexOf('"', start);
          if (end != -1) {
            // The content is delimited by \n so split on that during the conversion.
            String content = value.substring(start, end);
            String[] split = content.split("\\\\n");

            // Write the converted bytes to a new stream and process those bytes instead.
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            for (String line : split) {
              byte[] binary = XMLTypeFactory.eINSTANCE.createBase64Binary(line);
              out.write(binary);
            }

            out.close();
            bytes = out.toByteArray();
          }
        }
      }

      try {
        BaseUtil.writeFile(uriConverter, options, cacheURI, bytes);
      } catch (IORuntimeException ex) {
        // Ignore attempts to write out to the cache file.
        // This may collide with another JVM doing exactly the same thing.
        transferListener.eTag = null;
      } finally {
        setETag(uriConverter, cacheURI, transferListener.eTag);
      }

      setExpectedETag(uri, transferListener.eTag);
      Map<Object, Object> response = getResponse(options);
      if (response != null) {
        response.put(URIConverter.RESPONSE_TIME_STAMP_PROPERTY, transferListener.lastModified);
      }

      ETagMirror etagMirror = (ETagMirror) options.get(ETagMirror.OPTION_ETAG_MIRROR);
      if (etagMirror != null) {
        etagMirror.cacheUpdated(uri);
      }

      return new ByteArrayInputStream(bytes);
    }
  }
 protected void connectContainer() throws ContainerConnectException {
   // then if targetId is non-null (client), connect to target Id
   if (targetId != null)
     container.connect(
         IDFactory.getDefault().createID(container.getConnectNamespace(), targetId), null);
 }