protected void purgeEntries(Field properties)
      throws IllegalArgumentException, IllegalAccessException {
    if (properties == null) return;

    if (!properties.isAccessible()) properties.setAccessible(true);

    ConcurrentHashMap map = (ConcurrentHashMap) properties.get(null);
    if (map == null) return;

    Iterator<Class> itor = map.keySet().iterator();
    while (itor.hasNext()) {
      Class clazz = itor.next();
      LOG.info("Clazz: " + clazz + " loaded by " + clazz.getClassLoader());
      if (Thread.currentThread().getContextClassLoader().equals(clazz.getClassLoader())) {
        itor.remove();
        LOG.info("removed");
      } else
        LOG.info(
            "not removed: "
                + "contextclassloader="
                + Thread.currentThread().getContextClassLoader()
                + "clazz's classloader="
                + clazz.getClassLoader());
    }
  }
示例#2
0
  public static void removeAll() {
    for (Block block : ignitedblocks.keySet()) remove(block);

    Iterator<Integer> iter = instances.keySet().iterator();
    while (iter.hasNext()) {
      Integer key = iter.next();
      instances.get(key).remove();
    }
  }
 @Override
 public String toString() {
   return "ActivityHandleReferenceFactory[ pendingIds = "
       + pendingIds.keySet()
       + ", handles = "
       + handle2ref.keySet()
       + ", refs = "
       + ref2handle.keySet()
       + " ]";
 }
 public static void cleanup() {
   for (Block block : AFFECTED_BLOCKS.keySet()) {
     TempBlock.revertBlock(block, Material.AIR);
     AFFECTED_BLOCKS.remove(block);
     WALL_BLOCKS.remove(block);
   }
   for (Block block : WALL_BLOCKS.keySet()) {
     TempBlock.revertBlock(block, Material.AIR);
     AFFECTED_BLOCKS.remove(block);
     WALL_BLOCKS.remove(block);
   }
 }
 public static void printAllResults() {
   List<String> l = new ArrayList<String>(procedures.keySet());
   Collections.sort(l);
   for (String e : l) {
     printProcedureResults(e);
   }
 }
示例#6
0
 public void shutdown() {
   this.quit = true;
   // stop everything
   for (RequiresShutdown shutdown : shutdownObjects.keySet()) {
     shutdown.shutdown();
   }
 }
  /** handle actual disconnecting - from ui thread only */
  void doDisconnect() {
    mState = State.kDisconnecting;
    for (RoomObserver obs : mObservers) {
      obs.onRoomDisconnected();
    }
    Set<String> keyset = mRemoteStream.keySet();
    for (String key : keyset) {
      StreamDescription stream = (StreamDescription) mRemoteStream.get(key);
      removeStream(stream);
      triggerStreamRemoved(stream);
    }
    mRemoteStream.clear();

    if (mLocalStream.size() > 0) {
      unpublish();
    }

    synchronized (mSocketLock) {
      if (mIoClient != null) {
        mIoClient.disconnect();
        mIoClient = null;
      }
    }

    mState = State.kDisconnected;
  }
 public static void removeAll() {
   for (Player player : instances.keySet()) {
     WaterReturn wr = instances.get(player);
     if (wr.block != null) wr.block.revertBlock();
   }
   instances.clear();
 }
 private void run(
     Runnable runnable, int numberOfRequests, final ConcurrentHashMap<String, Boolean> results)
     throws InterruptedException {
   Boolean finalResult = true;
   LOGGER.info("Tests start now!");
   final ArrayList<Thread> threads = new ArrayList<>();
   for (int i = 0; i < numberOfRequests; i++) {
     Thread t = new Thread(runnable, "pipeline" + i);
     threads.add(t);
   }
   for (Thread t : threads) {
     Thread.sleep(1000 * (new Random().nextInt(3) + 1));
     t.setUncaughtExceptionHandler(
         new Thread.UncaughtExceptionHandler() {
           public void uncaughtException(Thread t, Throwable e) {
             LOGGER.error("Exception " + e + " from thread " + t);
             results.put(t.getName(), false);
           }
         });
     t.start();
   }
   for (Thread t : threads) {
     int i = threads.indexOf(t);
     if (i == (numberOfRequests - 1)) {
       //                takeHeapDump(dumpDir, i);
     }
     t.join();
   }
   for (String threadId : results.keySet()) {
     finalResult = results.get(threadId) && finalResult;
   }
   assertThat(finalResult, is(true));
 }
示例#10
0
  @Override
  public void dropTable(String databaseName, String tableName) {
    List<String> locations = listAllDataPaths(this, databaseName, tableName);

    SchemaTableName schemaTableName = new SchemaTableName(databaseName, tableName);
    Table table = relations.remove(schemaTableName);
    if (table == null) {
      throw new TableNotFoundException(schemaTableName);
    }
    views.remove(schemaTableName);
    partitions
        .keySet()
        .stream()
        .filter(partitionName -> partitionName.matches(databaseName, tableName))
        .forEach(partitions::remove);

    // remove data
    for (String location : locations) {
      if (location != null) {
        File directory = new File(URI.create(location));
        checkArgument(
            isParentDir(directory, baseDirectory),
            "Table directory must be inside of the metastore base directory");
        deleteRecursively(directory);
      }
    }
  }
示例#11
0
  @Override
  public void onReconnected() {
    log.info("reconnected");
    if (mode.contains(MODE.RESEND_SUBSCRIBE_ON_RECONNECTED)) {

      Set<String> channels;

      // channel as sourceDispatcherId
      channels = new HashSet<String>();
      channels.add(getSourceDispatcherId());
      driverImpl.subscribeChannels(channels);

      // channels as object_IDs registered with localObjectsMap
      channels = localObjectsMap.keySet();
      if (!channels.isEmpty()) {
        driverImpl.subscribeChannels(channels);
      }

      // all channels registered with subscribersMap
      channels = subscribersMap.getSubscribedChannels();
      if (!channels.isEmpty()) {
        driverImpl.subscribeChannels(channels);
      }

      // re-SUBSCRIBE completed with all the registered channels.
      pubSubDriverSuspended = false; // Resumed
    } else {
      // You may add some code here to inform other objects that
      // the network connectivity has resumed or the pubsub server
      // has become available.
    }
  }
示例#12
0
  /** This contacts the master to find if any of the pending acks are completed, */
  public synchronized void checkAcks() {
    LOG.debug("agent acks waiting for master: " + pending);

    // TODO (make this a batch operation with only one RPC call)
    List<String> done = new ArrayList<String>();
    for (String k : pending.keySet()) {
      try {
        boolean acked = client.checkAck(k);
        if (acked) {
          done.add(k);
        }
      } catch (IOException e) {
        // TODO (jon) there is a potential inconsistency here if master comms
        // fail (but this is recovered when retry happens).
        LOG.error("Master connection exception", e);
      }
    }

    for (String k : done) {
      try {
        listener.end(k);
        pending.remove(k);
        LOG.debug("removed ack tag from agent's ack queue: " + k);
      } catch (IOException e) {
        LOG.error("problem notifying agent pending ack queue", e);
      }
    }
  }
 public ArrayList<String> getEconPlayers() {
   ArrayList<String> econplayers = new ArrayList<String>();
   for (String player : hyperPlayers.keySet()) {
     econplayers.add(player);
   }
   return econplayers;
 }
示例#14
0
 public static ArrayList<Player> getPlayers() {
   ArrayList<Player> players = new ArrayList<Player>();
   for (Player player : instances.keySet()) {
     players.add(player);
   }
   return players;
 }
  private static void block(Player player) {
    for (int id : instances.keySet()) {
      EarthBlast blast = instances.get(id);

      if (blast.player.equals(player)) {
        continue;
      }

      if (!blast.location.getWorld().equals(player.getWorld())) {
        continue;
      }

      if (!blast.progressing) {
        continue;
      }

      if (GeneralMethods.isRegionProtectedFromBuild(player, "EarthBlast", blast.location)) {
        continue;
      }

      Location location = player.getEyeLocation();
      Vector vector = location.getDirection();
      Location mloc = blast.location;
      if (mloc.distance(location) <= RANGE
          && GeneralMethods.getDistanceFromLine(vector, location, blast.location) < deflectrange
          && mloc.distance(location.clone().add(vector))
              < mloc.distance(location.clone().add(vector.clone().multiply(-1)))) {
        blast.breakBlock();
      }
    }
  }
  private static void redirectTargettedBlasts(Player player, ArrayList<EarthBlast> ignore) {
    for (int id : instances.keySet()) {
      EarthBlast blast = instances.get(id);

      if (!blast.progressing || ignore.contains(blast)) {
        continue;
      }

      if (!blast.location.getWorld().equals(player.getWorld())) {
        continue;
      }

      if (GeneralMethods.isRegionProtectedFromBuild(player, "EarthBlast", blast.location)) {
        continue;
      }

      if (blast.player.equals(player)) {
        blast.redirect(player, getTargetLocation(player));
      }

      Location location = player.getEyeLocation();
      Vector vector = location.getDirection();
      Location mloc = blast.location;
      if (mloc.distance(location) <= RANGE
          && GeneralMethods.getDistanceFromLine(vector, location, blast.location) < deflectrange
          && mloc.distance(location.clone().add(vector))
              < mloc.distance(location.clone().add(vector.clone().multiply(-1)))) {
        blast.redirect(player, getTargetLocation(player));
      }
    }
  }
示例#17
0
 public void run() {
   for (String name : lastLoc.keySet()) {
     Player player = plugin.getServer().getPlayer(name);
     if (player == null) {
       removePlayer(name);
     } else {
       // workaround for bukkit issue
       String prevWorld = lastLoc.get(name).getWorld().getName();
       String curWorld = player.getLocation().getWorld().getName();
       if (prevWorld.equals(curWorld)) {
         if (player.getLocation().distance(lastLoc.get(name)) < 1) {
           continue;
         }
       }
       // if distance between player's current location and stored
       // location is less than 1, this move is not active; if active
       // and ignore vehicle movement is set and player in vehicle,
       // then update location, but don't count this move as active
       addPlayer(player);
       if (!isIgnoreVehicleMovement || !player.isInsideVehicle()) {
         afkBooter.getPlayerActivity().recordActivity(name);
       }
     }
   }
 }
  @Test
  public void testNumberOfThreads() {
    final ConcurrentHashMap<Long, Long> threads = new ConcurrentHashMap<Long, Long>();
    // parallelMerge into 3 streams and observeOn for each
    // we expect 3 threads in the output
    Observable.parallelMerge(getStreams(), 3)
        .flatMap(
            new Func1<Observable<String>, Observable<String>>() {

              @Override
              public Observable<String> call(Observable<String> o) {
                // for each of the parallel
                return o.observeOn(Schedulers.newThread());
              }
            })
        .toBlocking()
        .forEach(
            new Action1<String>() {

              @Override
              public void call(String o) {
                System.out.println("o: " + o + " Thread: " + Thread.currentThread().getId());
                threads.put(Thread.currentThread().getId(), Thread.currentThread().getId());
              }
            });

    assertTrue(
        threads.keySet().size()
            <= 3); // can be less than since merge doesn't block threads and may not use all of them
  }
示例#19
0
 protected void kill() {
   boolean hooked = false;
   AtomicInteger count = null;
   Map<RouteResultsetNode, BackendConnection> killees = null;
   for (RouteResultsetNode node : target.keySet()) {
     BackendConnection c = target.get(node);
     if (c != null) {
       if (!hooked) {
         hooked = true;
         killees = new HashMap<RouteResultsetNode, BackendConnection>();
         count = new AtomicInteger(0);
       }
       killees.put(node, c);
       count.incrementAndGet();
     }
   }
   if (hooked) {
     ConnectionMeta conMeta = new ConnectionMeta(null, null, -1, true);
     for (Entry<RouteResultsetNode, BackendConnection> en : killees.entrySet()) {
       KillConnectionHandler kill = new KillConnectionHandler(en.getValue(), this);
       MycatConfig conf = MycatSystem.getInstance().getConfig();
       PhysicalDBNode dn = conf.getDataNodes().get(en.getKey().getName());
       try {
         dn.getConnectionFromSameSource(conMeta, en.getValue(), kill, en.getKey());
       } catch (Exception e) {
         LOGGER.error("get killer connection failed for " + en.getKey(), e);
         kill.connectionError(e, null);
       }
     }
   }
 }
  void abortAll() throws IOException {
    Iterator myTxns = theTxns.keySet().iterator();

    while (myTxns.hasNext()) {
      TxnId myId = (TxnId) myTxns.next();

      TxnState myState = getState(myId);

      try {
        int myStatus = myState.getStatus();

        if ((myStatus == TransactionConstants.PREPARED)
            || (myStatus == TransactionConstants.ACTIVE)) {

          /*
           *  AbortAll is a naive operation in that it has no
           *  awareness of a specific transaction thus it cannot
           *  explicitly vote one of them off so we must do it
           *  ourselves
           */
          myState.vote();
          myState.abort();
          myTxns.remove();
        }

      } catch (TransactionException aTE) {
        // Whoops, got nailed checking status, logged in the call
        // nothing to do.
      }
    }
  }
示例#21
0
 public static void revertBlock(Block block) {
   for (int ID : instances.keySet()) {
     if (instances.get(ID).blockInAffectedBlocks(block)) {
       instances.get(ID).affectedblocks.remove(block);
     }
   }
 }
  @Override
  public boolean clearExpired(Date date) {
    boolean clearedAny = false;
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();

    for (ConcurrentHashMap.Entry<String, Cookie> entry : cookies.entrySet()) {
      String name = entry.getKey();
      Cookie cookie = entry.getValue();
      if (cookie.isExpired(date)) {
        // Clear cookies from local store
        cookies.remove(name);

        // Clear cookies from persistent store
        prefsWriter.remove(COOKIE_NAME_PREFIX + name);

        // We've cleared at least one
        clearedAny = true;
      }
    }

    // Update names in persistent store
    if (clearedAny) {
      prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));
    }
    prefsWriter.commit();

    return clearedAny;
  }
示例#23
0
 // should either be moved to a higher level (need to confirm we wrote the beacon frame before
 // looking for responses)
 // OR, do it automatically sometimes so higher level doesn't have to call it at all.
 public Set<NodeAddress> scan() {
   beacon.broadcast();
   // wait for some time and then return the list of beacon frames
   Util.sleep(20, TimeUnit.MILLISECONDS);
   return Collections.unmodifiableSet(
       nodes.keySet()); // XXX is this necessary? caller can just call getNodes() after scan()
 }
 public void _controllerShowSwitches(CommandInterpreter ci) {
   Set<Long> sids = switches.keySet();
   StringBuffer s = new StringBuffer();
   int size = sids.size();
   if (size == 0) {
     ci.print("switches: empty");
     return;
   }
   Iterator<Long> iter = sids.iterator();
   s.append("Total: " + size + " switches\n");
   while (iter.hasNext()) {
     Long sid = iter.next();
     Date date = switches.get(sid).getConnectedDate();
     String switchInstanceName = ((SwitchHandler) switches.get(sid)).getInstanceName();
     s.append(
         switchInstanceName
             + "/"
             + HexString.toHexString(sid)
             + " connected since "
             + date.toString()
             + "\n");
   }
   ci.print(s.toString());
   return;
 }
  @Override
  public void getExtraResponse() {
    try {
      Logger.getLogger(this.getClass()).info("[EXTRA-QUORUM] Getting last server info");
      String lastServerURL = getReplicasNotResponded(responseList.keySet(), urlList);

      Logger.getLogger(this.getClass()).info("[EXTRA-QUORUM] Last Server : " + lastServerURL);
      AnacomPortType port = getPortType(lastServerURL);

      // Sync Replica request
      responseType = port.getBalanceAndPhoneList(operatorSimpleTypeRequest);

      // Save vote
      BalanceAndPhoneListType type = (BalanceAndPhoneListType) responseType;
      voteList.addVote(type.getVersion(), responseType);

      // Vote again
      responseType = voteList.getBestResponse(getReplicaLength());

      // If cant find best answer with all replicas then is catastrophe
      if (responseType == null) {
        Logger.getLogger(this.getClass()).info("[ERR] JA FOSTE");
        System.exit(-1);
      }
    } catch (OperatorPrefixDoesNotExistRemoteException e) {
      throw new OperatorPrefixDoesNotExistException(e.getFaultInfo().getOperatorPrefix());
    }
  }
示例#26
0
  public static void removeAll() {
    for (int id : instances.keySet()) {
      instances.get(id).cancel();
    }

    instances.clear();
  }
 /**
  * Gets a {@link JSONObject} containing the post data supplied with the current request as
  * key-value pairs appended with the instrumentation data.
  *
  * <p>* @param instrumentationData {@link ConcurrentHashMap} with instrumentation values
  *
  * @return A {@link JSONObject} containing the post data supplied with the current request as
  *     key-value pairs and the instrumentation meta data.
  */
 public JSONObject getPostWithInstrumentationValues(
     ConcurrentHashMap<String, String> instrumentationData) {
   JSONObject extendedPost = new JSONObject();
   try {
     // Add original parameters
     if (params_ != null) {
       JSONObject originalParams = new JSONObject(params_.toString());
       Iterator<String> keys = originalParams.keys();
       while (keys.hasNext()) {
         String key = keys.next();
         extendedPost.put(key, originalParams.get(key));
       }
     }
     // Append instrumentation metadata
     if (instrumentationData.size() > 0) {
       JSONObject instrObj = new JSONObject();
       Set<String> keys = instrumentationData.keySet();
       try {
         for (String key : keys) {
           instrObj.put(key, instrumentationData.get(key));
           instrumentationData.remove(key);
         }
         extendedPost.put(Defines.Jsonkey.Branch_Instrumentation.getKey(), instrObj);
       } catch (JSONException ignore) {
       }
     }
   } catch (JSONException ignore) {
   } catch (ConcurrentModificationException ex) {
     extendedPost = params_;
   }
   return extendedPost;
 }
  /**
   * Unmount all file systems for the given dataspace
   *
   * @param spaceUri dataspace uri
   */
  private void unmountAllFileSystems(final DataSpacesURI spaceUri) {

    DataSpacesURI spacePart = spaceUri.getSpacePartOnly();

    final ConcurrentHashMap<String, FileObject> spaceRoots = mountedSpaces.remove(spacePart);

    VFSMountManagerHelper.closeFileSystems(spaceRoots.keySet());
  }
示例#29
0
  public static void removeAll() {
    for (Player player : instances.keySet()) {
      instances.get(player).remove();
    }

    // for (TempBlock block : water)
    // block.revertBlock();
  }
 @Override
 public void invalidate(ComputingCache.KeyPredicate<K> keyPredicate) {
   for (Iterator<K> iterator = map.keySet().iterator(); iterator.hasNext(); ) {
     if (keyPredicate.apply(iterator.next())) {
       iterator.remove();
     }
   }
 }