@Override public CExternalSetting[] getExternalSettings() { IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(fProjName); if (project.isAccessible()) { ICProjectDescription des = CProjectDescriptionManager.getInstance().getProjectDescription(project, false); if (des != null) { ICConfigurationDescription cfg = fCfgId.length() != 0 ? des.getConfigurationById(fCfgId) : des.getActiveConfiguration(); if (cfg != null) { CExternalSetting[] es; ICExternalSetting[] ies = cfg.getExternalSettings(); if (ies instanceof CExternalSetting[]) es = (CExternalSetting[]) ies; else { es = new CExternalSetting[ies.length]; System.arraycopy(ies, 0, es, 0, es.length); } // Update the cache with the real settings this configuration is exporting cachedSettings.put(fId, es); return es; } } } // If project not yet accessible, just return the previous settings // for the moment. We'll update again when the referenced project reappears if (!cachedSettings.containsKey(fId) && prevSettings.length > 0) cachedSettings.putIfAbsent(fId, prevSettings); if (prevSettings.length == 0 && cachedSettings.containsKey(fId)) return cachedSettings.get(fId); return prevSettings; }
/* * Returns all nearby terrain that is walkable. * Used for calculating what nearby squares a unit can go to. */ public void getWalkableTerrain() { walkable = new ArrayList<Coordinate>(IMMEDIATE_WALKABLE); Unit selUnit = unitMap.get(selectedTile); int moveRnge = selUnit.getMoveRange(); int x = selectedTile.getX(); // transform coords to tile coords, which is flipped about the x axis (y invert) int y = terrain.length - selectedTile.getY() - 1; Coordinate unitCoord = new Coordinate(-1, -1); // look at all 8 adjacent squares for (int i = x - moveRnge; i <= x + moveRnge; i++) { int r = Math.abs(Math.abs(i - x) - moveRnge); for (int j = y - r; j <= y + r; j++) { // skip over self if (i == x && j == y) continue; // make sure we don't go out of bounds if (i >= 0 && i < terrain[0].length && j >= 0 && j < terrain.length) { unitCoord.setX(i); unitCoord.setY(terrain.length - j - 1); // 1 is passable, 0 impassable terrain for now // also check to see if a unit isn't there -- stacking not allowed if ((terrain[j][i] == 1 && !unitMap.containsKey(unitCoord)) || ((terrain[j][i] == 0 || terrain[j][i] == 2) && selUnit.isMntnClimber() && !unitMap.containsKey(unitCoord))) { // transform coordinate back walkable.add(new Coordinate(i, terrain.length - j - 1)); } } } } }
@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 FireJet(Player player) { if (instances.containsKey(player)) { // player.setAllowFlight(canfly); instances.remove(player); return; } if (timers.containsKey(player)) { if (System.currentTimeMillis() < timers.get(player) + (long) ((double) cooldown / Tools.getFirebendingDayAugment(player.getWorld()))) { return; } } factor = Tools.firebendingDayAugment(defaultfactor, player.getWorld()); Block block = player.getLocation().getBlock(); if (FireStream.isIgnitable(player, block) || block.getType() == Material.AIR || AvatarState.isAvatarState(player)) { player.setVelocity( player.getEyeLocation().getDirection().clone().normalize().multiply(factor)); block.setType(Material.FIRE); this.player = player; // canfly = player.getAllowFlight(); player.setAllowFlight(true); time = System.currentTimeMillis(); timers.put(player, time); instances.put(player, this); } }
/** 解析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(); } }
@Override public void notifyResult(AuctionItem item) { if (registeredUsers.containsKey(item.getCreator_id())) { RMIClientIntf creator = registeredUsers.get(item.getCreator_id()); try { creator.callBack("Your Auction has produced the following results :\n "); creator.callBack(item.getResult()); } catch (RemoteException e) { System.out.println("Creator no longer online\n"); } } else { System.out.println("Creator id does not exist\n"); } // Normally an auction with no creator registered should not exist but since this is a // simplified implementation // We allow bids on auctions with no creator (usually the initialised ones) for testing // purposes. if (item.numberOfBids() != 0) { System.out.println("Notifying bidders"); Iterator<Bid> it = item.getBidders(); while (it.hasNext()) { Bid bidder = it.next(); if (registeredUsers.containsKey(bidder.getUserId())) { RMIClientIntf client = registeredUsers.get(bidder.getUserId()); try { client.callBack(item.getResult()); } catch (RemoteException e) { System.out.println("Bidder with id " + bidder.getUserId() + " no longer online\n"); } } else { System.out.println("User id does not exist\n"); } } } }
/** Process WAMP messages coming from the background reader. */ protected void processAppMessage(Object message) { if (message instanceof WampMessage.CallResult) { WampMessage.CallResult callresult = (WampMessage.CallResult) message; if (mCalls.containsKey(callresult.mCallId)) { CallMeta meta = mCalls.get(callresult.mCallId); if (meta.mResultHandler != null) { meta.mResultHandler.onResult(callresult.mResult); } mCalls.remove(callresult.mCallId); } } else if (message instanceof WampMessage.CallError) { WampMessage.CallError callerror = (WampMessage.CallError) message; if (mCalls.containsKey(callerror.mCallId)) { CallMeta meta = mCalls.get(callerror.mCallId); if (meta.mResultHandler != null) { meta.mResultHandler.onError(callerror.mErrorUri, callerror.mErrorDesc); } mCalls.remove(callerror.mCallId); } } else if (message instanceof WampMessage.Event) { WampMessage.Event event = (WampMessage.Event) message; if (mSubs.containsKey(event.mTopicUri)) { SubMeta meta = mSubs.get(event.mTopicUri); if (meta != null && meta.mEventHandler != null) { meta.mEventHandler.onEvent(event.mTopicUri, event.mEvent); } } } else if (message instanceof WampMessage.Welcome) { WampMessage.Welcome welcome = (WampMessage.Welcome) message; // FIXME: safe session ID / fire session opened hook if (DEBUG) Log.d( TAG, "WAMP session " + welcome.mSessionId + " established (protocol version " + welcome.mProtocolVersion + ", server " + welcome.mServerIdent + ")"); } else { if (DEBUG) Log.d(TAG, "unknown WAMP message in AutobahnConnection.processAppMessage"); } }
private void checkTopic2( final ConcurrentHashMap<String, ConcurrentHashMap<Partition, TopicPartitionRegInfo>> topicRegistry) { final ConcurrentHashMap<Partition, TopicPartitionRegInfo> partMap2 = topicRegistry.get("topic2"); assertNotNull(partMap2); assertEquals(1, partMap2.size()); assertTrue(partMap2.containsKey(new Partition("0-0"))); assertFalse(partMap2.containsKey(new Partition("1-0"))); }
private static void finalRemoveLava(Block block) { if (AFFECTED_BLOCKS.containsKey(block)) { TempBlock.revertBlock(block, Material.AIR); AFFECTED_BLOCKS.remove(block); } if (WALL_BLOCKS.containsKey(block)) { TempBlock.revertBlock(block, Material.AIR); WALL_BLOCKS.remove(block); } }
private void checkTopic1( final ConcurrentHashMap<String, ConcurrentHashMap<Partition, TopicPartitionRegInfo>> topicRegistry) { final ConcurrentHashMap<Partition, TopicPartitionRegInfo> partMap1 = topicRegistry.get("topic1"); assertNotNull(partMap1); assertEquals(3, partMap1.size()); assertTrue(partMap1.containsKey(new Partition("0-0"))); assertTrue(partMap1.containsKey(new Partition("0-1"))); assertTrue(partMap1.containsKey(new Partition("0-2"))); }
@Override public void process(Request request) { String name = getRouteName(request); if (name == null || name.isEmpty()) return; if (!ROUTE_TIMERS.containsKey(name)) { ROUTE_TIMERS.putIfAbsent(name, metrics.timer(getTimerName(name))); } if (!EXCEPTION_COUNTERS_BY_ROUTE.containsKey(name)) { EXCEPTION_COUNTERS_BY_ROUTE.putIfAbsent(name, metrics.counter(getExceptionCounterName(name))); } }
@SuppressWarnings("deprecation") public static void remove(Block block) { if (ignitedblocks.containsKey(block)) { ignitedblocks.remove(block); } if (ignitedtimes.containsKey(block)) { ignitedtimes.remove(block); } if (replacedBlocks.containsKey(block.getLocation())) { block.setType(replacedBlocks.get(block.getLocation()).getItemType()); block.setData(replacedBlocks.get(block.getLocation()).getData()); replacedBlocks.remove(block.getLocation()); } }
public boolean hasAccount(String name) { if (hc.useExternalEconomy()) { if (hc.getEconomy().hasAccount(name)) { if (!hyperPlayers.containsKey(fixpN(name))) { addPlayer(name); } return true; } else { return false; } } else { return hyperPlayers.containsKey(fixpN(name)); } }
public FileConfiguration gFC(String fileConfiguration) { if (configs.containsKey(fileConfiguration)) { return configs.get(fileConfiguration); } else { return null; } }
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; }
// TODO @GET @Path("/jobQueue/{jobID}") // @Produces(MediaType.TEXT_XML) public Response checkJobQueue(@PathParam("jobID") String jobID) { // does job exist? System.out.println("[checkJobQueue] queue length = " + jobqueue.size()); System.out.println("[checkJobQueue] jobID = " + jobID); if (jobqueue.containsKey(UUID.fromString(jobID))) { System.out.println("Found job ID"); // if job is not finished yet return 200 if (jobqueue.get(UUID.fromString(jobID)).getStatus() == SFPGenJob.PROCESSING) return Response.status(Status.OK) .entity("Still processing - please check back later.") .build(); // if job is finished and SFP has been created else { // return path to SFP resource URI sfp_uri; try { sfp_uri = new URI("SFP/sfplist/" + jobID); // update jobQueue SFPGenJob currjob = jobqueue.get(UUID.fromString(jobID)); currjob.updateStatus(SFPGenJob.GONE); jobqueue.put(UUID.fromString(jobID), currjob); return Response.status(Status.SEE_OTHER).location(sfp_uri).build(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } return Response.serverError().build(); } } else return Response.serverError().entity("No such job ID").build(); }
/** * Get the selected GameCharacter object * * @param entityID Of the object * @return GameCharacter object or null if it doesn't exists */ public GameCharacter getEntity(int entityID) { if (mapCharacterEntities.containsKey(entityID)) { return mapCharacterEntities.get(entityID); } else { return null; } }
public String getServiceOfferedFromRegMap(String serviceName) { if (serviceRegistrationMap.containsKey(serviceName)) { return serviceRegistrationMap.get(serviceName).getServiceOffered(); } else { return null; } }
public synchronized boolean doesClientNameExits(String clientName) { if (clientList.containsKey(clientName)) { return true; } else { return false; } }
@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; }
@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; }
public int readCurrentServiceIndexAndIncrement(String serviceOffered) throws Exception { if (currentServiceIndexMap.containsKey(serviceOffered)) { return currentServiceIndexMap.get(serviceOffered).incrementAndGet(); } else { throw new Exception("No Service for " + serviceOffered + " Available"); } }
public void endGame(UUID tableId) { if (controllers.containsKey(tableId)) { if (controllers.get(tableId).endGameAndStartNextGame()) { removeTable(tableId); } } }
public boolean submitDeck(UUID userId, UUID tableId, DeckCardLists deckList) throws MageException { if (controllers.containsKey(tableId)) { return controllers.get(tableId).submitDeck(userId, deckList); } return false; }
private void readAllChunks(boolean readPagePositions) { String[] files = new File(btreeStorageName).list(); if (files != null && files.length > 0) { for (String f : files) { int chunkId = Integer.parseInt(f.substring(0, f.length() - AOStorage.SUFFIX_AO_FILE_LENGTH)); if (!chunks.containsKey(chunkId)) { readChunkHeader(chunkId); } } if (readPagePositions) { for (BTreeChunk c : chunks.values()) { if (c.pagePositions == null) { ByteBuffer pagePositions = c.fileStorage.readFully( c.pagePositionsOffset + CHUNK_HEADER_SIZE, c.pageCount * 2 * 8); int size = c.pageCount * 2; c.pagePositions = new ArrayList<Long>(); for (int i = 0; i < size; i++) { c.pagePositions.add(pagePositions.getLong()); } } } } } }
public void addChair(Player player, Block block) { if (disabled) return; try { PacketContainer entitymeta = ProtocolLibrary.getProtocolManager().createPacket(40); entitymeta.getSpecificModifier(int.class).write(0, player.getEntityId()); WrappedDataWatcher watcher = new WrappedDataWatcher(); watcher.setObject(0, (byte) 4); entitymeta.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects()); for (Player play : plugin.getServer().getOnlinePlayers()) { if (play.getWorld().equals(player.getPlayer().getWorld())) { try { ProtocolLibrary.getProtocolManager().sendServerPacket(play, entitymeta); } catch (InvocationTargetException e) { BukkitUtil.printStacktrace(e); } } } } catch (Error e) { Bukkit.getLogger().severe("Chairs do not work without ProtocolLib!"); disabled = true; return; } if (chairs.containsKey(player.getName())) return; plugin.wrapPlayer(player).print(ChatColor.YELLOW + "You are now sitting."); chairs.put(player.getName(), block); }
/** * 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()); } }
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()); }
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; }
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)); }