Java Code Examples for java.util.concurrent.ConcurrentHashMap.isEmpty()

The following are Jave code examples for showing how to use isEmpty() of the java.util.concurrent.ConcurrentHashMap class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: GitHub   File: ProcessLock.java   View Source Code Vote up 7 votes
private static void release(String lockName, FileLock fileLock, File file, Closeable stream) {
    synchronized (LOCK_MAP) {
        if (fileLock != null) {
            try {
                LOCK_MAP.remove(lockName, fileLock.hashCode());
                ConcurrentHashMap<Integer, ProcessLock> locks = LOCK_MAP.get(lockName);
                if (locks == null || locks.isEmpty()) {
                    IOUtil.deleteFileOrDir(file);
                }

                if (fileLock.channel().isOpen()) {
                    fileLock.release();
                }
            } catch (Throwable ex) {
                LogUtil.e(ex.getMessage(), ex);
            } finally {
                IOUtil.closeQuietly(fileLock.channel());
            }
        }

        IOUtil.closeQuietly(stream);
    }
}
 
Example 2
Project: reading-and-annotate-rocketmq-3.4.6   File: ConsumerOffsetManager.java   View Source Code Vote up 7 votes
private boolean offsetBehindMuchThanData(final String topic, ConcurrentHashMap<Integer, Long> table) {
    Iterator<Entry<Integer, Long>> it = table.entrySet().iterator();
    boolean result = !table.isEmpty();

    while (it.hasNext() && result) {
        Entry<Integer, Long> next = it.next();
        long minOffsetInStore = this.brokerController.getMessageStore().getMinOffsetInQuque(topic, next.getKey());
        long offsetInPersist = next.getValue();
        if (offsetInPersist > minOffsetInStore) {
            result = false;
        }
        else {
            result = true;
        }
    }

    return result;
}
 
Example 3
Project: ditb   File: IntegrationTestDDLMasterFailover.java   View Source Code Vote up 7 votes
protected HTableDescriptor selectTable(ConcurrentHashMap<TableName, HTableDescriptor> tableMap)
{
  // randomly select table from tableMap
  if (tableMap.isEmpty()){
    return null;
  }
  // synchronization to prevent removal from multiple threads
  synchronized (tableMap){
    ArrayList<TableName> tableList = new ArrayList<TableName>(tableMap.keySet());
    TableName randomKey = tableList.get(RandomUtils.nextInt(tableList.size()));
    HTableDescriptor randomHtd = tableMap.get(randomKey);
    // remove from tableMap
    tableMap.remove(randomKey);
    return randomHtd;
  }
}
 
Example 4
Project: GitHub   File: DoubleKeyValueMap.java   View Source Code Vote up 6 votes
public void remove(K1 key1, K2 key2) {
    ConcurrentHashMap<K2, V> k2_v = k1_k2V_map.get(key1);
    if (k2_v != null) {
        k2_v.remove(key2);
    }
    if (k2_v == null || k2_v.isEmpty()) {
        k1_k2V_map.remove(key1);
    }
}
 
Example 5
Project: reading-and-annotate-rocketmq-3.4.6   File: ConsumerManager.java   View Source Code Vote up 6 votes
public void scanNotActiveChannel() {
    Iterator<Entry<String, ConsumerGroupInfo>> it = this.consumerTable.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, ConsumerGroupInfo> next = it.next();
        String group = next.getKey();
        ConsumerGroupInfo consumerGroupInfo = next.getValue();
        ConcurrentHashMap<Channel, ClientChannelInfo> channelInfoTable =
                consumerGroupInfo.getChannelInfoTable();

        Iterator<Entry<Channel, ClientChannelInfo>> itChannel = channelInfoTable.entrySet().iterator();
        while (itChannel.hasNext()) {
            Entry<Channel, ClientChannelInfo> nextChannel = itChannel.next();
            ClientChannelInfo clientChannelInfo = nextChannel.getValue();
            long diff = System.currentTimeMillis() - clientChannelInfo.getLastUpdateTimestamp();
            if (diff > ChannelExpiredTimeout) {
                log.warn(
                    "SCAN: remove expired channel from ConsumerManager consumerTable. channel={}, consumerGroup={}",
                    RemotingHelper.parseChannelRemoteAddr(clientChannelInfo.getChannel()), group);
                RemotingUtil.closeChannel(clientChannelInfo.getChannel());
                itChannel.remove();
            }
        }

        if (channelInfoTable.isEmpty()) {
            log.warn(
                "SCAN: remove expired channel from ConsumerManager consumerTable, all clear, consumerGroup={}",
                group);
            it.remove();
        }
    }
}
 
Example 6
Project: headb   File: HeaCore.java   View Source Code Vote up 6 votes
/**
 * 分析aliasMap
 * 
 * @param aliasMap
 * @param xmlUtils
 * @param joinSqlMap
 */
protected void analyzeAliasMap(ConcurrentHashMap<String, Boolean> aliasMap, HHashMap<Integer, String> joinSqlMap) {
	if (aliasMap.isEmpty()) {
		return;
	}
	for (Entry<String, Boolean> entry : aliasMap.entrySet()) {
		String alias = entry.getKey();
		Boolean flag = entry.getValue();
		if (!flag) {
			Join join = getXml().getJoin(alias);
			Integer level = join.getLevel();
			StringBuffer joinSqlBuffer = new StringBuffer();
			if (joinSqlMap.get(level) != null) {
				joinSqlBuffer.append(joinSqlMap.get(level));
			}
			joinSqlBuffer.append(HeaConstant.SPACE).append(join.getJoinSql()).append(HeaConstant.SPACE);
			joinSqlMap.set(level, joinSqlBuffer.toString());
			aliasMap.put(alias, true);
			if (join.getLevel() > 1) {
				String dependAlias = getXml().getDependAliasByField(join.getDependField());
				if (null == aliasMap.get(dependAlias)) {
					aliasMap.put(dependAlias, false);
					analyzeAliasMap(aliasMap, joinSqlMap);
				}
			}
		}

	}
}
 
Example 7
Project: uroborosql   File: SqlLoaderImpl.java   View Source Code Vote up 6 votes
/**
 * {@inheritDoc}
 *
 * @see jp.co.future.uroborosql.store.SqlLoader#load()
 */
@Override
public ConcurrentHashMap<String, String> load() {
	ConcurrentHashMap<String, String> loadedSqlMap = new ConcurrentHashMap<>();
	try {
		Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(loadPath);
		while (resources.hasMoreElements()) {
			URL resource = resources.nextElement();
			File rootDir = new File(URLDecoder.decode(resource.getFile(), StandardCharsets.UTF_8.toString()));

			if (!rootDir.exists() || !rootDir.isDirectory()) {
				if ("jar".equalsIgnoreCase(resource.getProtocol())) {
					putAllIfAbsent(loadedSqlMap, load((JarURLConnection) resource.openConnection(), loadPath));
					continue;
				}

				LOG.warn("Ignore because not directory.[{}]", rootDir.getAbsolutePath());
				continue;
			}

			LOG.debug("Start loading SQL template.[{}]", rootDir.getAbsolutePath());
			putAllIfAbsent(loadedSqlMap, load(new StringBuilder(), rootDir));
		}
	} catch (IOException e) {
		throw new UroborosqlRuntimeException("Failed to load SQL template.", e);
	}

	if (loadedSqlMap.isEmpty()) {
		LOG.warn("SQL template could not be found.");
		LOG.warn("Returns an empty SQL cache.");
	}

	return loadedSqlMap;
}
 
Example 8
Project: Reinickendorf_SER316   File: TestAgendaPanel.java   View Source Code Vote up 6 votes
@Test
public void testSliceJSONStrIntoConcHashMap() {

	String jsonStr = "{\"id\":\"/Users/user/src/path\"}";
	ConcurrentHashMap<String,String> chm = new ConcurrentHashMap();
	chm = AgendaPanel.sliceJSONStrIntoConcHashMap(jsonStr);
	System.out.println("Path: "+chm.get("id"));
	System.out.println(jsonStr);
	if(chm.isEmpty() || chm == null){
		fail("sliceJSONStrIntoConcHashMap returned empty map when given correct JSON");
	}else if(!(chm.get("id").equals("/Users/user/src/path"))){
		fail("sliceJSONStrIntoConcHashMap did not return proper formatting of path and/or ID");
	}
}
 
Example 9
Project: rmq4note   File: ConsumerOffsetManager.java   View Source Code Vote up 6 votes
private boolean offsetBehindMuchThanData(final String topic, ConcurrentHashMap<Integer, Long> table) {
    Iterator<Entry<Integer, Long>> it = table.entrySet().iterator();
    boolean result = !table.isEmpty();

    while (it.hasNext() && result) {
        Entry<Integer, Long> next = it.next();
        long minOffsetInStore = this.brokerController.getMessageStore().getMinOffsetInQuque(topic, next.getKey());
        long offsetInPersist = next.getValue();
        result = offsetInPersist <= minOffsetInStore;
    }

    return result;
}
 
Example 10
Project: rmq4note   File: ConsumerManager.java   View Source Code Vote up 6 votes
public void scanNotActiveChannel() {
    Iterator<Entry<String, ConsumerGroupInfo>> it = this.consumerTable.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, ConsumerGroupInfo> next = it.next();
        String group = next.getKey();
        ConsumerGroupInfo consumerGroupInfo = next.getValue();
        ConcurrentHashMap<Channel, ClientChannelInfo> channelInfoTable =
            consumerGroupInfo.getChannelInfoTable();

        Iterator<Entry<Channel, ClientChannelInfo>> itChannel = channelInfoTable.entrySet().iterator();
        while (itChannel.hasNext()) {
            Entry<Channel, ClientChannelInfo> nextChannel = itChannel.next();
            ClientChannelInfo clientChannelInfo = nextChannel.getValue();
            long diff = System.currentTimeMillis() - clientChannelInfo.getLastUpdateTimestamp();
            if (diff > CHANNEL_EXPIRED_TIMEOUT) {
                log.warn(
                    "SCAN: remove expired channel from ConsumerManager consumerTable. channel={}, consumerGroup={}",
                    RemotingHelper.parseChannelRemoteAddr(clientChannelInfo.getChannel()), group);
                RemotingUtil.closeChannel(clientChannelInfo.getChannel());
                itChannel.remove();
            }
        }

        if (channelInfoTable.isEmpty()) {
            log.warn(
                "SCAN: remove expired channel from ConsumerManager consumerTable, all clear, consumerGroup={}",
                group);
            it.remove();
        }
    }
}
 
Example 11
Project: GitHub   File: ProcessLock.java   View Source Code Vote up 5 votes
private static ProcessLock tryLockInternal(final String lockName, final String hash, final boolean writeMode) {
    synchronized (LOCK_MAP) {

        ConcurrentHashMap<Integer, ProcessLock> locks = LOCK_MAP.get(lockName);
        if (locks != null && !locks.isEmpty()) {
            Iterator<Map.Entry<Integer, ProcessLock>> itr = locks.entrySet().iterator();
            while (itr.hasNext()) {
                Map.Entry<Integer, ProcessLock> entry = itr.next();
                ProcessLock value = entry.getValue();
                if (value != null) {
                    if (!value.isValid()) {
                        itr.remove();
                    } else if (writeMode) {
                        return null;
                    } else if (value.mWriteMode) {
                        return null;
                    }
                } else {
                    itr.remove();
                }
            }
        }

        FileChannel channel = null;
        Closeable stream = null;
        try {
            File file = new File(
                    x.app().getDir(LOCK_FILE_DIR, Context.MODE_PRIVATE),
                    hash);
            if (file.exists() || file.createNewFile()) {

                if (writeMode) {
                    FileOutputStream out = new FileOutputStream(file, false);
                    channel = out.getChannel();
                    stream = out;
                } else {
                    FileInputStream in = new FileInputStream(file);
                    channel = in.getChannel();
                    stream = in;
                }
                if (channel != null) {
                    FileLock fileLock = channel.tryLock(0L, Long.MAX_VALUE, !writeMode);
                    if (isValid(fileLock)) {
                        ProcessLock result = new ProcessLock(lockName, file, fileLock, stream, writeMode);
                        LOCK_MAP.put(lockName, fileLock.hashCode(), result);
                        return result;
                    } else {
                        release(lockName, fileLock, file, stream);
                    }
                } else {
                    throw new IOException("can not get file channel:" + file.getAbsolutePath());
                }
            }
        } catch (Throwable ignored) {
            LogUtil.d("tryLock: " + lockName + ", " + ignored.getMessage());
            IOUtil.closeQuietly(stream);
            IOUtil.closeQuietly(channel);
        }
    }

    return null;
}
 
Example 12
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: MQClientInstance.java   View Source Code Vote up 5 votes
/**
 * Remove offline broker
 */
private void cleanOfflineBroker() {
    try {
        if (this.lockNamesrv.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS))
            try {
                ConcurrentHashMap<String, HashMap<Long, String>> updatedTable = new ConcurrentHashMap<String, HashMap<Long, String>>();

                Iterator<Entry<String, HashMap<Long, String>>> itBrokerTable = this.brokerAddrTable.entrySet().iterator();
                while (itBrokerTable.hasNext()) {
                    Entry<String, HashMap<Long, String>> entry = itBrokerTable.next();
                    String brokerName = entry.getKey();
                    HashMap<Long, String> oneTable = entry.getValue();

                    HashMap<Long, String> cloneAddrTable = new HashMap<Long, String>();
                    cloneAddrTable.putAll(oneTable);

                    Iterator<Entry<Long, String>> it = cloneAddrTable.entrySet().iterator();
                    while (it.hasNext()) {
                        Entry<Long, String> ee = it.next();
                        String addr = ee.getValue();
                        if (!this.isBrokerAddrExistInTopicRouteTable(addr)) {
                            it.remove();
                            log.info("the broker addr[{} {}] is offline, remove it", brokerName, addr);
                        }
                    }

                    if (cloneAddrTable.isEmpty()) {
                        itBrokerTable.remove();
                        log.info("the broker[{}] name's host is offline, remove it", brokerName);
                    } else {
                        updatedTable.put(brokerName, cloneAddrTable);
                    }
                }

                if (!updatedTable.isEmpty()) {
                    this.brokerAddrTable.putAll(updatedTable);
                }
            } finally {
                this.lockNamesrv.unlock();
            }
    } catch (InterruptedException e) {
        log.warn("cleanOfflineBroker Exception", e);
    }
}
 
Example 13
Project: reading-and-annotate-rocketmq-3.4.6   File: DefaultMessageStore.java   View Source Code Vote up 5 votes
public void cleanExpiredConsumerQueue() {
    long minCommitLogOffset = this.commitLog.getMinOffset();

    Iterator<Entry<String, ConcurrentHashMap<Integer, ConsumeQueue>>> it = this.consumeQueueTable.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, ConcurrentHashMap<Integer, ConsumeQueue>> next = it.next();
        String topic = next.getKey();
        if (!topic.equals(ScheduleMessageService.SCHEDULE_TOPIC)) {
            ConcurrentHashMap<Integer, ConsumeQueue> queueTable = next.getValue();
            Iterator<Entry<Integer, ConsumeQueue>> itQT = queueTable.entrySet().iterator();
            while (itQT.hasNext()) {
                Entry<Integer, ConsumeQueue> nextQT = itQT.next();
                long maxCLOffsetInConsumeQueue = nextQT.getValue().getLastOffset();

                if (maxCLOffsetInConsumeQueue == -1) {
                    log.warn("maybe ConsumeQueue was created just now. topic={} queueId={} maxPhysicOffset={} minLogicOffset={}.",//
                        nextQT.getValue().getTopic(),//
                        nextQT.getValue().getQueueId(),//
                        nextQT.getValue().getMaxPhysicOffset(),//
                        nextQT.getValue().getMinLogicOffset());
                }
                else if (maxCLOffsetInConsumeQueue < minCommitLogOffset) {
                    log.info(
                        "cleanExpiredConsumerQueue: {} {} consumer queue destroyed, minCommitLogOffset: {} maxCLOffsetInConsumeQueue: {}",//
                        topic,//
                        nextQT.getKey(),//
                        minCommitLogOffset,//
                        maxCLOffsetInConsumeQueue);

                    DefaultMessageStore.this.commitLog.removeQueurFromTopicQueueTable(nextQT.getValue().getTopic(), nextQT.getValue()
                        .getQueueId());

                    nextQT.getValue().destroy();
                    itQT.remove();
                }
            }

            if (queueTable.isEmpty()) {
                log.info("cleanExpiredConsumerQueue: {},topic destroyed", topic);
                it.remove();
            }
        }
    }
}
 
Example 14
Project: headb   File: HeaSoul.java   View Source Code Vote up 5 votes
/**
 *生成删除sql
 * @param parameter
 * @return SqlParmeter
 */ 
protected SqlParmeter generateDeleteSql(HeaMap parameter) {
	initEntityInfo(this.entityType);
	String entityName = getEntityName();
	Entity entityInfo = entityMap.get(entityName);
	String tableName = entityInfo.getTableName();
	SqlParmeter sqlParmeter = new SqlParmeter();
	if (null == parameter) {
		parameter = new HeaMap();
	}
	if (parameter.size() == 0) {
		throw new RuntimeException("必须传人参数!");
	}
	List<Object> params = new ArrayList<Object>();
	ConcurrentHashMap<String, Boolean> aliasMap = new ConcurrentHashMap<String, Boolean>();
	StringBuffer whereSql = new StringBuffer();// 包含where后面的sql语局
	String link = "where";// 第一个默认连接是where
	boolean firstQueryFlag = true;// 是否是第一个需查项
	List<String> groupSqlList = new ArrayList<String>();
	for (Entry<String, ?> entry : parameter.entrySet()) {
		String key = entry.getKey();
		Object value = entry.getValue();
		key = filterKey(key);
		if (key.startsWith(HeaConstant.Instruction.ADDGROUP)) {
			groupSqlList = getOrder(groupSqlList, value);
			continue;
		}
		ColumnCondition columnCondition = new ColumnCondition();
		columnCondition = analyzeKey(columnCondition, key, value);
		if (!columnCondition.getIfQuery()) {
			continue;
		}
		if (!firstQueryFlag) {
			link = columnCondition.getAndOr();
		}
		whereSql.append(HStringUtils.format(" {0} {1}", link, columnCondition.getSqlFragment()));
		if (null != columnCondition.getCookedValue()) {
			params.addAll(columnCondition.getCookedValue());
		}
		firstQueryFlag = false;
	}
	String whereSqlStr = whereSql.toString();
	String groupSql = "";
	if (groupSqlList.size() > 0) {
		groupSql = " group by " + HStringUtils.StrList(groupSqlList, ",");
	}
	String tempStr = HStringUtils.addStr(whereSqlStr, groupSql);
	aliasMap.putAll(HOrmUtil.getAliasFromSql(tempStr));
	// 分析得到joinSql
	String joinSql = "";
	if (!aliasMap.isEmpty()) {
		HHashMap<Integer, String> joinSqlMap = new HHashMap<Integer, String>();
		analyzeAliasMap(aliasMap, joinSqlMap);
		joinSql = getJoinSql(joinSqlMap);
	}
	String tableSqlStr = HStringUtils.format("{0} t {1}", tableName, joinSql);
	Map<String, Object> viewParams = parameter.getViewParams();
	TableSql tableSql = getTableSql(tableSqlStr, viewParams);
	tableSqlStr = tableSql.getTargetTableSql();
	List<Object> tableParams = tableSql.getParams();
	// 0:tableName 1:where
	String sql = HStringUtils.format("delete t from {0}  {1}", tableSqlStr, whereSqlStr);
	sqlParmeter.setSql(sql);
	tableParams.addAll(params);
	sqlParmeter.setParameters(tableParams.toArray());
	return sqlParmeter;
}
 
Example 15
Project: headb   File: HeaSoul.java   View Source Code Vote up 5 votes
/**
 * 生成更新Sql
 * @param entity
 * @param parameter
 * @return
 */
protected SqlParmeter generateUpdateSql(T entity, HeaMap parameter) {
	initEntityInfo(this.entityType);
	String entityName = getEntityName();
	Entity entityInfo = entityMap.get(entityName);
	String tableName = entityInfo.getTableName();
	SqlParmeter sqlParmeter = new SqlParmeter();
	if (null == parameter) {
		parameter = new HeaMap();
	}
	if (parameter.size() == 0) {
		throw new RuntimeException("必须传人参数!");
	}
	List<Object> params = new ArrayList<Object>();
	ConcurrentHashMap<String, Boolean> aliasMap = new ConcurrentHashMap<String, Boolean>();
	StringBuffer whereSql = new StringBuffer();// 包含where后面的sql语局
	String link = "where";// 第一个默认连接是where
	boolean firstQueryFlag = true;// 是否是第一个需查项
	List<String> groupSqlList = new ArrayList<String>();
	for (Entry<String, ?> entry : parameter.entrySet()) {
		String key = entry.getKey();
		Object value = entry.getValue();
		key = filterKey(key);
		if (key.startsWith(HeaConstant.Instruction.ADDGROUP)) {
			groupSqlList = getOrder(groupSqlList, value);
			continue;
		}
		ColumnCondition columnCondition = new ColumnCondition();
		columnCondition = analyzeKey(columnCondition, key, value);
		if (!columnCondition.getIfQuery()) {
			continue;
		}
		if (!firstQueryFlag) {
			link = columnCondition.getAndOr();
		}
		whereSql.append(HStringUtils.format(" {0} {1}", link, columnCondition.getSqlFragment()));
		if (null != columnCondition.getCookedValue()) {
			params.addAll(columnCondition.getCookedValue());
		}
		firstQueryFlag = false;
	}
	String whereSqlStr = whereSql.toString();
	String groupSql = "";
	if (groupSqlList.size() > 0) {
		groupSql = " group by " + HStringUtils.StrList(groupSqlList, ",");
	}
	String tempStr = HStringUtils.addStr(whereSqlStr, groupSql);
	aliasMap.putAll(HOrmUtil.getAliasFromSql(tempStr));
	// 分析得到joinSql
	String joinSql = "";
	if (!aliasMap.isEmpty()) {
		HHashMap<Integer, String> joinSqlMap = new HHashMap<Integer, String>();
		analyzeAliasMap(aliasMap, joinSqlMap);
		joinSql = getJoinSql(joinSqlMap);
	}
	String tableSqlStr = HStringUtils.format("{0} t {1}", tableName, joinSql);
	Map<String, Object> viewParams = parameter.getViewParams();
	TableSql tableSql = getTableSql(tableSqlStr, viewParams);
	tableSqlStr = tableSql.getTargetTableSql();
	List<Object> tableParams = tableSql.getParams();
	// 获得setSql
	SqlFragment setSqlEntity = getUpdateSetSql(entity, entityInfo, parameter.getUpdateNullMap());
	// 0:tableSql 1:setSql 2:where
	String sql = HStringUtils.format("update {0} set {1} {2}", tableSqlStr, setSqlEntity.getSql(), whereSqlStr);
	// String sql = StringUtils.format("delete t from {0}  {1}",
	// tableSqlStr, whereSqlStr);
	sqlParmeter.setSql(sql);
	tableParams.addAll(setSqlEntity.getParams());// set
	tableParams.addAll(params);
	sqlParmeter.setParameters(tableParams.toArray());
	return sqlParmeter;
}
 
Example 16
Project: fresco_floodlight   File: PacketTraceResource.java   View Source Code Vote up 5 votes
@Post("json")
public PacketTraceOutput packettrace(FilterParameters fp) {
    
    ConcurrentHashMap <String,String> filter = new ConcurrentHashMap<String,String> ();
    String sid = null;
    PacketTraceOutput output = new PacketTraceOutput();
    IOFMessageFilterManagerService manager = 
            (IOFMessageFilterManagerService)getContext()
                .getAttributes().
                    get(IOFMessageFilterManagerService.class.getCanonicalName());

    if (manager == null) {
        sid = null;
        setStatus(Status.SERVER_ERROR_SERVICE_UNAVAILABLE);
    }
    
    if (fp.getSessionId() != null) {
        filter.put("sessionId", fp.getSessionId());
    }
    if (fp.getMac() != null) {
        filter.put("mac", fp.getMac());
    }
    if (fp.getDirection() != null) {
        filter.put("direction", fp.getDirection());
    }
    
    if (filter.isEmpty()) {
        setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    } else {
        if (log.isDebugEnabled()) {
            log.debug ("Call setupFilter: sid:{} filter:{}, period:{}", 
                       new Object[] {fp.getSessionId(), filter, 
                                     fp.getPeriod()*1000});
        }
        sid = manager.setupFilter(fp.getSessionId(), filter, 
                                  fp.getPeriod()*1000);
        output.setSessionId(sid);
        setStatus(Status.SUCCESS_OK);
    }
    
    return output;
}
 
Example 17
Project: rmq4note   File: MQClientInstance.java   View Source Code Vote up 5 votes
/**
 * Remove offline broker
 */
private void cleanOfflineBroker() {
    try {
        if (this.lockNamesrv.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS))
            try {
                ConcurrentHashMap<String, HashMap<Long, String>> updatedTable = new ConcurrentHashMap<String, HashMap<Long, String>>();

                Iterator<Entry<String, HashMap<Long, String>>> itBrokerTable = this.brokerAddrTable.entrySet().iterator();
                while (itBrokerTable.hasNext()) {
                    Entry<String, HashMap<Long, String>> entry = itBrokerTable.next();
                    String brokerName = entry.getKey();
                    HashMap<Long, String> oneTable = entry.getValue();

                    HashMap<Long, String> cloneAddrTable = new HashMap<Long, String>();
                    cloneAddrTable.putAll(oneTable);

                    Iterator<Entry<Long, String>> it = cloneAddrTable.entrySet().iterator();
                    while (it.hasNext()) {
                        Entry<Long, String> ee = it.next();
                        String addr = ee.getValue();
                        if (!this.isBrokerAddrExistInTopicRouteTable(addr)) {
                            it.remove();
                            log.info("the broker addr[{} {}] is offline, remove it", brokerName, addr);
                        }
                    }

                    if (cloneAddrTable.isEmpty()) {
                        itBrokerTable.remove();
                        log.info("the broker[{}] name's host is offline, remove it", brokerName);
                    } else {
                        updatedTable.put(brokerName, cloneAddrTable);
                    }
                }

                if (!updatedTable.isEmpty()) {
                    this.brokerAddrTable.putAll(updatedTable);
                }
            } finally {
                this.lockNamesrv.unlock();
            }
    } catch (InterruptedException e) {
        log.warn("cleanOfflineBroker Exception", e);
    }
}
 
Example 18
Project: rmq4note   File: DefaultMessageStore.java   View Source Code Vote up 5 votes
public void cleanExpiredConsumerQueue() {
    long minCommitLogOffset = this.commitLog.getMinOffset();

    Iterator<Entry<String, ConcurrentHashMap<Integer, ConsumeQueue>>> it = this.consumeQueueTable.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, ConcurrentHashMap<Integer, ConsumeQueue>> next = it.next();
        String topic = next.getKey();
        if (!topic.equals(ScheduleMessageService.SCHEDULE_TOPIC)) {
            ConcurrentHashMap<Integer, ConsumeQueue> queueTable = next.getValue();
            Iterator<Entry<Integer, ConsumeQueue>> itQT = queueTable.entrySet().iterator();
            while (itQT.hasNext()) {
                Entry<Integer, ConsumeQueue> nextQT = itQT.next();
                long maxCLOffsetInConsumeQueue = nextQT.getValue().getLastOffset();

                if (maxCLOffsetInConsumeQueue == -1) {
                    log.warn("maybe ConsumeQueue was created just now. topic={} queueId={} maxPhysicOffset={} minLogicOffset={}.", //
                        nextQT.getValue().getTopic(), //
                        nextQT.getValue().getQueueId(), //
                        nextQT.getValue().getMaxPhysicOffset(), //
                        nextQT.getValue().getMinLogicOffset());
                } else if (maxCLOffsetInConsumeQueue < minCommitLogOffset) {
                    log.info(
                        "cleanExpiredConsumerQueue: {} {} consumer queue destroyed, minCommitLogOffset: {} maxCLOffsetInConsumeQueue: {}", //
                        topic, //
                        nextQT.getKey(), //
                        minCommitLogOffset, //
                        maxCLOffsetInConsumeQueue);

                    DefaultMessageStore.this.commitLog.removeQueueFromTopicQueueTable(nextQT.getValue().getTopic(),
                        nextQT.getValue().getQueueId());

                    nextQT.getValue().destroy();
                    itQT.remove();
                }
            }

            if (queueTable.isEmpty()) {
                log.info("cleanExpiredConsumerQueue: {},topic destroyed", topic);
                it.remove();
            }
        }
    }
}
 
Example 19
Project: iTAP-controller   File: PacketTraceResource.java   View Source Code Vote up 5 votes
@Post("json")
public PacketTraceOutput packettrace(FilterParameters fp) {
    
    ConcurrentHashMap <String,String> filter = new ConcurrentHashMap<String,String> ();
    String sid = null;
    PacketTraceOutput output = new PacketTraceOutput();
    IOFMessageFilterManagerService manager = 
            (IOFMessageFilterManagerService)getContext()
                .getAttributes().
                    get(IOFMessageFilterManagerService.class.getCanonicalName());

    if (manager == null) {
        sid = null;
        setStatus(Status.SERVER_ERROR_SERVICE_UNAVAILABLE);
    }
    
    if (fp.getSessionId() != null) {
        filter.put("sessionId", fp.getSessionId());
    }
    if (fp.getMac() != null) {
        filter.put("mac", fp.getMac());
    }
    if (fp.getDirection() != null) {
        filter.put("direction", fp.getDirection());
    }
    
    if (filter.isEmpty()) {
        setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    } else {
        if (log.isDebugEnabled()) {
            log.debug ("Call setupFilter: sid:{} filter:{}, period:{}", 
                       new Object[] {fp.getSessionId(), filter, 
                                     fp.getPeriod()*1000});
        }
        sid = manager.setupFilter(fp.getSessionId(), filter, 
                                  fp.getPeriod()*1000);
        output.setSessionId(sid);
        setStatus(Status.SUCCESS_OK);
    }
    
    return output;
}
 
Example 20
Project: jsf-sdk   File: TwoLevelMap.java   View Source Code Vote up 3 votes
/**
 * 删除一级key
 *
 * @param parentKey
 *         一级key
 * @return 删除结果
 */
public ConcurrentHashMap<K, V> removeIfEmpty(K parentKey) {
    ConcurrentHashMap<K, V> map = get(parentKey);
    return map.isEmpty() ? entries.remove(parentKey) : null;
}