@Test
  public void testSoftKeyWeakValue() throws InterruptedException {
    System.setProperty(FinalizeManager.class.getName() + ".thread.enabled", StringPool.FALSE);

    String testKey1 = new String("testKey1");
    String testKey2 = new String("testKey2");
    Object testValue1 = new Object();
    Object testValue2 = new Object();

    ConcurrentMap<String, Object> concurrentReferenceMap =
        new ConcurrentReferenceKeyHashMap<String, Object>(
            new ConcurrentReferenceValueHashMap<Reference<String>, Object>(
                FinalizeManager.WEAK_REFERENCE_FACTORY),
            FinalizeManager.SOFT_REFERENCE_FACTORY);

    Assert.assertNull(concurrentReferenceMap.put(testKey1, testValue1));
    Assert.assertNull(concurrentReferenceMap.put(testKey2, testValue2));
    Assert.assertEquals(2, concurrentReferenceMap.size());
    Assert.assertTrue(concurrentReferenceMap.containsKey(testKey1));
    Assert.assertTrue(concurrentReferenceMap.containsValue(testValue1));
    Assert.assertSame(testValue1, concurrentReferenceMap.get(testKey1));
    Assert.assertTrue(concurrentReferenceMap.containsKey(testKey2));
    Assert.assertTrue(concurrentReferenceMap.containsValue(testValue2));
    Assert.assertSame(testValue2, concurrentReferenceMap.get(testKey2));

    testKey1 = null;

    GCUtil.gc(true);

    ReflectionTestUtil.invoke(FinalizeManager.class, "_pollingCleanup", new Class<?>[0]);

    Assert.assertEquals(2, concurrentReferenceMap.size());
    Assert.assertTrue(concurrentReferenceMap.containsValue(testValue1));
    Assert.assertTrue(concurrentReferenceMap.containsKey(testKey2));
    Assert.assertTrue(concurrentReferenceMap.containsValue(testValue2));
    Assert.assertSame(testValue2, concurrentReferenceMap.get(testKey2));

    GCUtil.fullGC(true);

    ReflectionTestUtil.invoke(FinalizeManager.class, "_pollingCleanup", new Class<?>[0]);

    Assert.assertEquals(1, concurrentReferenceMap.size());
    Assert.assertTrue(concurrentReferenceMap.containsKey(testKey2));
    Assert.assertTrue(concurrentReferenceMap.containsValue(testValue2));
    Assert.assertSame(testValue2, concurrentReferenceMap.get(testKey2));

    testValue2 = null;

    GCUtil.gc(true);

    ReflectionTestUtil.invoke(FinalizeManager.class, "_pollingCleanup", new Class<?>[0]);

    Assert.assertTrue(concurrentReferenceMap.isEmpty());
  }
示例#2
0
  private void initSystemStorageConfig() {
    // add InMemoryStorage used by voldsys$_client_registry
    if (!storageConfigs.containsKey(InMemoryStorageConfiguration.TYPE_NAME)) {
      storageConfigs.put(
          InMemoryStorageConfiguration.TYPE_NAME, new InMemoryStorageConfiguration());
    }

    // add FileStorage config here
    if (!storageConfigs.containsKey(FileBackedCachingStorageConfiguration.TYPE_NAME)) {
      storageConfigs.put(
          FileBackedCachingStorageConfiguration.TYPE_NAME,
          new FileBackedCachingStorageConfiguration(voldemortConfig));
    }
  }
  @Test
  public void testConcurrentMapRemove() {
    final ConcurrentMap<Object, Object> map = new TrieMap<Object, Object>();

    for (int i = 128; i < COUNT; i++) {
      TestHelper.assertFalse(map.remove(i, i));
      TestHelper.assertTrue(null == map.put(i, i));
      TestHelper.assertFalse(map.remove(i, "lol"));
      TestHelper.assertTrue(map.containsKey(i));
      TestHelper.assertTrue(map.remove(i, i));
      TestHelper.assertFalse(map.containsKey(i));
      TestHelper.assertTrue(null == map.put(i, i));
    }
  }
 public static Class<?> findRepository(String name) {
   if (modelCache == null) {
     findModels();
   }
   String className = repoNames.containsKey(name) ? repoNames.get(name) : name;
   return repoCache.get(className);
 }
 public static Class<?> findModel(String name) {
   if (modelCache == null) {
     findModels();
   }
   String className = modelNames.containsKey(name) ? modelNames.get(name) : name;
   return modelCache.get(className);
 }
示例#6
0
 public synchronized void cancelTask(Guid vdsmTaskId) {
   if (_tasks.containsKey(vdsmTaskId)) {
     log.info("Attempting to cancel task '{}'.", vdsmTaskId);
     _tasks.get(vdsmTaskId).stopTask();
     _tasks.get(vdsmTaskId).concreteStartPollingTask();
   }
 }
示例#7
0
  public synchronized ArrayList<AsyncTaskStatus> pollTasks(ArrayList<Guid> vdsmTaskIdList) {
    ArrayList<AsyncTaskStatus> returnValue = new ArrayList<>();

    if (vdsmTaskIdList != null && vdsmTaskIdList.size() > 0) {
      for (Guid vdsmTaskId : vdsmTaskIdList) {
        if (_tasks.containsKey(vdsmTaskId)) {
          // task is still running or is still in the cache:
          _tasks.get(vdsmTaskId).setLastStatusAccessTime();
          returnValue.add(_tasks.get(vdsmTaskId).getLastTaskStatus());
        } else { // task doesn't exist in the manager (shouldn't happen) ->
          // assume it has been ended successfully.
          log.warn(
              "Polling tasks. Task ID '{}' doesn't exist in the manager -> assuming 'finished'.",
              vdsmTaskId);

          AsyncTaskStatus tempVar = new AsyncTaskStatus();
          tempVar.setStatus(AsyncTaskStatusEnum.finished);
          tempVar.setResult(AsyncTaskResultEnum.success);
          returnValue.add(tempVar);
        }
      }
    }

    return returnValue;
  }
示例#8
0
  private void addTaskToManager(SPMTask task) {
    if (task == null) {
      log.error("Cannot add a null task.");
    } else {
      if (!_tasks.containsKey(task.getVdsmTaskId())) {
        log.info(
            "Adding task '{}' (Parent Command '{}', Parameters Type '{}'), {}.",
            task.getVdsmTaskId(),
            task.getParameters().getDbAsyncTask().getActionType(),
            task.getParameters().getClass().getName(),
            task.getShouldPoll() ? "polling started." : "polling hasn't started yet.");

        // Set the indication to true for logging _tasks status on next
        // quartz execution.
        addTaskToMap(task.getVdsmTaskId(), task);
      } else {
        SPMTask existingTask = _tasks.get(task.getVdsmTaskId());
        if (existingTask.getParameters().getDbAsyncTask().getActionType() == VdcActionType.Unknown
            && task.getParameters().getDbAsyncTask().getActionType() != VdcActionType.Unknown) {
          log.info(
              "Task '{}' already exists with action type 'Unknown', now overriding it with action type '{}'",
              task.getVdsmTaskId(),
              task.getParameters().getDbAsyncTask().getActionType());

          // Set the indication to true for logging _tasks status on
          // next quartz execution.
          addTaskToMap(task.getVdsmTaskId(), task);
        }
      }
    }
  }
示例#9
0
  /**
   * Check if the configuration has already been loaded, and if so return that, otherwise attempt to
   * load the configuration from the filesystem and save the result
   *
   * @param path path to the configuration file
   * @return future that eventually contains the JsonObject representing the configuration
   */
  @SuppressFBWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")
  private Future<JsonObject> getOrLoadConfig(final String path) {
    final Future<JsonObject> configFuture = Future.future();

    if (loadedConfigs.containsKey(path)) {
      configFuture.complete(loadedConfigs.get(path));
    } else {
      final Future<JsonObject> loadedConfigFuture = loadAndParseConfigFromFilesystem(path);
      loadedConfigFuture.setHandler(
          new AsyncResultHandler<JsonObject>() {
            @Override
            public void handle(AsyncResult<JsonObject> result) {
              if (result.succeeded()) {
                JsonObject loadedConfig = result.result();
                loadedConfigs.put(path, loadedConfig);
                configFuture.complete(loadedConfig);
              } else {
                configFuture.fail(result.cause());
              }
            }
          });
    }

    return configFuture;
  }
示例#10
0
 public void injectByteCode(String className, byte[] classBytes) throws IOException {
   if (customClasses.containsKey(className)) {
     throw new IOException(
         String.format("The class defined %s has already been loaded.", className));
   }
   customClasses.put(className, classBytes);
 }
  void addInputChannel(RemoteInputChannel listener) {
    checkState(!channelError.get(), "There has been an error in the channel.");

    if (!inputChannels.containsKey(listener.getInputChannelId())) {
      inputChannels.put(listener.getInputChannelId(), listener);
    }
  }
  /* ------------------------------------------------------------ */
  public boolean validate(UserIdentity user) {
    if (_users.containsKey(user.getUserPrincipal().getName())) return true;

    if (loadUser(user.getUserPrincipal().getName()) != null) return true;

    return false;
  }
 private Activity getOrPutActivity(String uri) {
   Activity a = new Activity();
   if (activityDirectory.containsKey(uri)) a = activityDirectory.get(uri);
   else activityDirectory.put(uri, a);
   a.uri = (a.uri == null) ? uri : a.uri;
   return a;
 }
 private Entity getOrPutEntity(String uri) {
   Entity e = new Entity();
   if (entityDirectory.containsKey(uri)) e = entityDirectory.get(uri);
   else entityDirectory.put(uri, e);
   e.uri = (e.uri == null) ? uri : e.uri;
   return e;
 }
示例#15
0
 @Override
 public AbstractTaskModel getModelOrFail(String id) {
   if (!taskManagerHooks.containsKey(id)) {
     throw new IllegalArgumentException(String.format("Id %s is not registered", id));
   }
   return makeTaskModel(id);
 }
示例#16
0
  public void set(Map<String, Sink> newSinkMap) {
    try {
      for (Map.Entry<String, Sink> sink : sinkMap.entrySet()) {
        if (!newSinkMap.containsKey(sink.getKey())) { // removed
          Sink removedSink = sinkMap.remove(sink.getKey());
          if (removedSink != null) {
            log.info(String.format("Removing sink '%s'", sink.getKey()));
            removedSink.close();
          }
        }
      }

      for (Map.Entry<String, Sink> sink : newSinkMap.entrySet()) {
        if (!sinkMap.containsKey(sink.getKey())) { // added
          log.info(String.format("Adding sink '%s'", sink.getKey()));
          sink.getValue().open();
          sinkMap.put(sink.getKey(), sink.getValue());
        }
      }

    } catch (Exception e) {
      log.error("Exception on building SinkManager: " + e.getMessage(), e);
      if (sinkMap.isEmpty()) {
        throw new RuntimeException("At least one sink is needed");
      }
    }
  }
示例#17
0
  private String processRemoveBlanks(final String s) {
    String result = s;
    for (String tag : vRemoveBlanks) {
      if (!P_REMOVE_PAIR_BLANKS.containsKey(tag)) {
        P_REMOVE_PAIR_BLANKS.putIfAbsent(
            tag, Pattern.compile("<" + tag + "(\\s[^>]*)?></" + tag + ">"));
      }
      result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result);
      if (!P_REMOVE_SELF_BLANKS.containsKey(tag)) {
        P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>"));
      }
      result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result);
    }

    return result;
  }
 @Override
 public ServerStatus restartServer(
     final String serverName,
     final int gracefulTimeout,
     final ModelNode domainModel,
     final boolean blocking) {
   stopServer(serverName, gracefulTimeout);
   synchronized (shutdownCondition) {
     for (; ; ) {
       if (shutdown || connectionFinished) {
         throw HostControllerMessages.MESSAGES.hostAlreadyShutdown();
       }
       if (!servers.containsKey(serverName)) {
         break;
       }
       try {
         shutdownCondition.wait();
       } catch (InterruptedException e) {
         Thread.currentThread().interrupt();
         break;
       }
     }
   }
   startServer(serverName, domainModel, blocking);
   return determineServerStatus(serverName);
 }
 /**
  * Loads the cache result, computing it if needed by executing the query phase and otherwise
  * deserializing the cached value into the {@link SearchContext#queryResult() context's query
  * result}. The combination of load + compute allows to have a single load operation that will
  * cause other requests with the same key to wait till its loaded an reuse the same cache.
  */
 public void loadIntoContext(
     final ShardSearchRequest request, final SearchContext context, final QueryPhase queryPhase)
     throws Exception {
   assert canCache(request, context);
   Key key = buildKey(request, context);
   Loader loader = new Loader(queryPhase, context, key);
   Value value = cache.get(key, loader);
   if (loader.isLoaded()) {
     key.shard.requestCache().onMiss();
     // see if its the first time we see this reader, and make sure to register a cleanup key
     CleanupKey cleanupKey =
         new CleanupKey(
             context.indexShard(),
             ((DirectoryReader) context.searcher().getIndexReader()).getVersion());
     if (!registeredClosedListeners.containsKey(cleanupKey)) {
       Boolean previous = registeredClosedListeners.putIfAbsent(cleanupKey, Boolean.TRUE);
       if (previous == null) {
         context.searcher().getIndexReader().addReaderClosedListener(cleanupKey);
       }
     }
   } else {
     key.shard.requestCache().onHit();
     // restore the cached query result into the context
     final QuerySearchResult result = context.queryResult();
     result.readFromWithId(context.id(), value.reference.streamInput());
     result.shardTarget(context.shardTarget());
   }
 }
  @Override
  public synchronized void register(IndexProvider provider) throws RepositoryException {
    if (providers.containsKey(provider.getName())) {
      throw new IndexProviderExistsException(
          JcrI18n.indexProviderAlreadyExists.text(provider.getName(), repository.name()));
    }

    // Set the repository name field ...
    Reflection.setValue(provider, "repositoryName", repository.name());

    // Set the logger instance
    Reflection.setValue(provider, "logger", ExtensionLogger.getLogger(provider.getClass()));

    if (initialized.get()) {
      // This manager is already initialized, so we have to initialize the new provider ...
      doInitialize(provider);
    }

    // Do this last so that it doesn't show up in the list of providers before it's properly
    // initialized ...
    IndexProvider existing = providers.putIfAbsent(provider.getName(), provider);
    if (existing != null) {
      throw new IndexProviderExistsException(
          JcrI18n.indexProviderAlreadyExists.text(provider.getName(), repository.name()));
    }

    // Re-read the index definitions in case there were disabled index definitions that used the
    // now-available provider ...
    readIndexDefinitions();

    // Refresh the index writer ...
    refreshIndexWriter();
  }
 boolean containsNode(NodeID nodeId) {
   nodesReadLock.lock();
   try {
     return nodes.containsKey(nodeId);
   } finally {
     nodesReadLock.unlock();
   }
 }
  @NotNull
  public static KotlinEnvironment getEnvironment(IJavaProject javaProject) {
    if (!cachedEnvironment.containsKey(javaProject)) {
      cachedEnvironment.put(javaProject, new KotlinEnvironment(javaProject));
    }

    return cachedEnvironment.get(javaProject);
  }
  private void updateShardInfo(final String shardName, final PrimaryShardInfo primaryShardInfo) {
    final Optional<DataTree> maybeDataTree = primaryShardInfo.getLocalShardDataTree();
    if (maybeDataTree.isPresent()) {
      if (!knownLocal.containsKey(shardName)) {
        LOG.debug("Shard {} resolved to local data tree - adding local factory", shardName);

        F factory =
            factoryForShard(
                shardName, primaryShardInfo.getPrimaryShardActor(), maybeDataTree.get());
        knownLocal.putIfAbsent(shardName, factory);
      }
    } else if (knownLocal.containsKey(shardName)) {
      LOG.debug("Shard {} invalidating local data tree", shardName);

      knownLocal.remove(shardName);
    }
  }
 public void removeMessageGroup(Object groupId) {
   synchronized (lock) {
     if (!groupIdToMessageGroup.containsKey(groupId)) {
       return;
     }
     groupUpperBound.release(groupIdToMessageGroup.get(groupId).size());
     groupIdToMessageGroup.remove(groupId);
   }
 }
  /** {@inheritDoc} */
  public boolean remove(String name) {
    if (!objects.containsKey(name)) {
      return false;
    }

    IPersistable object = objects.remove(name);
    object.setPersistent(false);
    return true;
  }
 public void deleteServiceAppliance(String saUUID) {
   if (doveServiceApplianceDB.containsKey(saUUID)) {
     OpenDoveServiceAppliance target = doveServiceApplianceDB.remove(saUUID);
     for (OpenDoveObject o : networkMap.values()) {
       OpenDoveNetwork network = (OpenDoveNetwork) o;
       network.removeEGW(target);
     }
   }
 }
 @Override
 public boolean containsKey(Object key) {
   readLock.lock();
   try {
     return delegate.containsKey(key);
   } finally {
     readLock.unlock();
   }
 }
示例#28
0
 public Collection<Guid> getUserIdsForVdsmTaskIds(List<Guid> vdsmTaskIds) {
   Set<Guid> users = new TreeSet<>();
   for (Guid id : vdsmTaskIds) {
     if (_tasks.containsKey(id)) {
       users.add(_tasks.get(id).getParameters().getDbAsyncTask().getUserId());
     }
   }
   return users;
 }
示例#29
0
  @Override
  public void unregisterService(SimpleName node) {
    synchronized (_serverLock) {
      if (!_services.containsKey(node))
        throw new IllegalStateException(node + " is not advertised anyway.");

      _services.remove(node);
    }
  }
  public void createModule(final SModule module) {
    if (myModuleMap.containsKey(module)) {
      return;
    }

    final TransientModelsModule transientModelsModule =
        new TransientModelsModule(module, TransientModelsProvider.this);
    MPSModuleRepository.getInstance().registerModule(transientModelsModule, myOwner);
    myModuleMap.put(module, transientModelsModule);
  }