@Override
    public void run() {
      try {
        s_logger.debug("HostStatsCollector is running...");

        SearchCriteria<HostVO> sc = _hostDao.createSearchCriteria();
        sc.addAnd("status", SearchCriteria.Op.EQ, Status.Up.toString());
        sc.addAnd("type", SearchCriteria.Op.NEQ, Host.Type.Storage.toString());
        sc.addAnd("type", SearchCriteria.Op.NEQ, Host.Type.ConsoleProxy.toString());
        sc.addAnd("type", SearchCriteria.Op.NEQ, Host.Type.SecondaryStorage.toString());
        ConcurrentHashMap<Long, HostStats> hostStats = new ConcurrentHashMap<Long, HostStats>();
        List<HostVO> hosts = _hostDao.search(sc, null);
        for (HostVO host : hosts) {
          if (host.getId() != null) {
            HostStatsEntry stats = (HostStatsEntry) _agentMgr.getHostStatistics(host.getId());
            if (stats != null) {
              hostStats.put(host.getId(), stats);
            } else {
              s_logger.warn("Received invalid host stats for host: " + host.getId());
            }
          } else {
            s_logger.warn("Host: " + host.getId() + " does not exist, skipping host statistics");
          }
        }
        _hostStats = hostStats;
      } catch (Throwable t) {
        s_logger.error("Error trying to retrieve host stats", t);
      }
    }
  public void putStationPlayer(byte type, short id, PlayerController controller) {

    ConcurrentHashMap<Short, PlayerController> map = getStationPlayerMap(type);
    if (map != null) {
      map.put(id, controller);
    }
  }
 public void stopSingleSongs() {
   for (Entry<Song, PlayerController> entry : singleSongPlayers.entrySet()) {
     PlayerController controller = entry.getValue();
     controller.close(true);
   }
   singleSongPlayers.clear();
 }
  @Override
  public Iterable<Message> getNewMessages(String remoteNodeId) throws RemoteException {
    logger.debug("Requesting the new messages from node [" + remoteNodeId + "]");

    LinkedBlockingQueue<Message> newMessages = new LinkedBlockingQueue<Message>();

    for (MessageContainer messageContainer : broadcastedMessagesQueue) {
      if (!synchronizationTime.containsKey(remoteNodeId)
          || synchronizationTime.get(remoteNodeId) < messageContainer.getTimeStamp()) {
        newMessages.add(messageContainer.getMessage());
        logger.debug(
            "Message [" + messageContainer.getMessage() + "] added to the new messages to send");
      }
    }

    // set the synchronization time of the node
    long timeStamp = new DateTime().getMillis();
    if (synchronizationTime.containsKey(remoteNodeId)) {
      synchronizationTime.replace(remoteNodeId, timeStamp);
      logger.debug("Synchronization time replaced by new one");
    } else {
      synchronizationTime.put(remoteNodeId, timeStamp);
      logger.debug("Synchronization time setted by first time");
    }
    logger.debug("Node [" + remoteNodeId + "] synchronized at [" + timeStamp + "]");

    return newMessages;
  }
  public static Delegator getDelegator(String delegatorName) {
    if (delegatorName == null) {
      delegatorName = "default";
      // Debug.logWarning(new Exception("Location where getting delegator with null name"), "Got a
      // getGenericDelegator call with a null delegatorName, assuming default for the name.",
      // module);
    }
    do {
      Delegator delegator = delegatorCache.get(delegatorName);

      if (delegator != null) {
        // setup the Entity ECA Handler
        delegator.initEntityEcaHandler();
        // Debug.logInfo("got delegator(" + delegatorName + ") from cache", module);

        // setup the distributed CacheClear
        delegator.initDistributedCacheClear();

        return delegator;
      }
      try {
        delegator = UtilObject.getObjectFromFactory(DelegatorFactory.class, delegatorName);
      } catch (ClassNotFoundException e) {
        Debug.logError(e, module);
      }
      // Debug.logInfo("putting delegator(" + delegatorName + ") into cache", module);
      delegatorCache.putIfAbsent(delegatorName, delegator);
    } while (true);
  }
Esempio n. 6
0
 public boolean joinTournament(
     UUID userId, UUID tableId, String name, String playerType, int skill) throws GameException {
   if (controllers.containsKey(tableId)) {
     return controllers.get(tableId).joinTournament(userId, name, playerType, skill);
   }
   return false;
 }
Esempio n. 7
0
 /**
  * Starts the Match from a non tournament table
  *
  * @param userId table owner
  * @param roomId
  * @param tableId
  */
 public void startMatch(UUID userId, UUID roomId, UUID tableId) {
   if (controllers.containsKey(tableId)) {
     controllers.get(tableId).startMatch(userId);
     // chat of start dialog can be killed
     ChatManager.getInstance().destroyChatSession(controllers.get(tableId).getChatId());
   }
 }
 @Benchmark
 public void measureFollowThreads(Ids ids) {
   for (String s : ids.ids) {
     mapFollowThreads.remove(s);
     mapFollowThreads.put(s, s);
   }
 }
 @Benchmark
 public void measureDefault(Ids ids) {
   for (String s : ids.ids) {
     mapSingle.remove(s);
     mapSingle.put(s, s);
   }
 }
 private <T extends Object> Result doCircuitBreak(Invoker<?> invoker, Invocation invocation)
     throws RpcException {
   String interfaceName = invoker.getUrl().getParameter(Constants.INTERFACE_KEY);
   String circuitBreaker = interfaceName + "CircuitBreak";
   incrementBreakCount(invoker, invocation);
   try {
     logger.info("[{}] check has class [{}] to handle circuit break", localHost, circuitBreaker);
     Invoker<?> breakerInvoker = null;
     if (CIRCUIT_BREAKER_INVOKER_CACHE.containsKey(circuitBreaker)) {
       breakerInvoker = CIRCUIT_BREAKER_INVOKER_CACHE.get(circuitBreaker);
     } else {
       Class<T> breakerType = (Class<T>) Class.forName(circuitBreaker);
       Class<T> interfaceType = (Class<T>) Class.forName(interfaceName);
       if (interfaceType.isAssignableFrom(breakerType)) {
         logger.info("[{}] handle circuit break by class [{}]", localHost, circuitBreaker);
         T breaker = breakerType.newInstance();
         breakerInvoker = proxyFactory.getInvoker(breaker, interfaceType, invoker.getUrl());
         Invoker<?> oldInvoker =
             CIRCUIT_BREAKER_INVOKER_CACHE.putIfAbsent(circuitBreaker, breakerInvoker);
         if (oldInvoker != null) {
           breakerInvoker = oldInvoker;
         }
       }
     }
     if (breakerInvoker != null) {
       return breakerInvoker.invoke(invocation);
     }
   } catch (Exception e) {
     logger.error("failed to invoke circuit breaker", e);
   }
   logger.info("[{}] handle circuit break by exception", localHost);
   CircuitBreakerException baseBusinessException =
       new CircuitBreakerException(interfaceName, invocation.getMethodName());
   throw baseBusinessException;
 }
 private void caughtException(Invoker<?> invoker, Invocation invocation, Exception e) {
   String interfaceName = invoker.getUrl().getParameter(Constants.INTERFACE_KEY);
   String method = invocation.getMethodName();
   StringBuffer interfaceConfig = new StringBuffer(Config.DUBBO_REFERENCE_PREFIX);
   interfaceConfig.append(interfaceName);
   StringBuffer methodConfig = new StringBuffer(interfaceConfig.toString());
   methodConfig.append(".").append(method);
   String methodKey = methodConfig.toString();
   int timeout =
       invoker
           .getUrl()
           .getMethodParameter(
               invocation.getMethodName(), Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT);
   int limit = Config.getBreakLimit(invoker, invocation);
   // 一个异常的有效期,是通过连续出现异常数量乘以每个调用的超时时间,比如你配置连续出现10次异常之后进行服务降级,并且每次服务调用的超时时间是2000ms的话,同时
   // 每个服务重试次数是为2次,那么就是在(2+1)*2000*10
   ExceptionMarker breakMarker =
       new ExceptionMarker(System.currentTimeMillis(), limit * timeout, e);
   if (!breakCounterMap.containsKey(methodKey)) {
     BreakCounter oldValue = breakCounterMap.putIfAbsent(methodKey, new BreakCounter(methodKey));
     // 返回的oldValue为空,表示之前没有创建了赌赢的异常计数器,则需要对它分配一个loop
     if (oldValue == null) {
       nextLoop().register(breakCounterMap.get(methodKey));
     }
   }
   BreakCounter counter = breakCounterMap.get(methodKey);
   counter.addExceptionMarker(breakMarker);
   logger.info(
       "[{}] caught exception for rpc invoke [{}.{}],current exception count [{}]",
       localHost,
       interfaceName,
       method,
       counter.getCurrentExceptionCount());
 }
Esempio n. 12
0
 public void sendMessage(String receivers, String msg, String sender) {
   String messageString = "MESSAGE#" + sender + "#" + msg;
   String[] receiversarray = receivers.split(",");
   if (receiversarray.length == 1) {
     String receiver = receiversarray[0];
     if (receiver.equals("*")) {
       for (Handler handler : handlers.values()) {
         handler.sendMessage(messageString);
         Logger.getLogger(EchoServer.class.getName())
             .log(
                 Level.INFO,
                 handler.getUsername() + " Sent a message to all: " + messageString,
                 new Object[] {handler.getUsername()});
       }
     } else {
       Handler handler = (Handler) handlers.get(receiver);
       handler.sendMessage(messageString);
       Logger.getLogger(EchoServer.class.getName())
           .log(
               Level.INFO,
               handler.getUsername() + " Sent a message: " + messageString + " to: " + receiver,
               new Object[] {handler.getUsername()});
     }
   }
 }
Esempio n. 13
0
 @Override
 public void close() {
   for (OScheduledEvent event : events.values()) {
     event.interrupt();
   }
   events.clear();
 }
  private ConcurrentHashMap<Long, Book> seedData() {
    ConcurrentHashMap<Long, Book> bookMap = new ConcurrentHashMap<Long, Book>();
    Book book = new Book();
    book.setIsbn(1);
    book.setCategory("computer");
    book.setTitle("Java Concurrency in Practice");
    try {
      book.setCoverimage(new URL("http://goo.gl/N96GJN"));
    } catch (MalformedURLException e) {
      // eat the exception
    }
    bookMap.put(book.getIsbn(), book);

    book = new Book();
    book.setIsbn(2);
    book.setCategory("computer");
    book.setTitle("Restful Web Services");
    try {
      book.setCoverimage(new URL("http://goo.gl/ZGmzoJ"));
    } catch (MalformedURLException e) {
      // eat the exception
    }
    bookMap.put(book.getIsbn(), book);

    return bookMap;
  }
Esempio n. 15
0
 public FileConfiguration gFC(String fileConfiguration) {
   if (configs.containsKey(fileConfiguration)) {
     return configs.get(fileConfiguration);
   } else {
     return null;
   }
 }
Esempio n. 16
0
  public WxClient with(AppSetting appSetting) {
    if (!wxClients.containsKey(key(appSetting))) {
      String url = WxEndpoint.get("url.token.get");
      String clazz = appSetting.getTokenHolderClass();

      AccessTokenHolder accessTokenHolder = null;
      if (clazz == null || "".equals(clazz)) {
        try {
          accessTokenHolder = (AccessTokenHolder) Class.forName(clazz).newInstance();
          accessTokenHolder.setClientId(appSetting.getAppId());
          accessTokenHolder.setClientSecret(appSetting.getSecret());
          accessTokenHolder.setTokenUrl(url);
        } catch (Exception e) {
          accessTokenHolder =
              new DefaultAccessTokenHolder(url, appSetting.getAppId(), appSetting.getSecret());
        }
      } else {
        accessTokenHolder =
            new DefaultAccessTokenHolder(url, appSetting.getAppId(), appSetting.getSecret());
      }

      WxClient wxClient =
          new WxClient(appSetting.getAppId(), appSetting.getSecret(), accessTokenHolder);
      wxClients.putIfAbsent(key(appSetting), wxClient);
    }

    return wxClients.get(key(appSetting));
  }
  public Raster getFrame() {

    // lock the model so other people don't modify it while we do paint
    // calls based on it.
    synchronized (m) {
      // presumes that you instantiated Raster with a PGraphics.
      PGraphics myRaster = (PGraphics) (r.getRaster());
      myRaster.beginDraw();

      // TODO THIS SHOULD BE THE NORMAL WAY TO FIND NEW PEOPLE/CREATE NEW SPRITES
      ConcurrentHashMap<Integer, Person> people = m.getPeople();
      Iterator<Person> iter = people.values().iterator();
      while (iter.hasNext()) {
        Person p = iter.next();
        if (p.isNew()) {
          // TODO instantiate new sprites here
          Cross cross = new Cross(spriteIndex, r, p, 1, 1, sm, 3, 3); // 3x3 cross
          int[] loc = p.getLoc();
          // System.out.println(loc[0]+" "+loc[1]);
          cross.moveTo(loc[0] * tileSize, loc[1] * tileSize);
          cross.addListener(this);
          // sprites.add(cross);
          sprites.put(spriteIndex, cross);
          spriteIndex++;
        }
      }

      /*
      myRaster.background(0);		// clear the raster
      Cross cross = new Cross(r, null, 1, 1, 3, 3);		// 3x3 cross
      boolean[] sensorlist = m.getSensors();
      for(int i=0; i<sensorlist.length; i++){	// sensorlist is 16x11
      	if(sensorlist[i]){
      		int x = i % 16;			// probably shouldn't be static values
      		int y = i / 16;
      		// position is offset by 1 because of the extra column on each side
      		cross.moveTo((x+1)*tileSize, y*tileSize);	// moves instance of sprite to active tile
      		cross.draw();			// draws instance
      	}
      }
      */

      // TODO THIS SHOULD BE THE NORMAL WAY TO DRAW ALL SPRITES
      try {
        myRaster.background(0); // clear the raster
        Iterator<Sprite> spriteiter = sprites.values().iterator();
        while (spriteiter.hasNext()) {
          Sprite sprite = (Sprite) spriteiter.next();
          sprite.draw();
        }
      } catch (ConcurrentModificationException e) {
        // TODO WHY DOES IT THROW THESE ERRORS?
        e.printStackTrace();
      }

      // myRaster.background(255,0,0); // FULLY ON
      myRaster.endDraw();
    }
    return r;
  }
Esempio n. 18
0
  @Override
  public boolean updateQuitLoc(final PlayerAuth auth) {
    if (!cache.containsKey(auth.getNickname())) {
      return false;
    }
    final PlayerAuth cachedAuth = cache.get(auth.getNickname());
    final double oldX = cachedAuth.getQuitLocX();
    final double oldY = cachedAuth.getQuitLocY();
    final double oldZ = cachedAuth.getQuitLocZ();
    final String oldWorld = cachedAuth.getWorld();

    cachedAuth.setQuitLocX(auth.getQuitLocX());
    cachedAuth.setQuitLocY(auth.getQuitLocY());
    cachedAuth.setQuitLocZ(auth.getQuitLocZ());
    cachedAuth.setWorld(auth.getWorld());
    exec.execute(
        new Runnable() {
          @Override
          public void run() {
            if (!source.updateQuitLoc(auth)) {
              if (cache.containsKey(auth.getNickname())) {
                PlayerAuth cachedAuth = cache.get(auth.getNickname());
                cachedAuth.setQuitLocX(oldX);
                cachedAuth.setQuitLocY(oldY);
                cachedAuth.setQuitLocZ(oldZ);
                cachedAuth.setWorld(oldWorld);
              }
            }
          }
        });
    return true;
  }
Esempio n. 19
0
 public boolean submitDeck(UUID userId, UUID tableId, DeckCardLists deckList)
     throws MageException {
   if (controllers.containsKey(tableId)) {
     return controllers.get(tableId).submitDeck(userId, deckList);
   }
   return false;
 }
Esempio n. 20
0
  @Override
  public boolean updateSession(final PlayerAuth auth) {
    if (!cache.containsKey(auth.getNickname())) {
      return false;
    }
    PlayerAuth cachedAuth = cache.get(auth.getNickname());
    final String oldIp = cachedAuth.getIp();
    final long oldLastLogin = cachedAuth.getLastLogin();
    final String oldRealName = cachedAuth.getRealName();

    cachedAuth.setIp(auth.getIp());
    cachedAuth.setLastLogin(auth.getLastLogin());
    cachedAuth.setRealName(auth.getRealName());
    exec.execute(
        new Runnable() {
          @Override
          public void run() {
            if (!source.updateSession(auth)) {
              if (cache.containsKey(auth.getNickname())) {
                PlayerAuth cachedAuth = cache.get(auth.getNickname());
                cachedAuth.setIp(oldIp);
                cachedAuth.setLastLogin(oldLastLogin);
                cachedAuth.setRealName(oldRealName);
              }
            }
          }
        });
    return true;
  }
Esempio n. 21
0
 public void endGame(UUID tableId) {
   if (controllers.containsKey(tableId)) {
     if (controllers.get(tableId).endGameAndStartNextGame()) {
       removeTable(tableId);
     }
   }
 }
Esempio n. 22
0
  /** 解析Intent */
  private void parseIntent(final Intent intent) {
    final Bundle arguments = intent.getExtras();
    if (arguments != null) {
      if (arguments.containsKey(EXTRA_DIRECTORY)) {
        String directory = arguments.getString(EXTRA_DIRECTORY);
        Logger.i("onStartCommand:" + directory);
        // 扫描文件夹
        if (!mScanMap.containsKey(directory)) mScanMap.put(directory, "");
      } else if (arguments.containsKey(EXTRA_FILE_PATH)) {
        // 单文件
        String filePath = arguments.getString(EXTRA_FILE_PATH);
        Logger.i("onStartCommand:" + filePath);
        if (!StringUtils.isEmpty(filePath)) {
          if (!mScanMap.containsKey(filePath))
            mScanMap.put(filePath, arguments.getString(EXTRA_MIME_TYPE));
          //					scanFile(filePath, arguments.getString(EXTRA_MIME_TYPE));
        }
      }
    }

    if (mServiceStatus == SCAN_STATUS_NORMAL || mServiceStatus == SCAN_STATUS_END) {
      new Thread(this).start();
      // scan();
    }
  }
Esempio n. 23
0
  public AsymmetricCipherKeyPair getKeyPair(
      int keySize, String algorithm, String RNGAlgorithm, String RNGProvider) {
    AsymmetricCipherKeyPair pair = serverKeys.get(algorithm);
    if (pair != null) {
      return pair;
    }

    if (provider == null) {
      return pair;
    }

    SecureRandom secureRandom = getSecureRandom(RNGAlgorithm, RNGProvider);
    if (secureRandom == null) {
      return null;
    }

    AsymmetricCipherKeyPairGenerator generator = getGenerator(algorithm);

    if (generator == null) {
      return null;
    }

    initGenerator(keySize, algorithm, generator, secureRandom);

    AsymmetricCipherKeyPair newPair = generator.generateKeyPair();

    AsymmetricCipherKeyPair oldPair = serverKeys.putIfAbsent(algorithm, newPair);
    if (oldPair != null) {
      return oldPair;
    }

    return newPair;
  }
Esempio n. 24
0
  /** Gets the default data source. */
  public DataSource findDatabase(String driver, String url) {
    if (_database != null) return _database;
    else {
      try {
        String key = driver + ";" + url;

        DataSource database = _databaseMap.get(key);

        if (database != null) return database;

        ClassLoader loader = Thread.currentThread().getContextClassLoader();

        Class cls = loader.loadClass(driver);

        Object ds = cls.newInstance();

        if (ds instanceof DataSource) database = (DataSource) ds;
        else database = new JavaSqlDriverWrapper((java.sql.Driver) ds, url);

        _databaseMap.put(key, database);

        return database;
      } catch (ClassNotFoundException e) {
        throw new QuercusModuleException(e);
      } catch (InstantiationException e) {
        throw new QuercusModuleException(e);
      } catch (IllegalAccessException e) {
        throw new QuercusModuleException(e);
      }
    }
  }
  @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;
  }
Esempio n. 26
0
  /** Adds a java class */
  public JavaClassDef getJavaClassDefinition(String className) {
    JavaClassDef def;

    if (_classNotFoundCache.get(className) != null) return null;

    def = _javaClassWrappers.get(className);

    if (def == null) {
      try {
        def = getModuleContext().getJavaClassDefinition(className);

        _javaClassWrappers.put(className, def);
      } catch (RuntimeException e) {
        _classNotFoundCache.put(className, className);

        throw e;
      } catch (Exception e) {
        throw new QuercusRuntimeException(e);
      }
    }

    def.init();

    return def;
  }
Esempio n. 27
0
  private PlayerController createNewStationPlayer(byte type, short id) {

    // voice players are handled as stations but not as such in database
    if (!Client.database.hasStation(type, id) && type != GlobalConstants.TYPE_VOICE) {
      return null;
    }

    App.logger.d("Creating new player. Type: " + type + " id: " + id, null);

    PlayerController controller = null;

    Station station = Client.database.getStation(type, id);
    ConcurrentHashMap<Short, PlayerController> map = getStationPlayerMap(type);
    if (map != null) {
      if (station == null && type == GlobalConstants.TYPE_VOICE) {
        controller = new VoicePlayer(type, id);

      } else if (station != null) {
        controller = new StationPlayer(type, id);
      }

      map.put(id, controller);
    }

    if (controller != null) {
      // start the player
      controller.start();
    } else {
      App.logger.d("Failed to create new player. Type: " + type + " id: " + id, null);
    }

    return controller;
  }
  @EventHandler(priority = Byte.MAX_VALUE)
  public void onJoin(PostLoginEvent e) {

    Player player = new Player(e.getPlayer());
    uuidMap.put(e.getPlayer().getUniqueId(), player);
    nameMap.put(e.getPlayer().getName(), player);
  }
Esempio n. 29
0
 public static void revertBlock(Block block) {
   for (int ID : instances.keySet()) {
     if (instances.get(ID).blockInAffectedBlocks(block)) {
       instances.get(ID).affectedblocks.remove(block);
     }
   }
 }
 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;
 }