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

项目:smarti    文件:SolrSearchQueryBuilder.java   
private void addDefaultParams(SolrQuery solrQuery, SolrEndpointConfiguration config) {
    if(MapUtils.isNotEmpty(config.getDefaults())){
        config.getDefaults().entrySet().stream()
        .filter(e -> StringUtils.isNoneBlank(e.getKey()) && e.getValue() != null)
        .forEach(e -> {
            String param = e.getKey();
            Collection<?> values;
            if(e.getValue() instanceof Collection){
                values = (Collection<?>)e.getValue();
            } else if(e.getValue().getClass().isArray()) {
                 values = Arrays.asList((Object[])e.getValue());
            } else {
                values = Collections.singleton(e.getValue());
            }
            Collection<String> strValues = StreamSupport.stream(values.spliterator(), false)
                    .map(Objects::toString) //convert values to strings
                    .filter(StringUtils::isNoneBlank) //filter blank values
                    .collect(Collectors.toList());
            if(!strValues.isEmpty()){
                solrQuery.add(param, strValues.toArray(new String[strValues.size()]));
            }
        });
    }
}
项目:sdcct    文件:AbstractXmlTransformOptions.java   
@Override
@SuppressWarnings({ CompilerWarnings.UNCHECKED })
public T setVariables(@Nullable Map<QName, XdmValue> vars) {
    this.vars.clear();

    if (!MapUtils.isEmpty(vars)) {
        this.vars.putAll(vars);
    }

    return ((T) this);
}
项目:plugin-security-fortify    文件:FortifyPluginResource.java   
@SuppressWarnings("unchecked")
@Override
public String getVersion(final Map<String, String> parameters) throws Exception {
    final FortifyCurlProcessor processor = new FortifyCurlProcessor();
    // Check the user can log-in to Fortify
    authenticate(parameters, processor);

    final String url = StringUtils.appendIfMissing(parameters.get(PARAMETER_URL), "/") + "api/v1/userSession/info";
    final CurlRequest request = new CurlRequest("POST", url, null, "Accept: application/json");
    request.setSaveResponse(true);
    processor.process(request);
    final String content = ObjectUtils.defaultIfNull(request.getResponse(), "{}");
    final ObjectMapper mapper = new ObjectMapper();
    final Map<String, ?> data = MapUtils
            .emptyIfNull((Map<String, ?>) mapper.readValue(content, Map.class).get("data"));
    final String version = (String) data.get("webappVersion");
    processor.close();
    return version;
}
项目:DDComponentForAndroid    文件:RouterProcessor.java   
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
    super.init(processingEnv);

    routerNodes = new ArrayList<>();

    mFiler = processingEnv.getFiler();
    types = processingEnv.getTypeUtils();
    elements = processingEnv.getElementUtils();
    typeUtils = new TypeUtils(types, elements);

    type_String = elements.getTypeElement("java.lang.String").asType();

    logger = new Logger(processingEnv.getMessager());

    Map<String, String> options = processingEnv.getOptions();
    if (MapUtils.isNotEmpty(options)) {
        host = options.get(KEY_HOST_NAME);
        logger.info(">>> host is " + host + " <<<");
    }
    if (host == null || host.equals("")) {
        host = "default";
    }
    logger.info(">>> RouteProcessor init. <<<");
}
项目:DDComponentForAndroid    文件:RouterProcessor.java   
/**
 * generate HostRouterTable.txt
 */
private void generateRouterTable() {
    String fileName = RouteUtils.genRouterTable(host);
    if (FileUtils.createFile(fileName)) {

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("auto generated, do not change !!!! \n\n");
        stringBuilder.append("HOST : " + host + "\n\n");

        for (Node node : routerNodes) {
            stringBuilder.append(node.getDesc() + "\n");
            stringBuilder.append(node.getPath() + "\n");
            Map<String, String> paramsType = node.getParamsDesc();
            if (MapUtils.isNotEmpty(paramsType)) {
                for (Map.Entry<String, String> types : paramsType.entrySet()) {
                    stringBuilder.append(types.getKey() + ":" + types.getValue() + "\n");
                }
            }
            stringBuilder.append("\n");
        }
        FileUtils.writeStringToFile(fileName, stringBuilder.toString(), false);
    }
}
项目:bluegreen-manager    文件:RdsSnapshotRestoreTask.java   
/**
 * Checks that mapped stage physical instnames are nonblank and are different from live physical instnames.
 * Returns silently if ok.
 */
private void checkDbMap()
{
  final String liveLogicalName = liveLogicalDatabase.getLogicalName();
  if (MapUtils.isEmpty(dbMap) || !dbMap.containsKey(liveLogicalName))
  {
    throw new IllegalArgumentException("Live logical database '" + liveLogicalName
        + "' is unmapped, don't know what stage physical instname to create");
  }
  final String stagePhysicalInstanceName = dbMap.get(liveLogicalName);
  if (StringUtils.isBlank(stagePhysicalInstanceName))
  {
    throw new IllegalArgumentException("You have mapped live logical database '" + liveLogicalName
        + "' to a blank string, we don't know what stage physical instname to create");
  }
  if (StringUtils.equals(stagePhysicalInstanceName, livePhysicalDatabase.getInstanceName()))
  {
    throw new IllegalArgumentException("You have mapped live logical database '" + liveLogicalName
        + "' to stage physical instname '" + stagePhysicalInstanceName
        + "', but live physical database is already using that instname");
  }
}
项目:java-antlr-json-parser    文件:Application.java   
public static void main(String[] args) {
    // Loader
    JsonLoader jsonLoader = new JsonLoader();

    // Decoding some examples
    HashMap<String, ?> result1 = new JsonDecoder().decode(jsonLoader.getJsonFromResources("example1.json"));
    HashMap<String, ?>  result2 = new JsonDecoder().decode(jsonLoader.getJsonFromResources("example2.json"));
    HashMap<String, ?>  result3 = new JsonDecoder().decode(jsonLoader.getJsonFromResources("example3.json"));

    // Displaying them
    MapUtils.debugPrint(System.out, "0", result1);
    System.out.println("-----------------------");
    MapUtils.debugPrint(System.out, "0", result2);
    System.out.println("-----------------------");
    MapUtils.debugPrint(System.out, "0", result3);
}
项目:tc    文件:TcTransportClientFactoryBean.java   
@Override
public TransportClient getObject() throws Exception {
    checkNotNull(settings);
    checkArgument(MapUtils.isNotEmpty(inetAddresses));
    PreBuiltTransportClient client = new PreBuiltTransportClient(Settings.builder().put(settings).build());
    inetAddresses.forEach((key, value) -> {
        try {
            client.addTransportAddress(
                    new InetSocketTransportAddress(InetAddress.getByName(key), value));
            log.info("add socket transport address [{}:{}] to client", key, value);
        } catch (UnknownHostException e) {
            throw new IllegalStateException(e);
        }
    });
    this.client = client;
    log.info("successful create transport client instance ...");
    return client;
}
项目:cachecloud    文件:InstanceStatsCenterImpl.java   
private InstanceCommandStats parseCommand(long instanceId, String command,
        Map<String, Object> commandMap, boolean isCommand, int type) {
    Long collectTime = MapUtils.getLong(commandMap, ConstUtils.COLLECT_TIME, null);
    if (collectTime == null) {
        return null;
    }
    Long count;
    if (isCommand) {
        count = MapUtils.getLong(commandMap, "cmdstat_" + command.toLowerCase(), null);
    } else {
        count = MapUtils.getLong(commandMap, command.toLowerCase(), null);
    }
    if (count == null) {
        return null;
    }
    InstanceCommandStats stats = new InstanceCommandStats();
    stats.setCommandCount(count);
    stats.setCommandName(command);
    stats.setCollectTime(collectTime);
    stats.setCreateTime(DateUtil.getDateByFormat(String.valueOf(collectTime), "yyyyMMddHHmm"));
    stats.setModifyTime(DateUtil.getDateByFormat(String.valueOf(collectTime), "yyyyMMddHHmm"));
    stats.setInstanceId(instanceId);

    return stats;
}
项目:cachecloud    文件:InstanceStatsCenterImpl.java   
@Override
public boolean saveStandardStats(Map<String, Object> infoMap, Map<String, Object> clusterInfoMap, String ip, int port, String dbType) {
    Assert.isTrue(infoMap != null && infoMap.size() > 0);
    Assert.isTrue(StringUtils.isNotBlank(ip));
    Assert.isTrue(port > 0);
    Assert.isTrue(infoMap.containsKey(ConstUtils.COLLECT_TIME), ConstUtils.COLLECT_TIME + " not in infoMap");
    long collectTime = MapUtils.getLong(infoMap, ConstUtils.COLLECT_TIME);
    StandardStats ss = new StandardStats();
    ss.setCollectTime(collectTime);
    ss.setIp(ip);
    ss.setPort(port);
    ss.setDbType(dbType);
    if (infoMap.containsKey(RedisConstant.DIFF.getValue())) {
        Map<String, Object> diffMap = (Map<String, Object>) infoMap.get(RedisConstant.DIFF.getValue());
        ss.setDiffMap(diffMap);
        infoMap.remove(RedisConstant.DIFF.getValue());
    } else {
        ss.setDiffMap(new HashMap<String, Object>(0));
    }
    ss.setInfoMap(infoMap);
    ss.setClusterInfoMap(clusterInfoMap);

    int mergeCount = instanceStatsDao.mergeStandardStats(ss);
    return mergeCount > 0;
}
项目:cachecloud    文件:MiscTest.java   
@Test
public void testMaps() {
    Map<String, Long> map = new HashMap<String, Long>();
    map.put("first", 10L);
    map.put("second", 20L);
    map.put("third", null);
    logger.info("third from map: {}", map.get("third"));

    try {
        ImmutableMap<String, Long> readMap = ImmutableMap.copyOf(map);
        logger.info("third from readMap: {}", readMap.get("third"));
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }

    logger.info("third from MapUtils: {}", MapUtils.getLong(map, "third", 1000L));
}
项目:coco    文件:CocoServer.java   
@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
    if (useRpc) {
        // 扫描带有 RpcService 注解的类并初始化 handlerMap 对象
        Map<String, Object> serviceBeanMap = ctx.getBeansWithAnnotation(RpcService.class);
        if (MapUtils.isNotEmpty(serviceBeanMap)) {
            for (Object serviceBean : serviceBeanMap.values()) {
                RpcService rpcService = serviceBean.getClass().getAnnotation(RpcService.class);
                String serviceName = rpcService.value().getName();
                String serviceVersion = rpcService.version();
                if (StringUtil.isNotEmpty(serviceVersion)) {
                    serviceName += "-" + serviceVersion;
                }
                handlerMap.put(serviceName, serviceBean);
            }
        }
    }
    if (useRestFul) {
        if (restfulServer == null) {
            throw new RuntimeException("restful server bean not be set ,please check it ");
        }
    }

}
项目:cuba    文件:ExceptionDialog.java   
public void sendSupportEmail(String message, String stackTrace) {
    try {
        User user = userSessionSource.getUserSession().getUser();
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timeSource.currentTimestamp());

        Map<String, Object> binding = new HashMap<>();
        binding.put("timestamp", date);
        binding.put("errorMessage", message);
        binding.put("stacktrace", stackTrace);
        binding.put("systemId", clientConfig.getSystemID());
        binding.put("userLogin", user.getLogin());

        if (MapUtils.isNotEmpty(additionalExceptionReportBinding)) {
            binding.putAll(additionalExceptionReportBinding);
        }

        reportService.sendExceptionReport(clientConfig.getSupportEmail(), MapUtils.unmodifiableMap(binding));

        Notification.show(messages.getMainMessage("exceptionDialog.emailSent"));
    } catch (Throwable e) {
        log.error("Error sending exception report", e);
        Notification.show(messages.getMainMessage("exceptionDialog.emailSendingErr"));
    }
}
项目:cuba    文件:AbstractTextFieldLoader.java   
protected void loadCaseConversion(TextInputField.CaseConversionSupported component, Element element) {
    final String caseConversion = element.attributeValue("caseConversion");
    if (StringUtils.isNotEmpty(caseConversion)) {
        component.setCaseConversion(TextInputField.CaseConversion.valueOf(caseConversion));
        return;
    }

    if (resultComponent.getMetaPropertyPath() != null) {
        Map<String, Object> annotations = resultComponent.getMetaPropertyPath().getMetaProperty().getAnnotations();

        //noinspection unchecked
        Map<String, Object> conversion = (Map<String, Object>) annotations.get(CaseConversion.class.getName());
        if (MapUtils.isNotEmpty(conversion)) {
            ConversionType conversionType = (ConversionType) conversion.get("type");
            TextInputField.CaseConversion tfCaseConversion = TextInputField.CaseConversion.valueOf(conversionType.name());
            component.setCaseConversion(tfCaseConversion);
        }
    }
}
项目:session-couchbase-spring-boot-starter    文件:PersistentDao.java   
@Override
public void updateSession(Map<String, Object> attributesToUpdate, Set<String> attributesToRemove, String namespace, String id) {
    StringBuilder statement = new StringBuilder("UPDATE `").append(bucket).append("` USE KEYS $1");
    List<Object> parameters = new ArrayList<>(attributesToUpdate.size() + attributesToRemove.size() + 1);
    parameters.add(id);
    int parameterIndex = 2;
    if (MapUtils.isNotEmpty(attributesToUpdate)) {
        statement.append(" SET ");
        for (Entry<String, Object> attribute : attributesToUpdate.entrySet()) {
            parameters.add(attribute.getValue());
            statement.append("data.`").append(namespace).append("`.`").append(attribute.getKey()).append("` = $").append(parameterIndex++).append(",");
        }
        deleteLastCharacter(statement);
    }
    if (CollectionUtils.isNotEmpty(attributesToRemove)) {
        statement.append(" UNSET ");
        attributesToRemove.forEach(name -> statement.append("data.`").append(namespace).append("`.`").append(name).append("`,"));
        deleteLastCharacter(statement);
    }
    executeQuery(statement.toString(), from(parameters));
}
项目:txazo    文件:HttpUtils.java   
public static String getParamsString(Map<String, Object> params) {
    if (MapUtils.isEmpty(params)) {
        return null;
    }

    String key = null;
    StringBuilder sb = new StringBuilder();
    for (Iterator<String> i = params.keySet().iterator(); i.hasNext(); ) {
        key = i.next();
        if (StringUtils.isBlank(key)) {
            continue;
        }
        sb.append(key).append("=").append(params.get(key)).append("&");
    }

    String paramsString = sb.toString();
    return StringUtils.isBlank(paramsString) ? null : paramsString.substring(0, paramsString.length() - 1);
}
项目:sdcct    文件:JaxbContextRepositoryImpl.java   
@Override
public <T> Marshaller buildMarshaller(T src, @Nullable Map<String, Object> marshallerProps) throws JAXBException {
    Marshaller marshaller = this.findTypeMetadata(src.getClass()).getContext().getContext().createMarshaller();
    Map<String, Object> mergedMarshallerProps = new HashMap<>(this.defaultMarshallerProps);

    if (!MapUtils.isEmpty(marshallerProps)) {
        mergedMarshallerProps.putAll(marshallerProps);
    }

    Object marshallerPropValue;

    for (String marshallerPropName : mergedMarshallerProps.keySet()) {
        marshallerPropValue = mergedMarshallerProps.get(marshallerPropName);

        try {
            marshaller.setProperty(marshallerPropName, marshallerPropValue);
        } catch (PropertyException e) {
            throw new JAXBException(String.format("Unable to set JAXB marshaller property (name=%s) value: %s", marshallerPropName, marshallerPropValue),
                e);
        }
    }

    return marshaller;
}
项目:sdcct    文件:JaxbContextRepositoryImpl.java   
@Override
public <T> Unmarshaller buildUnmarshaller(Class<T> resultClass, @Nullable Map<String, Object> unmarshallerProps) throws JAXBException {
    Unmarshaller unmarshaller = this.findTypeMetadata(resultClass).getContext().getContext().createUnmarshaller();
    Map<String, Object> mergedUnmarshallerProps = new HashMap<>(this.defaultUnmarshallerProps);

    if (!MapUtils.isEmpty(unmarshallerProps)) {
        mergedUnmarshallerProps.putAll(unmarshallerProps);
    }

    Object unmarshallerPropValue;

    for (String unmarshallerPropName : mergedUnmarshallerProps.keySet()) {
        unmarshallerPropValue = mergedUnmarshallerProps.get(unmarshallerPropName);

        try {
            unmarshaller.setProperty(unmarshallerPropName, unmarshallerPropValue);
        } catch (PropertyException e) {
            throw new JAXBException(
                String.format("Unable to set JAXB unmarshaller property (name=%s) value: %s", unmarshallerPropName, unmarshallerPropValue), e);
        }
    }

    return unmarshaller;
}
项目:Telemarketer    文件:RequestParser.java   
private static Cookie[] parseCookie(Map<String, String> headMap) {
    if (MapUtils.isEmpty(headMap)) {
        return new Cookie[0];
    }
    String cookies = headMap.get("cookie");
    if (StringUtils.isBlank(cookies)) {
        return new Cookie[0];
    }
    String[] split = cookies.split(";");
    Cookie[] cookieArray = new Cookie[split.length];
    for (int i = 0; i < split.length; i++) {
        String[] array;
        try {
            array = split[i].split("=", 2);
            cookieArray[i] = new Cookie(array[0], array[1]);
        } catch (RuntimeException e) {
            LOGGER.error("非法cookie", e);
            cookieArray[i] = new Cookie(StringUtils.EMPTY, StringUtils.EMPTY); // TODO 这里不能为空,如果出现了保留cookie怎么办
        }
    }
    return cookieArray;
}
项目:metron    文件:DefaultProfileBuilder.java   
/**
 * Executes a set of expressions whose results need to be assigned to a variable.
 * @param expressions Maps the name of a variable to the expression whose result should be assigned to it.
 * @param transientState Additional transient state provided to the expression.
 * @param expressionType The type of expression; init, update, result.  Provides additional context if expression execution fails.
 */
private void assign(Map<String, String> expressions, Map<String, Object> transientState, String expressionType) {

  // for each expression...
  for(Map.Entry<String, String> entry : MapUtils.emptyIfNull(expressions).entrySet()) {
    String var = entry.getKey();
    String expr = entry.getValue();

    try {
      // assign the result of the expression to the variable
      executor.assign(var, expr, transientState);

    } catch (Throwable e) {

      // in-scope variables = persistent state maintained by the profiler + the transient state
      Set<String> variablesInScope = new HashSet<>();
      variablesInScope.addAll(transientState.keySet());
      variablesInScope.addAll(executor.getState().keySet());

      String msg = format("Bad '%s' expression: error='%s', expr='%s', profile='%s', entity='%s', variables-available='%s'",
              expressionType, e.getMessage(), expr, profileName, entity, variablesInScope);
      LOG.error(msg, e);
      throw new ParseException(msg, e);
    }
  }
}
项目:disruptor-spring-manager    文件:JmxDisruptorManager.java   
private void registerDisruptorMBeans()  {
    Map<String, DefaultDisruptorConfig> disruptorsMBeanMap = getDisruptorMBeans();

    if(MapUtils.isEmpty(disruptorsMBeanMap)){
        LOG.warn("No Disruptor beans identified.");
    }else{
        for(Map.Entry<String, DefaultDisruptorConfig> entry: disruptorsMBeanMap.entrySet()){
            try {
                JmxDisruptor jmxDisruptor = new JmxDisruptor(entry.getValue(), entry.getKey());
                mBeanServer.registerMBean(jmxDisruptor, jmxDisruptor.getObjectName());
                LOG.debug(entry.getKey() + " Disruptor bean is resgistered in the MBeanServer.");
            } catch (Exception e) {
                LOG.error("Error registering Disruptor MBean.", e);
            }
        }
        LOG.debug(disruptorsMBeanMap.size() + " Disruptor beans regsitered in the MBeanServer");    
    }
}
项目:EasyReport    文件:C3p0DataSourcePool.java   
@Override
public DataSource wrap(ReportDataSource rptDs) {
    try {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(rptDs.getDriverClass());
        dataSource.setJdbcUrl(rptDs.getJdbcUrl());
        dataSource.setUser(rptDs.getUser());
        dataSource.setPassword(rptDs.getPassword());
        dataSource.setInitialPoolSize(MapUtils.getInteger(rptDs.getOptions(), "initialPoolSize", 3));
        dataSource.setMinPoolSize(MapUtils.getInteger(rptDs.getOptions(), "minPoolSize", 1));
        dataSource.setMaxPoolSize(MapUtils.getInteger(rptDs.getOptions(), "maxPoolSize", 20));
        dataSource.setMaxStatements(MapUtils.getInteger(rptDs.getOptions(), "maxStatements", 50));
        dataSource.setMaxIdleTime(MapUtils.getInteger(rptDs.getOptions(), "maxIdleTime", 1800));
        dataSource.setAcquireIncrement(MapUtils.getInteger(rptDs.getOptions(), "acquireIncrement", 3));
        dataSource.setAcquireRetryAttempts(MapUtils.getInteger(rptDs.getOptions(), "acquireRetryAttempts", 30));
        dataSource.setIdleConnectionTestPeriod(
            MapUtils.getInteger(rptDs.getOptions(), "idleConnectionTestPeriod", 60));
        dataSource.setBreakAfterAcquireFailure(
            MapUtils.getBoolean(rptDs.getOptions(), "breakAfterAcquireFailure", false));
        dataSource.setTestConnectionOnCheckout(
            MapUtils.getBoolean(rptDs.getOptions(), "testConnectionOnCheckout", false));
        return dataSource;
    } catch (Exception ex) {
        throw new RuntimeException("C3p0DataSourcePool Create Error", ex);
    }
}
项目:EasyReport    文件:DBCP2DataSourcePool.java   
@Override
public DataSource wrap(final ReportDataSource rptDs) {
    try {
        final BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(rptDs.getDriverClass());
        dataSource.setUrl(rptDs.getJdbcUrl());
        dataSource.setUsername(rptDs.getUser());
        dataSource.setPassword(rptDs.getPassword());
        dataSource.setInitialSize(MapUtils.getInteger(rptDs.getOptions(), "initialSize", 3));
        dataSource.setMaxIdle(MapUtils.getInteger(rptDs.getOptions(), "maxIdle", 20));
        dataSource.setMinIdle(MapUtils.getInteger(rptDs.getOptions(), "minIdle", 1));
        dataSource.setLogAbandoned(MapUtils.getBoolean(rptDs.getOptions(), "logAbandoned", true));
        dataSource.setRemoveAbandonedTimeout(
            MapUtils.getInteger(rptDs.getOptions(), "removeAbandonedTimeout", 180));
        dataSource.setMaxWaitMillis(MapUtils.getInteger(rptDs.getOptions(), "maxWait", 1000));
        return dataSource;
    } catch (final Exception ex) {
        throw new RuntimeException("C3p0DataSourcePool Create Error", ex);
    }
}
项目:bean-query    文件:NestedKeyValueMapSelector.java   
@Override
protected Map<String, Object> doSelect(Object item) {
  Map<String, Object> originalResult = this.selector.select(item);
  if(MapUtils.isEmpty(originalResult)){
    return originalResult;
  }

  Map<String,Object> result=new LinkedHashMap<String, Object>();
  for (Entry<String, Object> originalItem : originalResult.entrySet()) {
    String key = originalItem.getKey();
    Object value = originalItem.getValue();

    if(StringUtils.isBlank(key) || (!key.contains("."))){
      result.put(key, value);
      continue;
    }
    addNestedKeyValue(key, value, result);
  }

  return result;
}
项目:cloud-slang    文件:TriggerTestCaseEventListener.java   
public static Map<String, Serializable> extractOutputs(LanguageEventData data) {

        Map<String, Serializable> outputsMap = new HashMap<>();

        boolean thereAreOutputsForRootPath = data.containsKey(LanguageEventData.OUTPUTS) &&
                data.containsKey(LanguageEventData.PATH) &&
                data.getPath().equals(EXEC_START_PATH);

        if (thereAreOutputsForRootPath) {
            Map<String, Serializable> outputs = data.getOutputs();
            if (MapUtils.isNotEmpty(outputs)) {
                outputsMap.putAll(outputs);
            }
        }

        return outputsMap;
    }
项目:cloud-slang    文件:TestCasesYamlParser.java   
public Map<String, SlangTestCase> parseTestCases(SlangSource source) {

        if (StringUtils.isEmpty(source.getContent())) {
            loggingService.logEvent(Level.INFO, "No tests cases were found in: " + source.getName());
            return new HashMap<>();
        }
        Validate.notEmpty(source.getContent(), "Source " + source.getName() + " cannot be empty");

        try {
            @SuppressWarnings("unchecked")
            Map<String, Map> parsedTestCases = yaml.loadAs(source.getContent(), Map.class);
            if (MapUtils.isEmpty(parsedTestCases)) {
                loggingService.logEvent(Level.INFO, "No tests cases were found in: " + source.getName());
                return new HashMap<>();
            }
            return parseTestCases(parsedTestCases, source.getFilePath());
        } catch (Throwable e) {
            throw new RuntimeException(
                    "There was a problem parsing the YAML source: " + source.getName() + ".\n" + e.getMessage(), e
            );
        }
    }
项目:cloud-slang    文件:SlangTestRunner.java   
/**
 *
 * @param projectPath the project path
 * @param testCases the test cases
 * @param compiledFlows the compiled flows
 * @param runTestsResults is updated to reflect skipped, failed passes test cases.
 */
public void runTestsSequential(String projectPath, Map<String, SlangTestCase> testCases,
                               Map<String, CompilationArtifact> compiledFlows, IRunTestResults runTestsResults) {

    if (MapUtils.isEmpty(testCases)) {
        return;
    }
    printTestForActualRunSummary(TestCaseRunMode.SEQUENTIAL, testCases);

    for (Map.Entry<String, SlangTestCase> testCaseEntry : testCases.entrySet()) {
        SlangTestCase testCase = testCaseEntry.getValue();

        loggingService.logEvent(Level.INFO, "Running test: " +
                SlangTestCase.generateTestCaseReference(testCase) + " - " + testCase.getDescription());
        try {
            CompilationArtifact compiledTestFlow = getCompiledTestFlow(compiledFlows, testCase);
            runTest(testCase, compiledTestFlow, projectPath);
            runTestsResults.addPassedTest(testCase.getName(), new TestRun(testCase, null));
        } catch (RuntimeException e) {
            runTestsResults.addFailedTest(testCase.getName(), new TestRun(testCase, e.getMessage()));
        }
    }
}
项目:cloud-slang    文件:SlangTestRunner.java   
private void handleTestCaseFailuresFromOutputs(SlangTestCase testCase, String testCaseReference,
                                               Map<String, Serializable> outputs,
                                               Map<String, Serializable> executionOutputs) {
    String message;
    if (MapUtils.isNotEmpty(outputs)) {
        for (Map.Entry<String, Serializable> output : outputs.entrySet()) {
            String outputName = output.getKey();
            Serializable outputValue = output.getValue();
            Serializable executionOutputValue = executionOutputs.get(outputName);
            if (!executionOutputs.containsKey(outputName) ||
                    !outputsAreEqual(outputValue, executionOutputValue)) {
                message = TEST_CASE_FAILED + testCaseReference + " - " + testCase.getDescription() +
                        "\n\tFor output: " + outputName + "\n\tExpected value: " + outputValue +
                        "\n\tActual value: " + executionOutputValue;

                loggingService.logEvent(Level.ERROR, message);
                throw new RuntimeException(message);
            }
        }
    }
}
项目:cloud-slang    文件:ExecutableBuilder.java   
private Map<String, Object> getActionRawData(
        Map<String, Object> executableRawData,
        List<RuntimeException> errors,
        ParsedSlang parsedSlang, String execName) {
    Map<String, Object> actionRawData = new HashMap<>();
    Object javaActionRawData = executableRawData.get(SlangTextualKeys.JAVA_ACTION_KEY);
    Object pythonActionRawData = executableRawData.get(SlangTextualKeys.PYTHON_ACTION_KEY);
    if (javaActionRawData != null) {
        actionRawData.put(SlangTextualKeys.JAVA_ACTION_KEY,
                executableRawData.get(SlangTextualKeys.JAVA_ACTION_KEY));
    }
    if (pythonActionRawData != null) {
        actionRawData.put(SlangTextualKeys.PYTHON_ACTION_KEY,
                executableRawData.get(SlangTextualKeys.PYTHON_ACTION_KEY));
    }
    if (MapUtils.isEmpty(actionRawData)) {
        errors.add(new RuntimeException("Error compiling " + parsedSlang.getName() +
                ". Operation: " + execName + " has no action data"));
    }
    return actionRawData;
}
项目:cloud-slang    文件:ExecutableBuilder.java   
private String resolveDoReferenceId(String rawReferenceId, Map<String, String> imports, String namespace) {

        int numberOfDelimiters = StringUtils.countMatches(rawReferenceId, NAMESPACE_DELIMITER);
        String resolvedReferenceId;

        if (numberOfDelimiters == 0) {
            // implicit namespace
            resolvedReferenceId = namespace + NAMESPACE_DELIMITER + rawReferenceId;
        } else {
            String prefix = StringUtils.substringBefore(rawReferenceId, NAMESPACE_DELIMITER);
            String suffix = StringUtils.substringAfter(rawReferenceId, NAMESPACE_DELIMITER);
            if (MapUtils.isNotEmpty(imports) && imports.containsKey(prefix)) {
                // expand alias
                resolvedReferenceId = imports.get(prefix) + NAMESPACE_DELIMITER + suffix;
            } else {
                // full path without alias expanding
                resolvedReferenceId = rawReferenceId;
            }
        }

        return resolvedReferenceId;
    }
项目:cloud-slang    文件:SyncTriggerEventListener.java   
public static Map<String, Serializable> extractNotEmptyOutputs(Map<String, Serializable> data) {

        Map<String, Serializable> originalOutputs = (Map<String, Serializable>) data.get(LanguageEventData.OUTPUTS);
        Map<String, Serializable> extractedOutputs = new HashMap<>();

        if (MapUtils.isNotEmpty(originalOutputs)) {
            for (Map.Entry<String, Serializable> output : originalOutputs.entrySet()) {
                if (output.getValue() != null && !(StringUtils.isEmpty(output.getValue().toString()))) {
                    extractedOutputs.put(output.getKey(),
                            StringUtils.abbreviate(output.getValue().toString(), 0, OUTPUT_VALUE_LIMIT));
                }
            }
            return extractedOutputs;
        }
        return new HashMap<>();
    }
项目:myriad    文件:SchedulerUtils.java   
public static boolean isMatchSlaveAttributes(Offer offer,
        Map<String, String> requestAttributes) {
    boolean match = true;

    Map<String, String> offerAttributes = new HashMap<String, String>();
    for (Attribute attribute : offer.getAttributesList()) {
        offerAttributes.put(attribute.getName(), attribute.getText()
                .getValue());
    }

    // Match with offer attributes only if request has attributes.
    if (!MapUtils.isEmpty(requestAttributes)) {
        match = offerAttributes.equals(requestAttributes);
    }

    LOGGER.info(
            "Match status: {} for offer: {} and requestAttributes: {}",
            match, offer, requestAttributes);

    return match;
}
项目:profile    文件:ConnectionUtils.java   
/**
 * Returns the list of {@link ConnectionData} associated to the provider ID of
 * the specified profile
 *
 * @param profile       the profile that contains the connection data in its attributes
 * @param providerId    the provider ID of the connection
 * @param encryptor     the encryptor used to decrypt the accessToken, secret and refreshToken
 *
 * @return the list of connection data for the provider, or empty if no connection data was found
 */
public static List<ConnectionData> getConnectionData(Profile profile, String providerId,
                                                     TextEncryptor encryptor) throws CryptoException {
    Map<String, List<Map<String, Object>>> allConnections = profile.getAttribute(CONNECTIONS_ATTRIBUTE_NAME);

    if (MapUtils.isNotEmpty(allConnections)) {
        List<Map<String, Object>> connectionsForProvider = allConnections.get(providerId);

        if (CollectionUtils.isNotEmpty(connectionsForProvider)) {
            List<ConnectionData> connectionDataList = new ArrayList<>(connectionsForProvider.size());

            for (Map<String, Object> connectionDataMap : connectionsForProvider) {
                connectionDataList.add(mapToConnectionData(providerId, connectionDataMap, encryptor));
            }

            return connectionDataList;
        }
    }

    return Collections.emptyList();
}
项目:profile    文件:ConnectionUtils.java   
/**
 * Remove the {@link ConnectionData} associated to the provider ID and user ID.
 *
 * @param providerId        the provider ID of the connection
 * @param providerUserId    the provider user ID
 * @param profile           the profile where to remove the data from
 */
public static void removeConnectionData(String providerId, String providerUserId, Profile profile) {
    Map<String, List<Map<String, Object>>> allConnections = profile.getAttribute(CONNECTIONS_ATTRIBUTE_NAME);

    if (MapUtils.isNotEmpty(allConnections)) {
        List<Map<String, Object>> connectionsForProvider = allConnections.get(providerId);

        if (CollectionUtils.isNotEmpty(connectionsForProvider)) {
            for (Iterator<Map<String, Object>> iter = connectionsForProvider.iterator(); iter.hasNext();) {
                Map<String, Object> connectionDataMap = iter.next();

                if (providerUserId.equals(connectionDataMap.get("providerUserId"))) {
                    iter.remove();
                }
            }
        }
    }
}
项目:profile    文件:ProfileServiceRestClient.java   
@Override
public Profile createProfile(String tenantName, String username, String password, String email, boolean enabled,
                             Set<String> roles, Map<String, Object> attributes, String verificationUrl)
        throws ProfileException {
    MultiValueMap<String, String> params = createBaseParams();
    HttpUtils.addValue(PARAM_TENANT_NAME, tenantName, params);
    HttpUtils.addValue(PARAM_USERNAME, username, params);
    HttpUtils.addValue(PARAM_PASSWORD, password, params);
    HttpUtils.addValue(PARAM_EMAIL, email, params);
    HttpUtils.addValue(PARAM_ENABLED, enabled, params);
    HttpUtils.addValues(PARAM_ROLE, roles, params);
    if (MapUtils.isNotEmpty(attributes)) {
        HttpUtils.addValue(PARAM_ATTRIBUTES, serializeAttributes(attributes), params);
    }
    HttpUtils.addValue(PARAM_VERIFICATION_URL, verificationUrl, params);

    String url = getAbsoluteUrl(BASE_URL_PROFILE + URL_PROFILE_CREATE);

    return doPostForObject(url, params, Profile.class);
}
项目:apigateway-sdk-core    文件:ApiRequest.java   
public void addMappedParams(Map<String, String> params, ParamPosition position){
    if(MapUtils.isNotEmpty(params)){
        for(Entry<String, String> entry : params.entrySet()){
            addParam(entry.getKey(), entry.getValue(), position, false);
        }
    }
}
项目:apigateway-sdk-core    文件:SignUtil.java   
/**
 * 将headers合成一个字符串
 * 需要注意的是,HTTP头需要按照字母排序加入签名字符串
 * 同时所有加入签名的头的列表,需要用逗号分隔形成一个字符串,加入一个新HTTP头@"X-Ca-Signature-Headers"
 *
 */
private static String buildHeaders(Map<String, String> headers) {

    if (MapUtils.isNotEmpty(headers)) {
        // 筛选出需要签名的key
        Predicate<String> signFilter = new Predicate<String>() {
            @Override
            public boolean apply(String input) {
                return input.startsWith(SdkConstant.CLOUDAPI_CA_HEADER_TO_SIGN_PREFIX_SYSTEM);
            }
        };

        // 使用TreeMap,默认按照字母排序
        Map<String, String> headersToSign = new TreeMap<String, String>(Maps.filterKeys(headers, signFilter));

        // 所有加入签名的头的列表,需要用逗号分隔形成一个字符串,加入一个新HTTP头@"X-Ca-Signature-Headers"
        String signHeaders = Joiner.on(',').join(headersToSign.keySet());
        headers.put(SdkConstant.CLOUDAPI_X_CA_SIGNATURE_HEADERS, signHeaders);

        // 拼装签名内容
        Joiner.MapJoiner joiner = Joiner.on(SdkConstant.CLOUDAPI_LF).withKeyValueSeparator(':');
        return joiner.join(headersToSign);

    } else {
        return StringUtils.EMPTY;
    }


}
项目:talchain    文件:TransactionTouchedStorage.java   
void addReading(Map<DataWord, DataWord> entries) {
    if (MapUtils.isEmpty(entries)) return;

    for (Map.Entry<DataWord, DataWord> entry : entries.entrySet()) {
        if (!this.entries.containsKey(entry.getKey())) add(entry, false);
    }
}
项目:talchain    文件:TransactionTouchedStorage.java   
void addWriting(Map<DataWord, DataWord> entries) {
    if (MapUtils.isEmpty(entries)) return;

    for (Map.Entry<DataWord, DataWord> entry : entries.entrySet()) {
        add(entry, true);
    }
}