Java Code Examples for org.apache.commons.collections.MapUtils

The following examples show how to use org.apache.commons.collections.MapUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: sunbird-lms-service   Source File: BaseRequestValidator.java    License: MIT License 6 votes vote down vote up
/**
 * Method to check whether given mandatory fields is in given map or not.
 *
 * @param data Map contains the key value,
 * @param keys List of string represents the mandatory fields.
 */
public void checkMandatoryFieldsPresent(Map<String, Object> data, String... keys) {
  if (MapUtils.isEmpty(data)) {
    throw new ProjectCommonException(
        ResponseCode.invalidRequestData.getErrorCode(),
        ResponseCode.invalidRequestData.getErrorMessage(),
        ResponseCode.CLIENT_ERROR.getResponseCode());
  }
  Arrays.stream(keys)
      .forEach(
          key -> {
            if (StringUtils.isEmpty((String) data.get(key))) {
              throw new ProjectCommonException(
                  ResponseCode.mandatoryParamsMissing.getErrorCode(),
                  ResponseCode.mandatoryParamsMissing.getErrorMessage(),
                  ResponseCode.CLIENT_ERROR.getResponseCode(),
                  key);
            }
          });
}
 
Example 2
Source Project: incubator-atlas   Source File: EntityREST.java    License: Apache License 2.0 6 votes vote down vote up
private Map<String, Object> getAttributes(HttpServletRequest request) {
    Map<String, Object> attributes = new HashMap<>();

    if (MapUtils.isNotEmpty(request.getParameterMap())) {
        for (Map.Entry<String, String[]> e : request.getParameterMap().entrySet()) {
            String key = e.getKey();

            if (key != null && key.startsWith(PREFIX_ATTR)) {
                String[] values = e.getValue();
                String   value  = values != null && values.length > 0 ? values[0] : null;

                attributes.put(key.substring(PREFIX_ATTR.length()), value);
            }
        }
    }

    return attributes;
}
 
Example 3
Source Project: atlas   Source File: EntityConsumer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void processItem(AtlasEntity.AtlasEntityWithExtInfo entityWithExtInfo) {
    int delta = MapUtils.isEmpty(entityWithExtInfo.getReferredEntities())
            ? 1
            : entityWithExtInfo.getReferredEntities().size() + 1;

    long currentCount = counter.addAndGet(delta);
    currentBatch.addAndGet(delta);

    try {
        processEntity(entityWithExtInfo, currentCount);
        attemptCommit();
    } catch (Exception e) {
        LOG.info("Invalid entities. Possible data loss: Please correct and re-submit!", e);
    }
}
 
Example 4
Source Project: we-cmdb   Source File: CiServiceImplLegacyModelTest.java    License: Apache License 2.0 6 votes vote down vote up
@Transactional
@Test
public void addCiDataWithWrongCodeIdThenThrowException() {
    Map<String, Object> ciDataMap = MapUtils.putAll(new HashMap(), new Object[] { "name_en", "new system", "description", "new system desc", "system_type", 999 });
    try {
        ciService.create(2, ImmutableList.of(ciDataMap));
        Assert.assertFalse(true);// should not be reached
    } catch (BatchChangeException ex) {
        Assert.assertThat(ex.getExceptionHolders()
                .size(), greaterThan(0));
        Assert.assertThat(ex.getExceptionHolders()
                .get(0)
                .getException()
                .getClass(), equalTo(InvalidArgumentException.class));
    }
}
 
Example 5
Source Project: PeonyFramwork   Source File: TxHashMap.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 事务中不能修改
 * @return
 */
@Override
public Collection values() {
    // 考虑事务
    Collection<V> ret = new ArrayList<>();
    if(inTx()){
        Map<K, PrepareCachedEntry<K,V>> map = cachedDataThreadLocal.get();
        if(MapUtils.isNotEmpty(map)){
            for(PrepareCachedEntry prepareCachedEntry:map.values()){
                if(prepareCachedEntry.getOperType() != OperType.Delete){
                    ret.add((V)prepareCachedEntry.getData());
                }
            }
        }
    }
    ret.addAll(_map.values());
    return ret;
}
 
Example 6
Source Project: atlas   Source File: AtlasBuiltInTypes.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isValidMap(Map map) {
    Object guid = map.get(AtlasObjectId.KEY_GUID);

    if (guid != null && StringUtils.isNotEmpty(guid.toString())) {
        return true;
    } else {
        Object typeName = map.get(AtlasObjectId.KEY_TYPENAME);
        if (typeName != null && StringUtils.isNotEmpty(typeName.toString())) {
            Object uniqueAttributes = map.get(AtlasObjectId.KEY_UNIQUE_ATTRIBUTES);

            if (uniqueAttributes instanceof Map && MapUtils.isNotEmpty((Map) uniqueAttributes)) {
                return true;
            }
        }
    }

    return false;
}
 
Example 7
Source Project: atlas   Source File: EntityAuditListenerV2.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onBusinessAttributesUpdated(AtlasEntity entity, Map<String, Map<String, Object>> updatedBusinessAttributes) throws AtlasBaseException {
    if (MapUtils.isNotEmpty(updatedBusinessAttributes)) {
        MetricRecorder metric = RequestContext.get().startMetricRecord("entityAudit");

        List<EntityAuditEventV2> auditEvents = new ArrayList<>();

        for (Map.Entry<String, Map<String, Object>> entry : updatedBusinessAttributes.entrySet()) {
            String              bmName     = entry.getKey();
            Map<String, Object> attributes = entry.getValue();
            String              details    = AtlasJson.toJson(new AtlasStruct(bmName, attributes));
            EntityAuditEventV2  auditEvent = createEvent(entity, BUSINESS_ATTRIBUTE_UPDATE, "Updated business attributes: " + details);

            auditEvents.add(auditEvent);
        }

        auditRepository.putEventsV2(auditEvents);

        RequestContext.get().endMetricRecord(metric);
    }
}
 
Example 8
Source Project: yes-cart   Source File: VoShippingServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void fillShopSummaryDetails(final VoShopSummary summary, final long shopId, final String lang) throws Exception {

    if (federationFacade.isShopAccessibleByCurrentManager(summary.getShopId())) {
        final Map<CarrierDTO, Boolean> all = dtoCarrierService.findAllByShopId(shopId);

        for (final Map.Entry<CarrierDTO, Boolean> dto : all.entrySet()) {

            String name = dto.getKey().getName();
            if (MapUtils.isNotEmpty(dto.getKey().getDisplayNames()) && dto.getKey().getDisplayNames().get(lang) != null) {
                name = dto.getKey().getDisplayNames().get(lang);
            }
            summary.getCarriers().add(MutablePair.of(name, dto.getValue()));

        }

    } else {
        throw new AccessDeniedException("Access is denied");
    }
}
 
Example 9
Source Project: bird-java   Source File: CommonSaveProvider.java    License: MIT License 6 votes vote down vote up
public String update(CommonSaveParam param) {
    Serializable id = param.getEntityDTO().getId();
    if (id == null) return "";

    Map<String, String> fieldValueMap = this.getFieldValueMap(param);
    if (MapUtils.isEmpty(fieldValueMap)) return "";

    String tableName = formatName(param.getTableName());

    StringBuilder sb = new StringBuilder("update ")
            .append(tableName)
            .append(" set ");
    for (Map.Entry<String, String> entry : fieldValueMap.entrySet()) {
        sb.append(entry.getKey()).append(" = ").append(entry.getValue()).append(",");
    }

    String modifiedTime = "'" + dateFormat.format(new Date()) + "'";
    sb.append("modifiedTime = ").append(modifiedTime);
    sb.append(" where id = ").append("'").append(id).append("'");

    return sb.toString();
}
 
Example 10
Source Project: we-cmdb   Source File: CiServiceImplLegacyModelTest.java    License: Apache License 2.0 6 votes vote down vote up
@Transactional
@Test
public void updateIsNotNullableFieldThenGetException() {
    Map<String, Object> ciDataMap = MapUtils.putAll(new HashMap(), new Object[] { "guid", "0002_0000000002", "system_type", null });
    try {
        ciService.update(2, ImmutableList.of(ciDataMap));
        Assert.assertFalse(true);// should not be reached
    } catch (BatchChangeException ex) {
        Assert.assertThat(ex.getExceptionHolders()
                .size(), greaterThan(0));
        Assert.assertThat(ex.getExceptionHolders()
                .get(0)
                .getException()
                .getClass(), equalTo(InvalidArgumentException.class));
        Assert.assertThat(((InvalidArgumentException) ex.getExceptionHolders()
                .get(0)
                .getException()).getArgumentName(), equalTo("system_type"));
    }
}
 
Example 11
Source Project: sunbird-lms-service   Source File: BaseLocationActor.java    License: MIT License 6 votes vote down vote up
public void generateTelemetryForLocation(
    String targetObjId, Map<String, Object> data, String operation, Map<String, Object> context) {
  // object of telemetry event...
  try {
    Map<String, Object> targetObject = null;
    List<Map<String, Object>> correlatedObject = new ArrayList<>();
    targetObject =
        TelemetryUtil.generateTargetObject(targetObjId, JsonKey.LOCATION, operation, null);
    if (!MapUtils.isEmpty(data)
        && StringUtils.isNotEmpty((String) data.get(GeoLocationJsonKey.PARENT_ID))) {
      TelemetryUtil.generateCorrelatedObject(
          (String) data.get(GeoLocationJsonKey.PARENT_ID),
          JsonKey.LOCATION,
          null,
          correlatedObject);
    }
    TelemetryUtil.telemetryProcessingCall(data, targetObject, correlatedObject, context);
  } catch (Exception e) {
    ProjectLogger.log(e.getMessage(), e);
  }
}
 
Example 12
Source Project: yes-cart   Source File: VoFulfilmentServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void fillShopSummaryDetails(final VoShopSummary summary, final long shopId, final String lang) throws Exception {

    if (federationFacade.isShopAccessibleByCurrentManager(summary.getShopId())) {
        final Map<WarehouseDTO, Boolean> all = dtoWarehouseService.findAllByShopId(shopId);

        for (final Map.Entry<WarehouseDTO, Boolean> dto : all.entrySet()) {

            String name = dto.getKey().getName();
            if (MapUtils.isNotEmpty(dto.getKey().getDisplayNames()) && dto.getKey().getDisplayNames().get(lang) != null) {
                name = dto.getKey().getDisplayNames().get(lang);
            }
            summary.getFulfilmentCentres().add(MutablePair.of(name, dto.getValue()));

        }

    } else {
        throw new AccessDeniedException("Access is denied");
    }

}
 
Example 13
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;
}
 
Example 14
Source Project: framework   Source File: ShardedRedisCache.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Description: <br>
 * 
 * @author 王伟<br>
 * @taskId <br>
 * @param key
 * @param dataMap <br>
 */
@Override
protected void putNode(final byte[] key, final Map<byte[], byte[]> dataMap) {
    if (MapUtils.isNotEmpty(dataMap)) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = shardedPool.getResource();
            shardedJedis.hmset(key, dataMap);
        }
        finally {
            if (shardedJedis != null) {
                shardedJedis.close();
            }
        }
    }

}
 
Example 15
Source Project: DDMQ   Source File: ConsumeGroupBo.java    License: Apache License 2.0 6 votes vote down vote up
public static ConsumeGroupBo buildConsumeGroupBo(ConsumeGroup group) {
    ConsumeGroupBo groupBo = new ConsumeGroupBo();
    BeanUtils.copyProperties(group, groupBo);
    groupBo.setGroupId(group.getId());
    groupBo.setAlarmGroup(group.getGroupAlarmGroup());
    groupBo.setExtraParams(group.getGroupExtraParams());

    if (MapUtils.isEmpty(groupBo.getOperationParams())) {
        groupBo.setOperationParams(Maps.newHashMap());
    }
    ConsumeGroupConfig config = group.getConsumeGroupConfig();
    groupBo.getOperationParams().put(ConsumeGroupConfig.key_asyncThreads, String.valueOf(config.getAsyncThreads()));
    groupBo.getOperationParams().put(ConsumeGroupConfig.key_redisConfigStr, StringUtils.isEmpty(config.getRedisConfigStr()) ? "" : config.getRedisConfigStr());

    return groupBo;
}
 
Example 16
Source Project: rest-client   Source File: APIUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
* 
* @Title: headerStr 
* @Description: header map to string 
* @param @param hdr
* @param @return 
* @return String
* @throws
 */
public static String headerStr(Map<String, String> hdr)
{
    if (MapUtils.isEmpty(hdr))
    {
        return StringUtils.EMPTY;
    }

    StringBuilder sb = new StringBuilder();
    Set<Entry<String, String>> es = hdr.entrySet();
    for (Entry<String, String> e : es)
    {
        sb.append(e.toString().replaceFirst("=", " : "))
          .append(RESTUtil.lines(1));
    }
    return sb.toString();
}
 
Example 17
Source Project: carbon-identity   Source File: OpenIDExtension.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Populate the required claims with claim values.
 *
 * @param requiredClaims Required claims as requested by the RP.
 * @param requestDTO
 * @return A map, populated with ClaimDO objects which have OpenIDTag, that
 * is OpenID supported
 * claims.
 */
protected Map<String, OpenIDClaimDTO> populateAttributeValues(List<String> requiredClaims,
                                                              String openId, String profileName,
                                                              OpenIDAuthRequestDTO requestDTO) {
    Map<String, OpenIDClaimDTO> map = new HashMap<>();

    if (MapUtils.isEmpty(requestDTO.getResponseClaims())) {
        return map;
    }

    OpenIDClaimDTO[] claims = getClaimValues(requiredClaims, requestDTO.getResponseClaims());

    if (claims != null) {
        for (int i = 0; i < claims.length; i++) {
            if (claims[i] != null) {
                map.put(claims[i].getClaimUri(), claims[i]);
            }
        }
    }
    return map;
}
 
Example 18
Source Project: cloudbreak   Source File: FreeIpaConfigView.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("ExecutableStatementCount")
public Map<String, Object> toMap() {
    Map<String, Object> map = new HashMap<>();
    map.put("realm", ObjectUtils.defaultIfNull(this.realm, EMPTY_CONFIG_DEFAULT));
    map.put("domain", ObjectUtils.defaultIfNull(this.domain, EMPTY_CONFIG_DEFAULT));
    map.put("password", ObjectUtils.defaultIfNull(this.password, EMPTY_CONFIG_DEFAULT));
    map.put("dnssecValidationEnabled", this.dnssecValidationEnabled);
    map.put("reverseZones", ObjectUtils.defaultIfNull(this.reverseZones, EMPTY_CONFIG_DEFAULT));
    map.put("admin_user", ObjectUtils.defaultIfNull(this.adminUser, EMPTY_CONFIG_DEFAULT));
    map.put("freeipa_to_replicate", ObjectUtils.defaultIfNull(this.freeipaToReplicate, EMPTY_CONFIG_DEFAULT));
    if (MapUtils.isNotEmpty(backup.toMap())) {
        map.put("backup", this.backup.toMap());
    }
    if (CollectionUtils.isNotEmpty(this.hosts)) {
        map.put("hosts", this.hosts);
    }
    return map;
}
 
Example 19
Source Project: sunbird-lms-service   Source File: KeyCloakServiceImpl.java    License: MIT License 6 votes vote down vote up
@Override
public String getEmailVerifiedUpdatedFlag(String userId) {
  String fedUserId = getFederatedUserId(userId);
  UserResource resource =
      keycloak.realm(KeyCloakConnectionProvider.SSO_REALM).users().get(fedUserId);
  UserRepresentation user = resource.toRepresentation();
  Map<String, List<String>> map = user.getAttributes();
  List<String> list = null;
  if (MapUtils.isNotEmpty(map)) {
    list = map.get(JsonKey.EMAIL_VERIFIED_UPDATED);
  }
  if (CollectionUtils.isNotEmpty(list)) {
    return list.get(0);
  } else {
    return "";
  }
}
 
Example 20
protected Map<String, Object> createScriptVariables(SiteItem component, Map<String, Object> templateModel,
                                                    Map<String, Object> additionalModel) {
    Map<String, Object> variables = new HashMap<>();
    RequestContext context = RequestContext.getCurrent();

    if (context != null) {
        GroovyScriptUtils.addSiteItemScriptVariables(variables, context.getRequest(), context.getResponse(), servletContext,
                                                     component, templateModel);

        if (MapUtils.isNotEmpty(additionalModel)) {
            variables.putAll(additionalModel);
        }
    } else {
        throw new IllegalStateException("No current request context found");
    }

    return variables;
}
 
Example 21
Source Project: atlas   Source File: AtlasBaseTypeDef.java    License: Apache License 2.0 6 votes vote down vote up
public static StringBuilder dumpObjects(Map<?, ?> objects, StringBuilder sb) {
    if (sb == null) {
        sb = new StringBuilder();
    }

    if (MapUtils.isNotEmpty(objects)) {
        int i = 0;
        for (Map.Entry<?, ?> e : objects.entrySet()) {
            if (i > 0) {
                sb.append(", ");
            }

            sb.append(e.getKey()).append(":").append(e.getValue());
            i++;
        }
    }

    return sb;
}
 
Example 22
Source Project: assertj-swagger   Source File: ConsumerDrivenValidator.java    License: Apache License 2.0 6 votes vote down vote up
private void validateResponses(Map<String, Response> actualOperationResponses, Map<String, Response> expectedOperationResponses, String httpMethod, String path) {
    String message = String.format("Checking responses of '%s' operation of path '%s'", httpMethod, path);
    if (MapUtils.isNotEmpty(expectedOperationResponses)) {
        softAssertions.assertThat(actualOperationResponses).as(message).isNotEmpty();
        if (MapUtils.isNotEmpty(actualOperationResponses)) {
            softAssertions.assertThat(actualOperationResponses.keySet()).as(message).hasSameElementsAs(expectedOperationResponses.keySet());
            for (Map.Entry<String, Response> actualResponseEntry : actualOperationResponses.entrySet()) {
                Response expectedResponse = expectedOperationResponses.get(actualResponseEntry.getKey());
                Response actualResponse = actualResponseEntry.getValue();
                String responseName = actualResponseEntry.getKey();
                validateResponse(actualResponse, expectedResponse, responseName, httpMethod, path);
            }
        }
    } else {
        softAssertions.assertThat(actualOperationResponses).as(message).isNullOrEmpty();
    }
}
 
Example 23
Source Project: scaffold-cloud   Source File: MyMessageSource.java    License: MIT License 6 votes vote down vote up
/**
 * 从数据库中获取所有国际化配置 这边可以根据自己数据库表结构进行相应的业务实现
 * 对应的语言能够取出来对应的值就行了 无需一定要按照这个方法来
 */
public Map<String, Map<String, String>> loadAllMessageResourcesFromDB() {
    ResponseModel<List<SysI18nBO>> resp = sysI18nFeign.findList(new SysI18nAO());
    List<SysI18nBO> list = resp.getData();
    if (CollectionUtils.isNotEmpty(list)) {
        final Map<String, String> zhCnMessageResources = new HashMap<>(list.size());
        final Map<String, String> enUsMessageResources = new HashMap<>(list.size());
        for (SysI18nBO bo : list) {
            String name = bo.getModel() + "." + bo.getName();
            String zhText = bo.getZhCn();
            String enText = bo.getEnUs();
            zhCnMessageResources.put(name, zhText);
            enUsMessageResources.put(name, enText);
        }
        LOCAL_CACHE.put("zh", zhCnMessageResources);
        LOCAL_CACHE.put("en", enUsMessageResources);
    }
    return MapUtils.EMPTY_MAP;
}
 
Example 24
Source Project: atlas   Source File: EntityAuditListenerV2.java    License: Apache License 2.0 6 votes vote down vote up
private Map<String, Object> pruneEntityAttributesForAudit(AtlasEntity entity) {
    Map<String, Object> ret               = null;
    Map<String, Object> entityAttributes  = entity.getAttributes();
    List<String>        excludeAttributes = auditRepository.getAuditExcludeAttributes(entity.getTypeName());
    AtlasEntityType     entityType        = typeRegistry.getEntityTypeByName(entity.getTypeName());

    if (CollectionUtils.isNotEmpty(excludeAttributes) && MapUtils.isNotEmpty(entityAttributes) && entityType != null) {
        for (AtlasAttribute attribute : entityType.getAllAttributes().values()) {
            String attrName  = attribute.getName();
            Object attrValue = entityAttributes.get(attrName);

            if (excludeAttributes.contains(attrName)) {
                if (ret == null) {
                    ret = new HashMap<>();
                }

                ret.put(attrName, attrValue);
                entityAttributes.remove(attrName);
            }
        }
    }

    return ret;
}
 
Example 25
Source Project: apollo   Source File: RedisClient.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void hmSetByStringSerializer(String key, Map<String, String> values) throws Exception {
    Jedis jedis = null;
    try {
        jedis = this.jedisPool.getResource();
        if (MapUtils.isEmpty(values)) {
            values = Collections.emptyMap();
        }
        jedis.hmset(key, values);
        // LOG.info("hmSet key:" + key + " field:" + values.keySet());
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        this.jedisPool.returnBrokenResource(jedis);
        throw e;
    } finally {
        if (jedis != null) {
            this.jedisPool.returnResource(jedis);
        }
    }
}
 
Example 26
Source Project: sunbird-lms-service   Source File: BaseRequestValidator.java    License: MIT License 6 votes vote down vote up
/**
 * Method to check whether given header fields present or not.
 *
 * @param data List of strings representing the header names in received request.
 * @param keys List of string represents the headers fields.
 */
public void checkMandatoryHeadersPresent(Map<String, String[]> data, String... keys) {
  if (MapUtils.isEmpty(data)) {
    throw new ProjectCommonException(
        ResponseCode.invalidRequestData.getErrorCode(),
        ResponseCode.invalidRequestData.getErrorMessage(),
        ResponseCode.CLIENT_ERROR.getResponseCode());
  }
  Arrays.stream(keys)
      .forEach(
          key -> {
            if (ArrayUtils.isEmpty(data.get(key))) {
              throw new ProjectCommonException(
                  ResponseCode.mandatoryHeadersMissing.getErrorCode(),
                  ResponseCode.mandatoryHeadersMissing.getErrorMessage(),
                  ResponseCode.CLIENT_ERROR.getResponseCode(),
                  key);
            }
          });
}
 
Example 27
Source Project: joyqueue   Source File: ProducerConnectionState.java    License: Apache License 2.0 5 votes vote down vote up
public void handleRemoveProducers() {
    if (MapUtils.isEmpty(producerMap)) {
        return;
    }
    for (Map.Entry<String, Set<String>> entry : producerMap.entrySet()) {
        doHandleRemoveProducers(Lists.newArrayList(entry.getValue()), entry.getKey());
    }
}
 
Example 28
Source Project: joyqueue   Source File: BrokerMessageConverter.java    License: Apache License 2.0 5 votes vote down vote up
public static Map<String, FetchMessageData> convert(String app, Map<String, FetchTopicMessageAckData> topicMessageMap) {
    if (MapUtils.isEmpty(topicMessageMap)) {
        return Collections.emptyMap();
    }
    Map<String, FetchMessageData> result = Maps.newHashMap();
    for (Map.Entry<String, FetchTopicMessageAckData> entry : topicMessageMap.entrySet()) {
        String topic = entry.getKey();
        FetchTopicMessageAckData fetchTopicMessageAckData = entry.getValue();
        FetchMessageData fetchMessageData = new FetchMessageData(convert(topic, app, fetchTopicMessageAckData.getMessages()), fetchTopicMessageAckData.getCode());
        result.put(topic, fetchMessageData);
    }
    return result;
}
 
Example 29
Source Project: reliable   Source File: ScheduleReliableController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/clean", method = RequestMethod.GET)
public boolean clean() {

    List<String> cleanStatusList = new ArrayList<>();
    cleanStatusList.add(MessageStatus.OK.toString());
    cleanStatusList.add(MessageStatus.BLANK.toString());

    CriteriaBuilder.ResultMappedBuilder builder = CriteriaBuilder.buildResultMapped(ReliableMessage.class);
    builder.resultKey("id");
    builder.and().eq("underConstruction", false);
    builder.and().in("status", cleanStatusList);

    Criteria.ResultMappedCriteria resultMappedCriteria = builder.get();

    List<Map<String, Object>> list = this.reliableMessageService.listByResultMap(resultMappedCriteria);


    for (Map<String, Object> map : list) {
        String id = MapUtils.getString(map, "id");
        if (StringUtil.isNullOrEmpty(id))
            continue;

        this.messageResultService.removeByMessageId(id);
        this.reliableMessageService.remove(id);
    }

    return true;
}
 
Example 30
Source Project: hadoop-ozone   Source File: DatanodeIdYaml.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Read datanode.id from file.
 */
public static DatanodeDetails readDatanodeIdFile(File path)
    throws IOException {
  DatanodeDetails datanodeDetails;
  try (FileInputStream inputFileStream = new FileInputStream(path)) {
    Yaml yaml = new Yaml();
    DatanodeDetailsYaml datanodeDetailsYaml;
    try {
      datanodeDetailsYaml =
          yaml.loadAs(inputFileStream, DatanodeDetailsYaml.class);
    } catch (Exception e) {
      throw new IOException("Unable to parse yaml file.", e);
    }

    DatanodeDetails.Builder builder = DatanodeDetails.newBuilder();
    builder.setUuid(datanodeDetailsYaml.getUuid())
        .setIpAddress(datanodeDetailsYaml.getIpAddress())
        .setHostName(datanodeDetailsYaml.getHostName())
        .setCertSerialId(datanodeDetailsYaml.getCertSerialId());

    if (!MapUtils.isEmpty(datanodeDetailsYaml.getPortDetails())) {
      for (Map.Entry<String, Integer> portEntry :
          datanodeDetailsYaml.getPortDetails().entrySet()) {
        builder.addPort(DatanodeDetails.newPort(
            DatanodeDetails.Port.Name.valueOf(portEntry.getKey()),
            portEntry.getValue()));
      }
    }
    datanodeDetails = builder.build();
  }

  return datanodeDetails;
}