Java 类org.apache.commons.collections.MapUtils 实例源码

项目:easycode    文件:ShiroConfig.java   
@Bean
public ShiroFilterFactoryBean shiroFilter() {
    ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();

    //设置Filter映射
    LinkedHashMap<String, Filter> filterMap = new LinkedHashMap<>();
    DefaultCasFilter casFilter = new DefaultCasFilter();
    casFilter.setFailureUrl(loginProperties.getFailureUrl()); //配置验证错误时的失败页面
    casFilter.setReloginUrl(loginProperties.getCasLogin() + "&msg={0}"); //验证错误后显示登录页面,并提示错误信息。只试用于ErrorContext异常
    casFilter.setLogoutUrl(loginProperties.getCasLogout());
    filterMap.put("casFilter", casFilter);
    LogoutFilter logoutFilter = new LogoutFilter();
    logoutFilter.setRedirectUrl(loginProperties.getCasLogout() + "?service=" + loginProperties.getCasLogoutCallback());
    filterMap.put("logoutFilter", logoutFilter);
    filterMap.put("perms", new DefaultPermissionsAuthorizationFilter());
    filterMap.put("authc", new DefaultFormAuthenticationFilter());
    filterMap.put("sense", new SenseLoginFilter());
    factoryBean.setFilters(filterMap);

    factoryBean.setSecurityManager(securityManager());
    factoryBean.setLoginUrl(loginProperties.getCasLogin());
    factoryBean.setUnauthorizedUrl(loginProperties.getUnauthorizedUrl());
    //加载权限配置
    Ini ini = new Ini();
    ini.loadFromPath(loginProperties.getShiroFilterFile());
    //did they explicitly state a 'urls' section?  Not necessary, but just in case:
    Ini.Section section = ini.getSection(IniFilterChainResolverFactory.URLS);
    if (MapUtils.isEmpty(section)) {
        //no urls section.  Since this _is_ a urls chain definition property, just assume the
        //default section contains only the definitions:
        section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
    }
    factoryBean.setFilterChainDefinitionMap(section);
    return factoryBean;
}
项目:xproject    文件:AdminRoleMgtController.java   
/**
 * 配置角色-资源关系
 * @param request
 * @param response
 * @param parameter
 * @return
 */
@RequestMapping(value="/admin/role/config/submit", method=POST, consumes=APPLICATION_JSON, produces=APPLICATION_JSON)
@HttpAccessLogging(title="系统管理/角色管理/配置角色资源关系")
public Object configRoleResources(HttpServletRequest request, HttpServletResponse response,  @RequestBody Map<String,Object> parameter) {
    List<Long> resourceIdList = new ArrayList<Long>();
    String resourceIds = MapUtils.getString(parameter, "resourceIds");
    Long roleId = MapUtils.getLong(parameter, "roleId");
    if(!StringUtils.isEmpty(resourceIds)){
        String[] resourceIdArray = resourceIds.split(",");
        if(resourceIdArray != null && resourceIdArray.length > 0){
            for(String resourceId : resourceIdArray){
                resourceIdList.add(Long.valueOf(resourceId));
            }
        }
    }
    LoginToken<AdminUser> loginToken = ShiroUtils.getSessionAttribute(LoginToken.LOGIN_TOKEN_SESSION_KEY);
    adminRoleService.configRoleResources(roleId, resourceIdList, loginToken.getLoginId(), DateTimeUtils.formatNow());
    return genSuccessResult("配置成功!", null);
}
项目:configx    文件:HookStoreService.java   
/**
 * 创建Webhook事件参数
 *
 * @param webhookId
 * @param eventType
 * @param paramMap
 * @return
 */
public List<WebhookEventParam> createEventParams(int webhookId, int eventType, Map<String, String> paramMap) {
    if (MapUtils.isEmpty(paramMap)) {
        return Collections.emptyList();
    }

    List<WebhookEventParam> webhookEventParams = new ArrayList<>();
    WebhookEventParam webhookEventParam = null;
    for (Map.Entry<String, String> entry : paramMap.entrySet()) {
        webhookEventParam = newWebhookEventParam(webhookId, eventType, entry.getKey(), entry.getValue());
        webhookEventParams.add(webhookEventParam);
    }
    if (CollectionUtils.isNotEmpty(webhookEventParams)) {
        eventParamMapper.batchInsert(webhookEventParams);
    }
    return webhookEventParams;
}
项目:configx    文件:HookStoreService.java   
/**
 * 创建Webhook请求参数
 *
 * @param webhookId
 * @param paramMap
 * @return
 */
public List<WebhookRequestParam> createRequestParams(int webhookId, Map<String, String> paramMap) {
    if (MapUtils.isEmpty(paramMap)) {
        return Collections.emptyList();
    }

    List<WebhookRequestParam> webhookRequestParams = new ArrayList<>();
    WebhookRequestParam webhookRequestParam = null;
    for (Map.Entry<String, String> entry : paramMap.entrySet()) {
        webhookRequestParam = newWebhookRequestParam(webhookId, entry.getKey(), entry.getValue());
        webhookRequestParams.add(webhookRequestParam);
    }
    if (CollectionUtils.isNotEmpty(webhookRequestParams)) {
        webhookRequestParamMapper.batchInsert(webhookRequestParams);
    }
    return webhookRequestParams;
}
项目:xproject    文件:DefaultHttpAccessLoggingInterceptor.java   
protected AdminUser getAccessUser(HttpServletRequest request, LoggingContext loggingContext) {
    if(loggingContext.getHttpAccessLogging().isLogin()){ //用户正在登录
        HandlerMethod handlerMethod = loggingContext.getHandlerMethod();
        MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
        if(methodParameters != null){
            for(MethodParameter methodParameter : methodParameters){
                if(methodParameter.hasParameterAnnotation(RequestBody.class) && AdminUser.class.equals(methodParameter.getParameterType())){
                    HttpRequestParameter requestParameter = loggingContext.getHttpAccessLog().getRequestParameter();
                    Object requestBody = requestParameter.getBody();
                    MediaType contentType = loggingContext.getHttpAccessLog().getRequestContentType();
                    if (contentType != null && requestBody != null && requestBody instanceof Map && MediaType.APPLICATION_JSON.getType().equals(contentType.getType())) {
                        Map<String,Object> requestBodyMap = (Map<String, Object>) requestBody;
                        return adminUserService.getUserByUserName(MapUtils.getString(requestBodyMap, "userName"), false);
                    }
                }
            }
        }
        return null;
    }else{ //用户已登录
        LoginToken<AdminUser> loginToken = (LoginToken<AdminUser>) ShiroUtils.getSessionAttribute(LoginToken.LOGIN_TOKEN_SESSION_KEY);
        return loginToken == null ? null : loginToken.getLoginUser();
    }
}
项目:xproject    文件:AdminUserMgtController.java   
/**
 * 添加用户-角色配置
 * @param request
 * @param response
 * @param userId
 * @param roleIds
 * @return
 */
@RequestMapping(value="/admin/user/config/add", method=POST, consumes=APPLICATION_JSON, produces=APPLICATION_JSON)
@HttpAccessLogging(title="系统管理/用户管理/添加用户角色配置")
public Object addUserRoles(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String,Object> parameter) {
    Long userId = MapUtils.getLong(parameter, "userId");
    String roleIds = MapUtils.getString(parameter, "roleIds");
    List<Long> roleIdList = new ArrayList<Long>();
    if(!StringUtils.isEmpty(roleIds)){
        String[] roleIdArray = roleIds.split(",");
        if(roleIdArray != null && roleIdArray.length > 0){
            for(String roleId : roleIdArray){
                roleIdList.add(Long.valueOf(roleId));
            }
        }
    }

    LoginToken<AdminUser> loginToken = ShiroUtils.getSessionAttribute(LoginToken.LOGIN_TOKEN_SESSION_KEY);
    AdminUser user = new AdminUser();
    user.setUserId(userId);
    adminUserService.addUserRoles(user, roleIdList, loginToken.getLoginId(), DateTimeUtils.formatNow());
    return genSuccessResult("添加成功!", null);
}
项目:xproject    文件:AdminUserMgtController.java   
/**
 * 删除户-角色配置
 * @param request
 * @param response
 * @param userId
 * @param roleIds
 * @return
 */
@RequestMapping(value="/admin/user/config/del", method=POST, consumes=APPLICATION_JSON, produces=APPLICATION_JSON)
@HttpAccessLogging(title="系统管理/用户管理/删除用户角色配置")
public Object delUserRoles(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String,Object> parameter) {
    Long userId = MapUtils.getLong(parameter, "userId");
    String roleIds = MapUtils.getString(parameter, "roleIds");
    List<Long> roleIdList = new ArrayList<Long>();
    if(!StringUtils.isEmpty(roleIds)){
        String[] roleIdArray = roleIds.split(",");
        if(roleIdArray != null && roleIdArray.length > 0){
            for(String roleId : roleIdArray){
                roleIdList.add(Long.valueOf(roleId));
            }
        }
    }
    AdminUser user = new AdminUser();
    user.setUserId(userId);
    adminUserService.delUserRoles(user, roleIdList);
    return genSuccessResult("删除成功!", null);
}
项目:YiDu-Novel    文件:Utils.java   
/**
 * 判断对象是不是定义了 <br>
 * List的话,不为NULL和空<br>
 * 字符串的的话,不为NULL或空<br>
 * Integer的话,不为NULL或0<br>
 * 
 * @param obj
 *            要判断的对象
 * @return 是否定义了
 */
public static boolean isDefined(Object obj) {
    if (obj instanceof Collection) {
        return CollectionUtils.isNotEmpty((Collection<?>) obj);
    }

    if (obj instanceof Map) {
        return MapUtils.isNotEmpty((Map<?, ?>) obj);
    }

    if (obj instanceof String) {
        return StringUtils.isNotEmpty((String) obj);
    }

    if (obj instanceof Integer) {
        return obj != null && (Integer) obj != 0;
    }

    return obj != null;
}
项目:xm-gate    文件:GatewayResource.java   
private Map<String, Object> extractServiceMetaData(RouteVM routeVM) {
    Objects.requireNonNull(routeVM,
        "Can't extract service metadata because routeVM is not pass");

    Map<String, String> serviceInstancesStatus = routeVM.getServiceInstancesStatus();
    if (MapUtils.isEmpty(serviceInstancesStatus)) {
        log.error("Microservice instances has no statuses");
        return null;
    }
    Map<String, Object> result = null;
    for (ServiceInstance instance : routeVM.getServiceInstances()) {
        if (instance.getUri() == null || StringUtils.isBlank(instance.getUri().toString())) {
            continue;
        }
        String uri = instance.getUri().toString();
        if ("UP".equals(serviceInstancesStatus.get(uri))) {
            if (result == null) {
                result = new HashMap<>();
            }
            result.put(uri, getInstanceInfo(uri));
        }
    }
    return result;
}
项目:circus-train    文件:Source.java   
public SourceLocationManager getLocationManager(
    Table table,
    List<Partition> partitions,
    String eventId,
    Map<String, Object> copierOptions)
  throws IOException {
  if (MetaStoreUtils.isView(table)) {
    return new ViewLocationManager();
  }
  HdfsSnapshotLocationManager hdfsSnapshotLocationManager = new HdfsSnapshotLocationManager(getHiveConf(), eventId,
      table, partitions, snapshotsDisabled, sourceTableLocation, sourceCatalogListener);
  boolean ignoreMissingFolder = MapUtils.getBooleanValue(copierOptions,
      CopierOptions.IGNORE_MISSING_PARTITION_FOLDER_ERRORS, false);
  if (ignoreMissingFolder) {
    return new FilterMissingPartitionsLocationManager(hdfsSnapshotLocationManager, getHiveConf());
  }
  return hdfsSnapshotLocationManager;
}
项目:Yidu    文件:Utils.java   
/**
 * 判断对象是不是定义了 <br>
 * List的话,不为NULL和空<br>
 * 字符串的的话,不为NULL或空<br>
 * Integer的话,不为NULL或0<br>
 * 
 * @param obj
 *            要判断的对象
 * @return 是否定义了
 */
public static boolean isDefined(Object obj) {
    if (obj instanceof Collection) {
        return CollectionUtils.isNotEmpty((Collection<?>) obj);
    }

    if (obj instanceof Map) {
        return MapUtils.isNotEmpty((Map<?, ?>) obj);
    }

    if (obj instanceof String) {
        return StringUtils.isNotEmpty((String) obj);
    }

    if (obj instanceof Integer) {
        return obj != null && (Integer) obj != 0;
    }

    return obj != null;
}
项目:nan    文件:RevokerFactoryBean.java   
@Override
public void afterPropertiesSet() throws Exception {

    //获取服务注册中心
    IRegisterCenter4Invoker registerCenter4Consumer = ZKRegisterCenter.singleton();
    //初始化服务提供者列表到本地缓存
    registerCenter4Consumer.initProviderMap(remoteAppKey, groupName);

    //初始化Netty Channel,providerMap提供几个服务接口就是几个
    Map<String, List<ProviderService>> providerMap = registerCenter4Consumer.getServiceMetaDataMap4Consume();
    if (MapUtils.isEmpty(providerMap)) {
        throw new RuntimeException("service provider list is empty.");
    }
    NettyChannelPoolFactory.channelPoolFactoryInstance().initChannelPoolFactory(providerMap);

    //获取服务提供者代理对象
    RevokerProxyBeanFactory proxyFactory = RevokerProxyBeanFactory.singleton(targetInterface, timeout, clusterStrategy);
    this.serviceObject = proxyFactory.getProxy();

    //将消费者信息注册到注册中心
    InvokerService invoker = new InvokerService();
    invoker.setServiceItf(targetInterface);
    invoker.setRemoteAppKey(remoteAppKey);
    invoker.setGroupName(groupName);
    registerCenter4Consumer.registerInvoker(invoker);
}
项目:ECFileCache    文件:ZKChildMonitor.java   
@Override
public void onChanged(String parentPath, List<String> currentChildren) {
  if (currentChildren == null) {
    LOGGER.error("{} is null", parentPath);
    return;
  } else {
    LOGGER.warn("{} is changed to '{}'", parentPath, currentChildren);
  }

  Map<Integer, String> zkRedisCluster = new HashMap<Integer, String>();
  for (String node : currentChildren) {
    String nodeData = client.getData(String.class, parentPath + SLASH + node);
    zkRedisCluster.put(Integer.parseInt(node), nodeData);
  }

  if (MapUtils.isNotEmpty(zkRedisCluster) && !zkRedisCluster.equals(redisCluster)) {
    redisCluster = zkRedisCluster;
    if (isRedisAccessParallel) {
      redisAccess = new RedisAccessParallel(zkRedisCluster);
    } else {
      redisAccess = new RedisAccessSerial(zkRedisCluster);
    }
  }
}
项目:jeeWe    文件:BaseProvider.java   
@SuppressWarnings({"rawtypes", "unchecked"})
private Map<Object, Object> getBeanMap(Object obj) throws Exception {
    Map oMap = new BeanMap(obj);
    Map rMap = new HashMap();
    if (MapUtils.isEmpty(oMap)) {
        throw new Exception("实体类没有可用属性");
    } else {
        // 去除class属性
        for (Object key : oMap.keySet()) {
            if (!"class".equals(key)) {
                rMap.put(key, oMap.get(key));
            }
        }
    }
    return rMap;
}
项目:alm-rest-api    文件:RestConnector.java   
private static WebTarget createWebTarget(String uri, Map<String, String> queryParams) throws URISyntaxException
{
    WebTarget webTarget = null;

    URI u = new URI(uri);
    Client client = ClientBuilder.newClient();

    webTarget = client.target(u);

    if (MapUtils.isNotEmpty(queryParams))
    {
        for (Entry<String, String> entry : queryParams.entrySet())
        {
            if (StringUtils.isNotBlank(entry.getKey()) && StringUtils.isNotBlank(entry.getValue()))
            {
                String value = UriComponent.encode(
                        entry.getValue(),
                        UriComponent.Type.QUERY_PARAM_SPACE_ENCODED);

                webTarget = webTarget.queryParam(entry.getKey(), value);
            }
        }
    }

    return webTarget;
}
项目:OpenCyclos    文件:FieldHelper.java   
public <CFV extends CustomFieldValue> void toCustomFieldValues(final Class<CFV> valueClass, final List<? extends CustomField> allowedFields, final Map<String, String> customValues, final Collection<CFV> fieldValues) {
    if (MapUtils.isNotEmpty(customValues)) {
        for (String internalName : customValues.keySet()) {
            String value = customValues.get(internalName);
            if (StringUtils.isNotEmpty(value)) {
                CustomField field = customFieldHelper.findByInternalName(allowedFields, internalName);
                if (field == null) {
                    throw new IllegalArgumentException("Couldn't find custom field with internal name: '" + internalName + "' or the field is not searchable");
                } else {
                    CFV fieldValue;
                    try {
                        fieldValue = valueClass.newInstance();
                    } catch (Exception e) {
                        throw new IllegalStateException(e);
                    }
                    fieldValue.setField(field);
                    fieldValue.setValue(value);
                    fieldValues.add(fieldValue);
                }
            }
        }
    }
}
项目:lodsve-framework    文件:HttpClientUtils.java   
/**
 * 发送一个post请求
 *
 * @param url    地址
 * @param params 参数
 * @return 返回结果
 * @throws java.io.IOException
 */
public static String post(String url, Map<String, String> params) throws IOException {
    PostMethod method = new PostMethod(url);

    method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, DEFAULT_CHARSET);
    method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, DEFAULT_TIMEOUT);

    if (MapUtils.isNotEmpty(params)) {
        List<NameValuePair> pairs = new ArrayList<>(params.size());
        for (Map.Entry<String, String> entry : params.entrySet()) {
            NameValuePair pair = new NameValuePair();
            pair.setName(entry.getKey());
            pair.setValue(entry.getValue());

            pairs.add(pair);
        }

        method.addParameters(pairs.toArray(new NameValuePair[pairs.size()]));
    }

    return executeMethod(method);
}
项目:lodsve-framework    文件:BeanRegisterUtils.java   
/**
 * 注册,可以对beanName进行修改
 *
 * @param beanDefinitions BeanDefinition的map集合(key为beanName, value为BeanDefinition)
 * @param registry        spring注册Bean的对象
 */
public static void registerBeans(Map<String, BeanDefinition> beanDefinitions, BeanDefinitionRegistry registry, BeanNameBuilder builder) {
    if (MapUtils.isEmpty(beanDefinitions)) {
        return;
    }

    if (registry == null) {
        return;
    }

    Set<String> beanNames = beanDefinitions.keySet();
    for (String beanName : beanNames) {
        BeanDefinition bean = beanDefinitions.get(beanName);
        beanName = builder.buildBeanName(beanName, bean);
        if (registry.containsBeanDefinition(beanName)) {
            continue;
        }

        registry.registerBeanDefinition(beanName, bean);
    }
}
项目:apache-archiva    文件:DefaultArchivaConfiguration.java   
private boolean policyExists( String policyId )
{
    if ( MapUtils.isEmpty( prePolicies ) )
    {
        log.error( "No PreDownloadPolicies found!" );
        return false;
    }

    if ( MapUtils.isEmpty( postPolicies ) )
    {
        log.error( "No PostDownloadPolicies found!" );
        return false;
    }

    return ( prePolicies.containsKey( policyId ) || postPolicies.containsKey( policyId )
        || downloadErrorPolicies.containsKey( policyId ) );
}
项目:carbon-identity-framework    文件:DefaultClaimHandler.java   
/**
 * @param applicationConfig
 * @param locallyMappedUserRoles
 * @return
 */
private static String getServiceProviderMappedUserRoles(ApplicationConfig applicationConfig,
                                                        List<String> locallyMappedUserRoles, String claimSeparator)
        throws FrameworkException {

    Map<String, String> localToSpRoleMapping = applicationConfig.getRoleMappings();

    if (!MapUtils.isEmpty(localToSpRoleMapping)) {
        for (Map.Entry<String, String> roleMapping : localToSpRoleMapping.entrySet()) {
            if (locallyMappedUserRoles.contains(roleMapping.getKey())) {
                locallyMappedUserRoles.remove(roleMapping.getKey());
                locallyMappedUserRoles.add(roleMapping.getValue());
            }
        }
    }

    return StringUtils.join(locallyMappedUserRoles, claimSeparator);
}
项目:carbon-identity-framework    文件:DefaultPasswordLengthPolicy.java   
/**
   * Required initializations to get the configuration values from file.
   */
  @Override
  public void init(Map<String, String> params) {

/*
       *  Initialize the configuration with the parameters defined in config file.
 *  Eg.
 *  In the config file if you specify as follows.
 *  Password.policy.extensions.1.min.length=6
 *  Get the value from the map as shown below using key "min.length".
 */
      if (!MapUtils.isEmpty(params)) {
          MIN_LENGTH = Integer.parseInt(params.get("min.length"));
          MAX_LENGTH = Integer.parseInt(params.get("max.length"));
      }
  }
项目:scim-inbound-provisioning-scim2    文件:SupportUtils.java   
/**
 * build the jaxrs response
 * @param scimResponse
 * @return
 */
public static Response buildResponse(SCIMResponse scimResponse) {
    //create a response builder with the status code of the response to be returned.
    Response.ResponseBuilder responseBuilder = Response.status(scimResponse.getResponseStatus());
    //set the headers on the response
    Map<String, String> httpHeaders = scimResponse.getHeaderParamMap();
    if (MapUtils.isNotEmpty(httpHeaders)) {
        for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {

            responseBuilder.header(entry.getKey(), entry.getValue());
        }
    }
    //set the payload of the response, if available.
    if (scimResponse.getResponseMessage() != null) {
        responseBuilder.entity(scimResponse.getResponseMessage());
    }
    return responseBuilder.build();
}
项目:BCDS    文件:ClaimDataService.java   
private Long getPattrenId(String modelType, Map<Long, Integer> contentionCounts, List<DiagnosisCount> diagnosisCount, Long claimantAge, Long claimCount, long size, long cddAge) {
    List<DDMModelPattern> patterns = ddmDataService.getPatternId(modelType, claimantAge, claimCount, size, cddAge);
    List<Long> diagPattren = new ArrayList<>();
    List<Long> cntntPattrens = new ArrayList<>();
    Long pattrenId = null;
    if (CollectionUtils.isNotEmpty(patterns)) {
        List<Long> patternsList = patterns.stream().map(DDMModelPattern::getPatternId).collect(Collectors.toList());
        if(MapUtils.isNotEmpty(contentionCounts)){
             LOG.info("Contention count :::::: " + contentionCounts);
            cntntPattrens = ddmModelCntntService.getKneePatternId(contentionCounts, patternsList, modelType.toUpperCase());
        }
        if (CollectionUtils.isNotEmpty(cntntPattrens)) {
            //List<Long> diagPatternsList = patterns.stream().map(DDMModelPattern::getPatternId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(diagnosisCount)) {
                LOG.info("Diagnosis count :::::: " + diagnosisCount);
                diagPattren = ddmModelDiagService.getKneePatternId(diagnosisCount, cntntPattrens, modelType.toUpperCase());
            }
            LOG.info("PATTREN SIZE :::::: " + diagPattren);
            if (CollectionUtils.isNotEmpty(diagPattren)) {
                pattrenId = diagPattren.get(0);
                LOG.info("PATTREN ID :: " + pattrenId);
            }
        }
    }
    return pattrenId;
}
项目:bee    文件:ClusterListenerManager.java   
public void addConnect(ConnectInfo connectInfo) {
    ConnectInfo cacheConnectInfo = CONNECT_MAP.get(connectInfo.getConnect());
    if(cacheConnectInfo == null) {
        ConnectInfo oldConnectInfo = CONNECT_MAP.putIfAbsent(connectInfo.getConnect(), connectInfo);
        if(oldConnectInfo != null) {
            cacheConnectInfo = oldConnectInfo;
        }
    }
    if(cacheConnectInfo != null) {
        if(MapUtils.isEmpty(connectInfo.getServiceNames())) {
            if(LOGGER.isInfoEnabled()) {
                LOGGER.info("[cluster-listener-mgr] add services from:" + connectInfo);
            }
            connectInfo.addServiceNames(cacheConnectInfo.getServiceNames());
        } else {
            cacheConnectInfo.addServiceNames(connectInfo.getServiceNames());
        }
    }
    for(ClusterListener clusterListener : CLUSTER_LISTENER) {
        clusterListener.addConnected(connectInfo);
    }
}
项目:bee    文件:PropertiesUtils.java   
public static void convertPropertiesToMap(Map<String, String> results, Properties properties) {
    if(results == null) {
        LOGGER.error("params:[results] is null");
        return;
    }
    if(MapUtils.isEmpty(properties)) {
        LOGGER.error(("params:[properties] is empty"));
        return;
    }
    Iterator<?> iterator = properties.keySet().iterator();
    String key = null;
    String value = null;
    while(iterator.hasNext()) {
        key = iterator.next().toString();
        if(key.startsWith(COMMENT_PREFIX)) {
            // 注释的属性不加载
            continue;
        }
        value = properties.getProperty(key);
        if(StringUtils.isBlank(value)) {
            LOGGER.error(String.format("properties file has valid value, key[%s]", key));
            continue;
        }
        results.put(key, value);
    }
}
项目:MMServerEngine    文件:SqlHelper.java   
/**
 * 生成 update 语句
 */
public static String generateUpdateSql(Class<?> entityClass, Map<String, Object> fieldMap, String condition) {
    StringBuilder sql = new StringBuilder("update ").append(getTable(entityClass));
    if (MapUtils.isNotEmpty(fieldMap)) {
        sql.append(" set ");
        int i = 0;
        for (Map.Entry<String, Object> fieldEntry : fieldMap.entrySet()) {
            String fieldName = fieldEntry.getKey();
            String columnName = EntityHelper.getColumnName(entityClass, fieldName);
            if (i == 0) {
                sql.append(columnName).append(" = ?");
            } else {
                sql.append(", ").append(columnName).append(" = ?");
            }
            i++;
        }
    }
    sql.append(generateWhere(condition));
    return sql.toString();
}
项目:MMServerEngine    文件:DefaultDataAccessor.java   
@Override
public <T> T queryEntity(Class<T> entityClass, String sql, Object... params) {
    T result;
    try {
        Map<String, String> columnMap = EntityHelper.getColumnMap(entityClass);
        if (MapUtils.isNotEmpty(columnMap)) {
            result = queryRunner.query(sql, new BeanHandler<T>(entityClass, new BasicRowProcessor(new BeanProcessor(columnMap))), params);
        } else {
            result = queryRunner.query(sql, new BeanHandler<T>(entityClass), params);
        }
    } catch (SQLException e) {
        logger.error("查询出错!", e);
        throw new RuntimeException(e);
    }
    printSQL(sql);
    return result;
}
项目:MMServerEngine    文件:DefaultDataAccessor.java   
@Override
public <T> List<T> queryEntityList(Class<T> entityClass, String sql, Object... params) {
    List<T> result;
    try {
        Map<String, String> columnMap = EntityHelper.getColumnMap(entityClass);
        if (MapUtils.isNotEmpty(columnMap)) {
            result = queryRunner.query(sql, new BeanListHandler<T>(entityClass, new BasicRowProcessor(new BeanProcessor(columnMap))), params);
        } else {
            result = queryRunner.query(sql, new BeanListHandler<T>(entityClass), params);
        }
    } catch (SQLException e) {
        logger.error("查询出错!", e);
        throw new RuntimeException(e);
    }
    printSQL(sql);
    return result;
}
项目:cachecloud    文件:MachineCenterImpl.java   
@Override
public Map<String, Integer> getMachineInstanceCountMap() {
 List<Map<String,Object>> mapList = instanceDao.getMachineInstanceCountMap();
 if (CollectionUtils.isEmpty(mapList)) {
     return Collections.emptyMap();
 }

 Map<String, Integer> resultMap = new HashMap<String, Integer>();
 for(Map<String,Object> map : mapList) {
     String ip = MapUtils.getString(map, "ip", "");
     if (StringUtils.isBlank(ip)) {
         continue;
     }
     int count = MapUtils.getIntValue(map, "count");
     resultMap.put(ip, count);
 }
    return resultMap;
}
项目:cachecloud    文件:RedisCenterImpl.java   
private AppStats getAppStats(long appId, long collectTime, Table<RedisConstant, String, Long> table,
                             Map<RedisConstant, Map<String, Object>> infoMap) {
    AppStats appStats = new AppStats();
    appStats.setAppId(appId);
    appStats.setCollectTime(collectTime);
    appStats.setModifyTime(new Date());
    appStats.setUsedMemory(MapUtils.getLong(infoMap.get(RedisConstant.Memory), RedisInfoEnum.used_memory.getValue(), 0L));
    appStats.setHits(MapUtils.getLong(table.row(RedisConstant.Stats), RedisInfoEnum.keyspace_hits.getValue(), 0L));
    appStats.setMisses(MapUtils.getLong(table.row(RedisConstant.Stats), RedisInfoEnum.keyspace_misses.getValue(), 0L));
    appStats.setEvictedKeys(MapUtils.getLong(table.row(RedisConstant.Stats), RedisInfoEnum.evicted_keys.getValue(), 0L));
    appStats.setExpiredKeys(MapUtils.getLong(table.row(RedisConstant.Stats), RedisInfoEnum.expired_keys.getValue(), 0L));
    appStats.setNetInputByte(MapUtils.getLong(table.row(RedisConstant.Stats), RedisInfoEnum.total_net_input_bytes.getValue(), 0L));
    appStats.setNetOutputByte(MapUtils.getLong(table.row(RedisConstant.Stats), RedisInfoEnum.total_net_output_bytes.getValue(), 0L));
    appStats.setConnectedClients(MapUtils.getIntValue(infoMap.get(RedisConstant.Clients), RedisInfoEnum.connected_clients.getValue(), 0));
    appStats.setObjectSize(getObjectSize(infoMap));
    return appStats;
}
项目:cachecloud    文件:RedisCenterImpl.java   
private List<AppCommandStats> getCommandStatsList(long appId, long collectTime,
                                                  Table<RedisConstant, String, Long> table) {
    Map<String, Long> commandMap = table.row(RedisConstant.Commandstats);
    List<AppCommandStats> list = new ArrayList<AppCommandStats>();
    if (commandMap == null) {
        return list;
    }
    for (String key : commandMap.keySet()) {
        String commandName = key.replace("cmdstat_", "");
        long callCount = MapUtils.getLong(commandMap, key, 0L);
        if (callCount == 0L) {
            continue;
        }
        AppCommandStats commandStats = new AppCommandStats();
        commandStats.setAppId(appId);
        commandStats.setCollectTime(collectTime);
        commandStats.setCommandName(commandName);
        commandStats.setCommandCount(callCount);
        commandStats.setModifyTime(new Date());
        list.add(commandStats);
    }
    return list;
}
项目:cachecloud    文件:RedisCenterImpl.java   
@Override
public Map<String, Long> getInstanceSlowLogCountMapByAppId(Long appId, Date startDate, Date endDate) {
    try {
        List<Map<String, Object>> list = instanceSlowLogDao.getInstanceSlowLogCountMapByAppId(appId, startDate, endDate);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyMap();
        }
        Map<String, Long> resultMap = new LinkedHashMap<String, Long>();
        for (Map<String, Object> map : list) {
            long count = MapUtils.getLongValue(map, "count");
            String hostPort = MapUtils.getString(map, "hostPort");
            if (StringUtils.isNotBlank(hostPort)) {
                resultMap.put(hostPort, count);
            }
        }
        return resultMap;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return Collections.emptyMap();
    }
}
项目:cachecloud    文件:AlertConfigStrategy.java   
/**
 * 获取全量统计项中的内容
 * @param redisInfo
 * @param attribute
 * @return
 */
protected static Object getValueFromRedisInfo(StandardStats standardStats, String attribute) {
    if (standardStats == null) {
        return null;
    }
    // 转换成Map
    Map<String, Object> infoMap = JsonUtil.fromJson(standardStats.getInfoJson(), Map.class);
    if (MapUtils.isEmpty(infoMap)) {
        return null;
    }
    for (Entry<String, Object> entry : infoMap.entrySet()) {
        Object object = entry.getValue();
        // 转换成Map<String, Map<String,Object>>
        if (!(object instanceof Map)) {
            continue;
        }
        Map<String, Object> sectionInfoMap = (Map<String, Object>) object;
        if (sectionInfoMap != null && sectionInfoMap.containsKey(attribute)) {
            return MapUtils.getObject(sectionInfoMap, attribute);
        }
    }
    return null;
}
项目:easycode    文件:StringTemplateProcessor.java   
/**
 * 替换模板内的占位符格式有以下三种:
 * <ul>
 *     <li>template:<i>{}走路掉{}里了</i>  model:<i>["小明", "坑"]</i> &nbsp; --> <i><b>小明</b>走路掉<b>坑</b>里了</i></li>
 *     <li>template:<i>{0}走路掉{1}里了</i>  model:<i>["小东", "缸"]</i> &nbsp; --> <i><b>小东</b>走路掉<b>缸</b>里了</i></li>
 *     <li>template:<i>{name}走路掉{thing}里了</i>  model:<i>{"name": "小李", "thing": "池塘"}</i> &nbsp; --> <i><b>小李</b>走路掉<b>池塘</b>里了</i></li>
 * </ul>
 * @param template 模板内容
 * @param model 替换数据 - 可以是POJO对象或者Map类型或者数组
 * @return
 */
@Override
public String process(String template, Object model) throws ParseTemplateException {
    int mode = Strings.EMPTY_INDEX_MODEL | Strings.NUM_INDEX_MODEL | Strings.KEY_VALUE_MODEL;
    try {
        String roughTmpl;
        if (model != null && model.getClass().isArray()
                && !model.getClass().getComponentType().isPrimitive()) {
            roughTmpl = Strings.formatMix(template, mode, defaultVal, (Object[]) model);
        } else {
            roughTmpl = Strings.formatMix(template, mode, defaultVal, model);
        }
        if (MapUtils.isNotEmpty(this.globalModel)) {
            roughTmpl = Strings.formatMix(roughTmpl, mode, defaultVal, this.globalModel);
        }
        return roughTmpl;
    } catch (Exception e) {
        throw new ParseTemplateException("Parse template error.", e);
    }
}
项目:marathon-plugin    文件:MarathonBuilderImpl.java   
private void setEnv() {
    if (CollectionUtils.isNotEmpty(config.getEnv())) {
        Map<String, Object> envsToAdd = new HashMap<>(config.getEnv().size());
        for (MarathonVars var : config.getEnv()) {
            envsToAdd.put(
                    Util.replaceMacro(var.getName(), envVars),
                    Util.replaceMacro(var.getValue(), envVars));
        }

        if (MapUtils.isEmpty(getApp().getEnv())) {
            getApp().setEnv(envsToAdd);
        } else {
            getApp().getEnv().putAll(envsToAdd);
        }
    }
}
项目:dcos-commons    文件:PodSpecsCannotUseUnsupportedFeatures.java   
private static boolean podRequestsCNI(PodSpec podSpec) {
    // if we don't have a cluster that supports CNI port mapping make sure that we don't either (1) specify
    // any networks and/ (2) if we are make sure we didn't explicitly do any port mapping or that
    // any of the tasks ask for ports (which will automatically be forwarded, this requiring port mapping).
    for (NetworkSpec networkSpec : podSpec.getNetworks()) {
        if (!MapUtils.isEmpty(networkSpec.getPortMappings())) {
            return true;
        }
    }

    for (TaskSpec taskSpec : podSpec.getTasks()) {
        for (ResourceSpec resourceSpec : taskSpec.getResourceSet().getResources()) {
            if (resourceSpec.getName().equals("ports")) {
                return true;
            }
        }
    }
    return false;
}
项目:excel-bean    文件:ListUtils.java   
/**
 * 将列表转换成Key - List&lt;Map&lt;String,Object&gt;&gt; 形式,方便取值,如果key值重复则在列表中添加,如果Key值取不到或者为空则使用默认值
 * 
 * @param list 列表
 * @param key 作为key 的属性名称
 * @param defaultKey Key 的默认值
 * @param <T> 任意类型
 * @return Map
 */
public static <T> Map<String, List<Map<String, T>>> keyList(List<Map<String, T>> list, String key,
        String defaultKey) {
    Map<String, List<Map<String, T>>> result = new LinkedHashMap<String, List<Map<String, T>>>();
    if (list == null || list.size() == 0)
        return result;
    for (Map<String, T> map : list) {
        String keyValue = MapUtils.getString(map, key, defaultKey);
        if (result.containsKey(keyValue)) {
            result.get(keyValue).add(map);
        } else {
            List<Map<String, T>> tempList = new ArrayList<>();
            tempList.add(map);
            result.put(keyValue, tempList);
        }
    }
    return result;
}
项目:visitormanagement    文件:HttpConnectorHelper.java   
/** 
 * 
 * @param map
 * 
 * @return HttpEntity
 */
public static HttpEntity buildEntityWithBodyParam(Map<String, String> map) {
    if (MapUtils.isEmpty(map)) {
        return null;
    }
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    map.forEach((k, v) -> builder.addTextBody(k, v));
    return builder.build();
}
项目:visitormanagement    文件:HttpConnectorHelper.java   
/**
 * @param buildMap
 * @param partParam
 * 
 * @return HttpEntity
 */
public static HttpEntity buildMultiPartEntity(Map<String, String> buildMap, Map<String, ContentBody> partParam) {
    if (MapUtils.isEmpty(buildMap)) {
        return null;
    }
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    buildMap.forEach((k, v) -> builder.addTextBody(k, v));
    if (MapUtils.isNotEmpty(partParam)) {
        partParam.forEach((k, v) -> builder.addPart(k, v)); 
    }
    return builder.build();
}
项目:vind    文件:DocumentFactory.java   
@Override
public String toString(){
    final String serialiceString = "{" +
            "\"type\":\"%s\"," +
            "\"updatable\":%s," +
            "\"fields\":%s" +
            "}";
    return String.format(serialiceString,
            this.type,
            this.updatable,
            MapUtils.isNotEmpty(this.fields)? "{"+this.fields.entrySet().stream()
                    .map(e ->"\""+e.getKey()+"\":"+e.getValue())
                    .collect(Collectors.joining(", ")) + "}" :this.fields
    );
}