Esempio n. 1
0
 public synchronized void watch(String table, int h, Map<String, Object> options) {
   logger.info("Starting to watch " + table + " handle = " + h + " with options: " + options);
   boolean found = false;
   try {
     for (Observer o : observers) found |= o.watch(this, h, table, options);
     if (!found) {
       sendError("there is no table " + table);
       return;
     }
   } catch (Exception ex) {
     sendError(ex.getMessage());
   }
   /*
   try {
   	DefaultValue value = proc.interestedIn(this, options);
   	Handle handle = value.handle;
   	handles.put(h, handle);
   	rhandles.put(handle, h);
   	if (value.table != null)
   		deliver(handle, value.table);
   } catch (Exception ex) {
   	ex.printStackTrace();
   	sendError(ex.getMessage());
   }
   */
 }
Esempio n. 2
0
 /** 通知所有观察者 */
 public void notifyObservers() {
   Iterator it = observers.iterator();
   while (it.hasNext()) {
     Observer o = (Observer) it.next();
     o.update(this);
   }
 }
  @Override
  public void performAction(Connection connection, OperationObserver observer)
      throws SQLException, Exception {

    ProcedureTranslator transl = createTranslator(connection);
    CallableStatement statement = (CallableStatement) transl.createStatement();

    try {
      // stored procedure may contain a mixture of update counts and result sets,
      // and out parameters. Read out parameters first, then
      // iterate until we exhaust all results
      boolean hasResultSet = statement.execute();

      // local observer to cache results and provide them to the external observer
      // in the order consistent with other adapters.

      Observer localObserver = new Observer(observer);

      // read query, using local observer

      while (true) {
        if (hasResultSet) {
          ResultSet rs = statement.getResultSet();
          try {
            RowDescriptor descriptor = describeResultSet(rs, processedResultSets++);
            readResultSet(rs, descriptor, query, localObserver);
          } finally {
            try {
              rs.close();
            } catch (SQLException ex) {
            }
          }
        } else {
          int updateCount = statement.getUpdateCount();
          if (updateCount == -1) {
            break;
          }
          dataNode.getJdbcEventLogger().logUpdateCount(updateCount);
          localObserver.nextCount(query, updateCount);
        }

        hasResultSet = statement.getMoreResults();
      }

      // read out parameters to the main observer ... AFTER the main result set
      // TODO: I hope SQLServer does not support ResultSets as OUT parameters,
      // otherwise
      // the order of custom result descriptors will be messed up
      readProcedureOutParameters(statement, observer);

      // add results back to main observer
      localObserver.flushResults(query);
    } finally {
      try {
        statement.close();
      } catch (SQLException ex) {

      }
    }
  }
Esempio n. 4
0
 @Override
 public Object call() throws Exception {
   long start = System.currentTimeMillis();
   Exception exception = null;
   try {
     observer.snapshot(timestamp);
     return null;
   } catch (Exception e) {
     exception = e;
     return null;
   } finally {
     long stop = System.currentTimeMillis();
     long duration = stop - start;
     StringBuilder sb = new StringBuilder();
     sb.append("snapshot for service [")
         .append(serviceConfig.getName())
         .append("] observer [")
         .append(observer.getName())
         .append("]: time=")
         .append((stop - start))
         .append(" ms");
     if (exception == null) {
       sb.append("; result was ok");
       // only print out good case if > step
       if (duration >= serviceConfig.getStepMillis()) {
         logger.warn("{} but exceeded stepMillis", sb);
       }
     } else {
       sb.append("; exception: ").append(exception.getMessage());
       logger.warn("{}", sb);
       logger.warn("", exception);
     }
   }
 }
Esempio n. 5
0
  @Override
  public void notifyObserver() {

    for (Observer observer : observers) {
      observer.update(temperature, humidity, pressure);
    }
  }
 public void notifyObservers() {
   Iterator<Observer> iterator = vector.iterator();
   while (iterator.hasNext()) {
     Observer observer = iterator.next();
     observer.update();
   }
 }
Esempio n. 7
0
  @Override
  public void notifyObserver() {

    for (final Observer observer : observers) {
      observer.update(currentColor);
    }
  }
Esempio n. 8
0
  public void testMultipleListenersOnSingleObserver() {
    Participant one = new Participant("one");
    Participant two = new Participant("two");

    final Observer obsA = newObserver(one, InterfaceA.class);
    final ObserverListener lisAone = new ObserverListener(one);
    final ObserverListener lisAtwo = new ObserverListener(one);

    obsA.registerListener(lisAone);
    obsA.registerListener(lisAtwo);
    lisAone.expectInvocations(2);
    lisAtwo.expectInvocations(2);

    two.createA(A);
    two.createAB(AB);
    two.registerObject(A);
    two.registerObject(AB);

    Lambda ok =
        new Lambda() {
          @Override
          public boolean func() {
            return lisAone.getCounter() == 0 && lisAtwo.getCounter() == 0;
          }
        };
    boolean result = waitForLambda(3000, ok);
    assertTrue("Count one =  " + lisAone.getCounter() + ", two = " + lisAtwo.getCounter(), result);
  }
Esempio n. 9
0
  /** Recalculates page rectangles. */
  private void updatePageRects() {
    if (mViewRect.width() == 0 || mViewRect.height() == 0) {
      return;
    } else if (mViewMode == SHOW_ONE_PAGE) {
      mPageRectRight.set(mViewRect);
      mPageRectRight.left += mViewRect.width() * mMargins.left;
      mPageRectRight.right -= mViewRect.width() * mMargins.right;
      mPageRectRight.top += mViewRect.height() * mMargins.top;
      mPageRectRight.bottom -= mViewRect.height() * mMargins.bottom;

      mPageRectLeft.set(mPageRectRight);
      mPageRectLeft.offset(-mPageRectRight.width(), 0);

      int bitmapW = (int) ((mPageRectRight.width() * mViewportWidth) / mViewRect.width());
      int bitmapH = (int) ((mPageRectRight.height() * mViewportHeight) / mViewRect.height());
      mObserver.onPageSizeChanged(bitmapW, bitmapH);
    } else if (mViewMode == SHOW_TWO_PAGES) {
      mPageRectRight.set(mViewRect);
      mPageRectRight.left += mViewRect.width() * mMargins.left;
      mPageRectRight.right -= mViewRect.width() * mMargins.right;
      mPageRectRight.top += mViewRect.height() * mMargins.top;
      mPageRectRight.bottom -= mViewRect.height() * mMargins.bottom;

      mPageRectLeft.set(mPageRectRight);
      mPageRectLeft.right = (mPageRectLeft.right + mPageRectLeft.left) / 2;
      mPageRectRight.left = mPageRectLeft.right;

      int bitmapW = (int) ((mPageRectRight.width() * mViewportWidth) / mViewRect.width());
      int bitmapH = (int) ((mPageRectRight.height() * mViewportHeight) / mViewRect.height());
      mObserver.onPageSizeChanged(bitmapW, bitmapH);
    }
  }
 @Override
 public void notifyAllObserver(OperationType operation, int matchid) {
   log.info("Update all observers");
   for (Observer o : observers) {
     o.update(operation, matchid);
   }
 }
Esempio n. 11
0
 public void notifyObservers() {
   Iterator iter = observers.iterator();
   while (iter.hasNext()) {
     Observer observer = (Observer) iter.next();
     observer.update();
   }
 }
Esempio n. 12
0
 public int countProxies(Observer obs) {
   ProxyBusObject proxy;
   int count = 0;
   for (proxy = obs.getFirst(); proxy != null; proxy = obs.getNext(proxy)) {
     ++count;
   }
   return count;
 }
 @CalledByNative
 private static void onProfileDownloadSuccess(
     String accountId, String fullName, String givenName, Bitmap bitmap) {
   ThreadUtils.assertOnUiThread();
   for (Observer observer : sObservers) {
     observer.onProfileDownloaded(accountId, fullName, givenName, bitmap);
   }
 }
Esempio n. 14
0
  /** Upon initialization, send across emberized forms of the (relevant) model definitions */
  public void sendModels(ErrorHandler eh) {
    for (Observer o : observers) {
      Model m = o.getModel();
      for (String docName : m.documents()) {
        for (ObjectDefinition od : m.objects(docName)) {
          try {
            JSONObject model = new JSONObject();
            model.put("modelName", StringUtil.capitalize(od.name));
            JSONObject hash = new JSONObject();
            model.put("model", hash);
            for (FieldDefinition x : od.fields()) {
              hash.put(x.name, attrOf(x.type, x));
            }
            send(model);
          } catch (JSONException ex) {
            logger.error("Error creating models", ex);
          }
        }
        /*
        for (LeaderboardDefinition ld : m.leaderboards(docName)) {
        	for (Grouping g : ld.groupings()) {
        		try {
        			String vn = ld.getViewName(g);
        			ObjectDefinition od = m.getModel(eh, vn);
        			// First define the entry
        			String lbname = StringUtil.capitalize(ld.name) + g.asGroupName();
        			String lbentry = lbname + "Entry";
        			{
        				JSONObject model = new JSONObject();
        				model.put("modelName", lbentry);
        				JSONObject hash = new JSONObject();
        				model.put("model", hash);
        				for (FieldDefinition x : od.fields()) {
        					hash.put(x.name, attrOf(x.type));
        				}
        				send(model);
        			}

        			// Then define the board
        			{
        				JSONObject model = new JSONObject();
        				model.put("modelName", lbname);
        				JSONObject hash = new JSONObject();
        				model.put("model", hash);
        				hash.put("entries", new JSONObject(CollectionUtils.map("rel", "hasMany", "name", lbentry)));
        				send(model);
        			}

        		} catch (JSONException ex) {
        			logger.error("Error creating models", ex);
        		}
        	}
        }
        */
      }
    }
  }
Esempio n. 15
0
 @Override
 public void notifyTimerObserver() {
   if (subjectState == "TimeOff") {
     Farm farm = (Farm) getWorld();
     for (Observer ob : lstObserver) {
       ob.gameOver(farm);
     }
   }
 }
Esempio n. 16
0
  public void notifyObservers() {

    for (int i = 0; i < observers.size(); i++) {

      Observer observer = observers.get(i);

      observer.notice();
    }
  }
Esempio n. 17
0
  public void notifyObserver() {

    // Cycle through all observers and notifies them of
    // price changes

    for (Observer observer : observers) {

      observer.update(ibmPrice, aaplPrice, googPrice);
    }
  }
Esempio n. 18
0
 public void unwatch(int hs) {
   logger.info("Stopping watching handle = " + hs);
   for (Observer o : observers) o.unwatch(hs);
   //		Handle handle = handles.remove(hs);
   //		if (handle == null)
   //			sendError("There is no handle " + hs);
   //		else {
   //			rhandles.remove(handle);
   //			handle.proc.disinterested(this, handle);
   //		}
 }
Esempio n. 19
0
  private void addObserver(Observer<D> observer) throws Exception {
    // verify this observer doesn't already exist
    if (observers.containsKey(observer.getName())) {
      throw new Exception(
          "Observer with name ["
              + observer.getName()
              + "] already exists (observer names MUST be unique)");
    }

    // add to list of observers as well as group
    observers.put(observer.getName(), observer);
    this.groups.addAll(observer.getConfiguration().getGroups());
  }
Esempio n. 20
0
  /** Retrieves the dimensions of this image using an <code>ImageObserver</code>. */
  public static Dimension get(Image image) {
    MutableInteger width = new MutableInteger(-1);
    MutableInteger height = new MutableInteger(-1);

    Observer observer = new Observer(width, height);

    int w = image.getWidth(observer);
    if (w != -1) observer.imageUpdate(image, 0, 0, 0, w, 0);
    int h = image.getHeight(observer);
    if (h != -1) observer.imageUpdate(image, 0, 0, 0, 0, h);

    observer.load();

    return new Dimension(observer.w.value, observer.h.value);
  }
Esempio n. 21
0
  /**
   * This method is the main function of the thread of the collective. It does housekeeping and
   * regularly talks to peers to exchange information. It can be stopped by calling <code>close()
   * </code>.
   *
   * @see #close()
   */
  public final void run() {

    while (shouldLive) {
      // try{
      System.gc();
      removeOldStuff();
      if (!refresh()) {
        Address[] a = observer.getPeerAddresses();
        if (a != null)
          synchronized (cache) {
            for (int i = 0; i < a.length; ++i)
              cache.put(a[i].name, new ContributionBox(a[i], null));
          }
      }
      for (int i = 0; i < REFRESHRATE; i += 1000) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          shouldLive = false;
        }
        if (shouldLive == false) break;
        Thread.yield();
      }
      /*}
      catch( RuntimeException e )
      {
      	Logger.error( "Collective#run()",
      	"Runtime exception caught, something is going wrong",e);

      }*/
    }

    cache = null;
    observer = null;
  }
Esempio n. 22
0
 /** This should be executed in the ActionListener, but it can't. */
 private void update() {
   int value = getInt();
   if (0 <= value && value <= 100) {
     setText(getText());
     observer.update(this, value);
   }
 }
Esempio n. 23
0
 @Override
 public Future onFail(Observer observer) {
   if (isFailed()) {
     observer.apply(value);
   }
   return this;
 }
Esempio n. 24
0
  private void doSignIn() {
    Log.d(TAG, "Committing the sign-in process now");
    assert mSignInAccount != null;

    // Cache the signed-in account name.
    ChromeSigninController.get(mContext).setSignedInAccountName(mSignInAccount.name);

    // Tell the native side that sign-in has completed.
    // This will trigger NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL.
    nativeOnSignInCompleted(mNativeSigninManagerAndroid, mSignInAccount.name);

    // Register for invalidations.
    InvalidationController invalidationController = InvalidationController.get(mContext);
    invalidationController.setRegisteredTypes(mSignInAccount, true, new HashSet<ModelType>());

    // Sign-in to sync.
    ProfileSyncService profileSyncService = ProfileSyncService.get(mContext);
    if (SyncStatusHelper.get(mContext).isSyncEnabled(mSignInAccount)
        && !profileSyncService.hasSyncSetupCompleted()) {
      profileSyncService.setSetupInProgress(true);
      profileSyncService.syncSignIn();
    }

    if (mSignInObserver != null) mSignInObserver.onSigninComplete();

    // All done, cleanup.
    Log.d(TAG, "Signin done");
    mSignInActivity = null;
    mSignInAccount = null;
    mSignInObserver = null;
  }
Esempio n. 25
0
  // constructor
  public Arena(MasterObserver master) {
    status = 0;
    // creating the board
    board = new Piece[sizeOfArena][]; // Size may be change
    for (int i = 0; i < sizeOfArena; i++) board[i] = new Piece[sizeOfArena];

    // creating walls
    createWalls();

    // creating snake
    snake = createSnake();
    snake.initBoard(board);

    // Random generator
    generator = new Random();

    // creating 30 baits and putting one to board
    baits = new ArrayList<Bait>();
    createBaits();
    current = giveBait();

    // initializing observers
    super.master = master;
    super.master.add(this);

    // initializing timer

  }
Esempio n. 26
0
  @Override
  public synchronized void onDrawFrame(GL10 gl) {

    mObserver.onDrawFrame();

    if (mBackgroundColorChanged) {
      gl.glClearColor(
          Color.red(mBackgroundColor) / 255f,
          Color.green(mBackgroundColor) / 255f,
          Color.blue(mBackgroundColor) / 255f,
          Color.alpha(mBackgroundColor) / 255f);
      mBackgroundColorChanged = false;
    }

    gl.glClear(GL10.GL_COLOR_BUFFER_BIT); // | GL10.GL_DEPTH_BUFFER_BIT);
    gl.glLoadIdentity();

    if (USE_PERSPECTIVE_PROJECTION) {
      gl.glTranslatef(0, 0, -6f);
    }

    for (int i = 0; i < mCurlMeshes.size(); ++i) {
      mCurlMeshes.get(i).draw(gl);
    }
  }
Esempio n. 27
0
 private void callVanishObserver(Object ptn, Match m) {
   SikuliEventVanish se = new SikuliEventVanish(ptn, m, _region);
   Object ao = _vanishOb.get(ptn);
   Observer.addEvent(_names.get(ptn), se);
   if (ao != null && ao instanceof SikuliEventObserver) {
     ((SikuliEventObserver) _vanishOb.get(ptn)).targetVanished(se);
   }
 }
Esempio n. 28
0
  @Override
  public void tearDown() throws Exception {
    for (Observer observer : observers) {
      observer.close();
    }
    for (Participant participant : participants) {
      participant.stop();
    }
    participants.clear();
    assertFalse(failure);
    System.gc();
    System.gc();
    System.runFinalization();
    System.runFinalization();

    Thread.sleep(100);
  }
Esempio n. 29
0
  public void testRejection() throws Exception {
    Participant willing = new Participant("willing");
    Participant doubtful = new Participant("doubtful");
    Participant unwilling = new Participant("unwilling");
    Participant consumer = new Participant("consumer");

    willing.createA(A);
    doubtful.createAB(A);
    unwilling.createAB(A);

    unwilling.accepter.accept = false;

    final ObserverListener listener = new ObserverListener(consumer);
    final Observer obs = newObserver(consumer, InterfaceA.class);
    obs.registerListener(listener);

    listener.expectInvocations(2);
    willing.registerObject(A);
    doubtful.registerObject(A);
    unwilling.registerObject(A);

    Lambda ok = new SingleLambda(listener);
    assertTrue(waitForLambda(3000, ok));

    /* now let doubtful kill the connection */
    Thread.sleep(100); // This sleep is necessary to make sure the provider knows it has a session.
    listener.expectInvocations(1);

    Integer sessionid = doubtful.accepter.sessions.get(consumer.bus.getUniqueName());
    assertNotNull(sessionid);
    doubtful.bus.leaveHostedSession(sessionid);

    assertTrue(waitForLambda(3000, ok));

    /* there should only be one object left */
    assertEquals(1, countProxies(obs));

    /* unannounce and reannounce, connection should be restored */
    listener.expectInvocations(1);
    doubtful.unregisterObject(A);
    doubtful.registerObject(A);
    assertTrue(waitForLambda(3000, ok));

    /* now there should only be two objects */
    assertEquals(2, countProxies(obs));
  }
  private void connectionTypeChanged() {
    int newConnectionType = getCurrentConnectionType();
    if (newConnectionType == mConnectionType) return;

    mConnectionType = newConnectionType;
    Log.d(TAG, "Network connectivity changed, type is: " + mConnectionType);
    mObserver.onConnectionTypeChanged(newConnectionType);
  }