private Policy findPolicy(String policyId) {
    if (MapUtils.isEmpty(prePolicies)) {
      log.error("No PreDownloadPolicies found!");
      return null;
    }

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

    Policy policy;

    policy = prePolicies.get(policyId);
    if (policy != null) {
      return policy;
    }

    policy = postPolicies.get(policyId);
    if (policy != null) {
      return policy;
    }

    policy = downloadErrorPolicies.get(policyId);
    if (policy != null) {
      return policy;
    }

    return null;
  }
  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));
  }
  private void ensureDestinationImageMap() {
    if (MapUtils.isEmpty(getParameters().getDiskInfoDestinationMap())) {
      diskInfoDestinationMap = new HashMap<>();

      if (getVmTemplate() == null) {
        return;
      }

      if (!Guid.isNullOrEmpty(getParameters().getStorageDomainId())) {
        Guid storageId = getParameters().getStorageDomainId();
        ArrayList<Guid> storageIds = new ArrayList<>();
        storageIds.add(storageId);
        for (DiskImage image : getVmTemplate().getDiskTemplateMap().values()) {
          image.setStorageIds(storageIds);
          diskInfoDestinationMap.put(image.getId(), image);
        }
      } else {
        ImagesHandler.fillImagesMapBasedOnTemplate(
            getVmTemplate(), diskInfoDestinationMap, destStorages);
      }
    } else {
      diskInfoDestinationMap = getParameters().getDiskInfoDestinationMap();
    }

    storageToDisksMap =
        ImagesHandler.buildStorageToDiskMap(
            getVmTemplate().getDiskTemplateMap().values(), diskInfoDestinationMap);
  }
  /**
   * create batch {@link ConfigItem} instances by name and value.
   *
   * @param configItem batch name and value
   * @return {@link ConfigItem} instances
   */
  public List<ConfigItem> newItems(Map<String, String> configItem) {
    if (MapUtils.isEmpty(configItem)) {
      return Collections.emptyList();
    }

    Date createDate = new Date();

    List<ConfigItem> ret = new ArrayList<ConfigItem>(configItem.size());

    Iterator<Entry<String, String>> iter = configItem.entrySet().iterator();
    while (iter.hasNext()) {
      Entry<String, String> entry = iter.next();
      ConfigItem item = new ConfigItem();
      item.setName(entry.getKey());
      item.setVal(entry.getValue());
      item.setRef(false);
      item.setCreateTime(createDate);
      item.setGroupId(getId());
      item.setShareable(false);
      item.setVersionId(getVersionId());

      ret.add(item);
    }

    return ret;
  }
  /**
   * Parse the template's (Groovy) script. The script must implement {@link IEmailDataScript}.
   *
   * @param keyVals
   * @return
   */
  public Map<String, String> parseScript(Map<String, String> keyVals) {

    Map<String, String> resultMap = new HashMap<String, String>();
    if (null == _script || "".equals(_script)) {
      return resultMap;
    }

    ClassLoader parent = getClass().getClassLoader();
    GroovyClassLoader loader = new GroovyClassLoader(parent);
    Class<?> clazz = loader.parseClass(_script, "EmailDataScript");

    IEmailDataScript scriptDelegate;
    try {
      scriptDelegate = (IEmailDataScript) clazz.newInstance();
      resultMap = scriptDelegate.getEmailData((HashMap<String, String>) keyVals);

      if (MapUtils.isEmpty(resultMap)) {
        // This may not necessarily be an error for some parameter values.
        LOGGER.warn(
            "sendTemplateEmail no data returned from Groovy script for templateID: " + _templateId);
      }
    } catch (InstantiationException e) {
      LOGGER.error(DetailedException.getMessageOrType(e));
    } catch (IllegalAccessException e) {
      LOGGER.error(DetailedException.getMessageOrType(e));
    } catch (CompilationFailedException e) {
      LOGGER.error(DetailedException.getMessageOrType(e));
    }

    return resultMap;
  }
示例#6
0
  public void addProperty(String name, int value) {
    if (MapUtils.isEmpty(integerProperties)) {
      integerProperties = new HashMap<String, Integer>();
    }

    integerProperties.put(name, value);
  }
示例#7
0
  public void addProperty(String name, boolean value) {
    if (MapUtils.isEmpty(booleanProperties)) {
      booleanProperties = new HashMap<String, Boolean>();
    }

    booleanProperties.put(name, value);
  }
示例#8
0
  public Integer getIntValue(String property) {
    if (MapUtils.isEmpty(integerProperties) || !integerProperties.containsKey(property)) {
      return null;
    }

    return integerProperties.get(property);
  }
 @Override
 protected AbstractBTGRuleDataEvent getEvent(final HttpServletRequest request) {
   RequestParametersUsedBTGRuleDataEvent result = null;
   final Map<String, String[]> params = request.getParameterMap();
   if (!MapUtils.isEmpty(params)) {
     result = new RequestParametersUsedBTGRuleDataEvent(params);
   }
   return result;
 }
  /**
   * 从配置容器中加载所有的配置属性值映射<br>
   *
   * @param props
   * @throws IOException
   */
  @Override
  protected void loadProperties(Properties props) throws IOException {
    Map<String, String> allConfigPropertyMap = configContext.getAllConfigPropertyKey2ValueMap();
    if (MapUtils.isEmpty(allConfigPropertyMap)) {
      return;
    }

    for (Entry<String, String> entryTemp : allConfigPropertyMap.entrySet()) {
      props.setProperty(entryTemp.getKey(), entryTemp.getValue());
    }
  }
示例#11
0
  public boolean isRegexEnabled(String name) {
    if (MapUtils.isEmpty(booleanProperties)) {
      return false;
    }

    for (Map.Entry<String, Boolean> value : booleanProperties.entrySet()) {
      if (name.matches(value.getKey())) {
        return value.getValue();
      }
    }

    return false;
  }
  /**
   * This method creates an PostalAddressType from the values in the provided map. The following
   * keys are expected in the provided map (Taken from EbrimConstants):
   *
   * <p>CITY = "city"; COUNTRY = "country"; POSTAL_CODE = "postalCode"; STATE_OR_PROVINCE =
   * "stateOrProvince"; STREET = "street"; STREET_NUMBER = "streetNumber";
   *
   * @param map the Map representation of the PostalAddressType to generate, null returns empty
   *     Optional
   * @return Optional PostalAddressType created from the values in the map
   */
  public Optional<PostalAddressType> convert(Map<String, Object> map) {
    Optional<PostalAddressType> optionalAddress = Optional.empty();
    if (MapUtils.isEmpty(map)) {
      return optionalAddress;
    }

    optionalAddress =
        mapToSchemaElement.populateStringElement(
            map,
            CITY,
            optionalAddress,
            (valueToPopulate, postalAddress) -> postalAddress.setCity(valueToPopulate));

    optionalAddress =
        mapToSchemaElement.populateStringElement(
            map,
            COUNTRY,
            optionalAddress,
            (valueToPopulate, postalAddress) -> postalAddress.setCountry(valueToPopulate));

    optionalAddress =
        mapToSchemaElement.populateStringElement(
            map,
            POSTAL_CODE,
            optionalAddress,
            (valueToPopulate, postalAddress) -> postalAddress.setPostalCode(valueToPopulate));

    optionalAddress =
        mapToSchemaElement.populateStringElement(
            map,
            STATE_OR_PROVINCE,
            optionalAddress,
            (valueToPopulate, postalAddress) -> postalAddress.setStateOrProvince(valueToPopulate));

    optionalAddress =
        mapToSchemaElement.populateStringElement(
            map,
            STREET,
            optionalAddress,
            (valueToPopulate, postalAddress) -> postalAddress.setStreet(valueToPopulate));

    optionalAddress =
        mapToSchemaElement.populateStringElement(
            map,
            STREET_NUMBER,
            optionalAddress,
            (valueToPopulate, postalAddress) -> postalAddress.setStreetNumber(valueToPopulate));

    return optionalAddress;
  }
  public void preUpdateServiceResourceByGuid(String guid, RangerServiceResource resource)
      throws Exception {
    if (StringUtils.isBlank(resource.getServiceName())
        || MapUtils.isEmpty(resource.getResourceElements())) {
      throw new Exception("No serviceName or resource in RangerServiceResource");
    }

    RangerServiceResource existing = tagStore.getServiceResourceByGuid(guid);
    if (existing == null) {
      throw new Exception("Attempt to update nonexistent resource, guid=" + guid);
    }

    RangerServiceResourceSignature serializer = new RangerServiceResourceSignature(resource);

    resource.setId(existing.getId());
    resource.setGuid(guid);
    resource.setResourceSignature(serializer.getSignature());
  }
示例#14
0
  @TraceCall
  @Override
  public Record getPageNoThrow(Context ctx, long pageId) {
    String sql =
        new SQLBuilder.Select()
            .select(StringUtils2.splitArray(BASIC_COLS, ",", true))
            .from(pageTable)
            .where("destroyed_time=0 AND page_id = ${v(page_id)}", "page_id", pageId)
            .toString();

    SQLExecutor se = getSqlExecutor();
    Record pageRec = se.executeRecord(sql, null);
    if (MapUtils.isEmpty(pageRec)) return null;

    attachBasicInfo(ctx, pageRec);
    attachDetailInfo(ctx, pageRec);
    return pageRec;
  }
  public RangerServiceResource preCreateServiceResource(RangerServiceResource resource)
      throws Exception {
    RangerServiceResource ret = null;

    if (StringUtils.isBlank(resource.getServiceName())
        || MapUtils.isEmpty(resource.getResourceElements())) {
      throw new Exception("No serviceName or resource in RangerServiceResource");
    }

    String guid = resource.getGuid();
    if (!StringUtils.isBlank(guid)) {
      ret = tagStore.getServiceResourceByGuid(guid);
    }

    RangerServiceResourceSignature serializer = new RangerServiceResourceSignature(resource);

    resource.setResourceSignature(serializer.getSignature());

    return ret;
  }
 @Override
 public String convert(final Map<Integer, String> row, final Long sequenceId) {
   String result = EMPTY_STRING;
   if (!MapUtils.isEmpty(row)) {
     final StringBuilder builder = new StringBuilder();
     int copyIdx = 0;
     int idx = impexRow.indexOf(BRACKET_START);
     while (idx > -1) {
       final int endIdx = impexRow.indexOf(BRACKET_END, idx);
       if (endIdx < 0) {
         throw new SystemException("Invalid row syntax [brackets not closed]: " + impexRow);
       }
       builder.append(impexRow.substring(copyIdx, idx));
       if (impexRow.charAt(idx + 1) == SEQUENCE_CHAR) {
         builder.append(sequenceId);
       } else {
         final boolean mandatory = impexRow.charAt(idx + 1) == PLUS_CHAR;
         Integer mapIdx = null;
         try {
           mapIdx = Integer.valueOf(impexRow.substring(mandatory ? idx + 2 : idx + 1, endIdx));
         } catch (final NumberFormatException e) {
           throw new SystemException("Invalid row syntax [invalid column number]: " + impexRow, e);
         }
         final String colValue = row.get(mapIdx);
         if (mandatory && StringUtils.isBlank(colValue)) {
           throw new IllegalArgumentException("Missing value for " + mapIdx);
         }
         if (colValue != null) {
           builder.append(colValue);
         }
       }
       copyIdx = endIdx + 1;
       idx = impexRow.indexOf(BRACKET_START, endIdx);
     }
     if (copyIdx < impexRow.length()) {
       builder.append(impexRow.substring(copyIdx));
     }
     result = builder.toString();
   }
   return escapeQuotes(result);
 }
  @Override
  public void invalidArgumentSecondaryTypeIds(String repositoryId, Properties properties) {
    if (properties == null) return;
    Map<String, PropertyData<?>> map = properties.getProperties();
    if (MapUtils.isEmpty(map)) return;

    List<String> results = new ArrayList<String>();
    PropertyData<?> ids = map.get(PropertyIds.SECONDARY_OBJECT_TYPE_IDS);
    if (ids == null || CollectionUtils.isEmpty(ids.getValues())) return;
    for (Object _id : ids.getValues()) {
      String id = (String) _id;
      TypeDefinitionContainer tdc = typeManager.getTypeById(repositoryId, id);
      if (tdc == null) {
        results.add(id);
      }
    }

    if (CollectionUtils.isNotEmpty(results)) {
      String msg =
          "Invalid cmis:SecondaryObjectTypeIds are provided:" + StringUtils.join(results, ",");
      invalidArgument(msg);
    }
  }
示例#18
0
  protected List<RoleMember> getPrimaryRoleMembers(
      Role role, Map<String, String> qualification, DateTime asOfDate, boolean isActiveOnly) {
    // define the return value
    List<RoleMember> primaryRoleMembers = new ArrayList<RoleMember>();

    if (role != null) {
      RoleTypeService roleTypeService = getRoleTypeService(role);
      // use predicate based filtering only on non-derived role.
      if (roleTypeService == null || !roleTypeService.isDerivedRoleType()) {
        List<Predicate> predicates = new ArrayList<Predicate>();
        predicates.add(equal(KimConstants.PrimaryKeyConstants.SUB_ROLE_ID, role.getId()));
        if (isActiveOnly) {
          predicates.add(
              or(isNull("activeFromDateValue"), lessThanOrEqual("activeFromDateValue", asOfDate)));
          predicates.add(
              or(isNull("activeToDateValue"), greaterThan("activeToDateValue", asOfDate)));
        }

        // LookupCustomizer<RoleMemberBo> lookupCustomizer = builder.build();
        // guard for default type roles
        if (roleTypeService != null) {
          if (MapUtils.isEmpty(qualification)) {
            primaryRoleMembers =
                getRoleService()
                    .findRoleMembers(
                        QueryByCriteria.Builder.fromPredicates(
                            predicates.toArray(new Predicate[predicates.size()])))
                    .getResults();
          } else {
            // get the keys (name) of the qualifiers needed for membership in this role
            List<String> attributesForExactMatch = roleTypeService.getQualifiersForExactMatch();
            if (CollectionUtils.isNotEmpty(attributesForExactMatch)) {
              if (attributesForExactMatch.size() <= 1) {
                for (Map.Entry<String, String> qualificationEntry : qualification.entrySet()) {
                  // do not add a qualification predicate for an attribute unless it is required for
                  // matching

                  if (attributesForExactMatch.contains(qualificationEntry.getKey())) {
                    predicates.add(
                        equal(
                            "attributes[" + qualificationEntry.getKey() + "]",
                            qualificationEntry.getValue()));
                  }
                }
                primaryRoleMembers =
                    getRoleService()
                        .findRoleMembers(
                            QueryByCriteria.Builder.fromPredicates(
                                predicates.toArray(new Predicate[predicates.size()])))
                        .getResults();

              } else {
                // rice's transformation doesn't work with more than one attribute.
                // here is a terrible hack
                List<RoleMember> intersectedMembers = null;
                for (Map.Entry<String, String> qualificationEntry : qualification.entrySet()) {
                  // do not add a qualification predicate for an attribute unless it is required for
                  // matching

                  if (attributesForExactMatch.contains(qualificationEntry.getKey())) {
                    Predicate attrPredicates =
                        equal(
                            "attributes[" + qualificationEntry.getKey() + "]",
                            qualificationEntry.getValue());
                    Predicate[] tempPredicates =
                        predicates.toArray(new Predicate[predicates.size() + 1]);
                    tempPredicates[predicates.size()] = attrPredicates;
                    List<RoleMember> tempMembers =
                        new ArrayList<RoleMember>(
                            getRoleService()
                                .findRoleMembers(
                                    QueryByCriteria.Builder.fromPredicates(tempPredicates))
                                .getResults());
                    if (intersectedMembers == null) {
                      intersectedMembers = new ArrayList<>();
                      intersectedMembers.addAll(tempMembers);
                    } else {
                      intersectedMembers = intersect(intersectedMembers, tempMembers);
                    }
                  }
                }
                primaryRoleMembers = intersectedMembers;
              }
            }
          }
        }
      } else {
        // for derived roles just add the as-of date and active only flag to a copy of the
        // qualification
        Map<String, String> derivedRoleQualification = new HashMap<String, String>(qualification);
        derivedRoleQualification.put("asOfDate", asOfDate.toString());
        derivedRoleQualification.put("activeOnly", String.valueOf(isActiveOnly));
        List<RoleMembership> derivedRoleMembers =
            roleTypeService.getRoleMembersFromDerivedRole(
                role.getNamespaceCode(), role.getName(), derivedRoleQualification);
        // convert the role memberships into role members
        for (RoleMembership derivedRoleMember : derivedRoleMembers) {
          RoleMember roleMember =
              RoleMember.Builder.create(
                      derivedRoleMember.getRoleId(),
                      derivedRoleMember.getId(),
                      derivedRoleMember.getMemberId(),
                      derivedRoleMember.getType(),
                      null,
                      null,
                      derivedRoleMember.getQualifier(),
                      role.getName(),
                      role.getNamespaceCode())
                  .build();

          primaryRoleMembers.add(roleMember);
        }
      }
    }

    return primaryRoleMembers;
  }
示例#19
0
 /** 判断 Map 是否为空 */
 public static boolean isEmpty(Map<?, ?> map) {
   return MapUtils.isEmpty(map);
 }
  /**
   * 根据前台查询条件 获得标准商品店铺采购统计
   *
   * @param request
   * @param response
   * @param productSearchCondition
   * @return
   */
  @RequestMapping(params = "method=getNormalProductStatByCondition")
  @ResponseBody
  public Object getNormalProductStatByCondition(
      HttpServletRequest request,
      HttpServletResponse response,
      ProductSearchCondition productSearchCondition) {

    try {
      Long shopId = WebUtil.getShopId(request);
      if (shopId == null) throw new Exception("shopId is null!");
      if (productSearchCondition == null
          || productSearchCondition.getNormalProductStatType() == null) {
        return null;
      }

      List<Long> shopIdList = null;
      if (StringUtil.isNotEmpty(productSearchCondition.getShopVersion())
          || productSearchCondition.getProvinceId() != null
          || productSearchCondition.getCityId() != null
          || productSearchCondition.getRegionId() != null) {
        IConfigService configService = ServiceManager.getService(IConfigService.class);

        List<Long> shopVersionIds = new ArrayList<Long>();

        if ("REPAIR_VERSION".equals(productSearchCondition.getShopVersion())) {
          shopVersionIds.add(10000010017531654L);
          shopVersionIds.add(10000010017531655L);
          shopVersionIds.add(10000010039823882L);
        } else if ("WHOLESALER_VERSION".equals(productSearchCondition.getShopVersion())) {
          shopVersionIds.add(10000010017531657L);
          shopVersionIds.add(10000010037193619L);
          shopVersionIds.add(10000010037193620L);
          shopVersionIds.add(10000010017531653L);
        }

        shopIdList =
            configService.getShopByShopVersionAndArea(
                shopVersionIds.toArray(new Long[shopVersionIds.size()]),
                productSearchCondition.getProvinceId(),
                productSearchCondition.getCityId(),
                productSearchCondition.getRegionId());
        if (CollectionUtils.isEmpty(shopIdList)) {
          return null;
        }
      } else {
        shopIdList = new ArrayList<Long>();
        shopIdList.add(StatConstant.EMPTY_SHOP_ID);
      }

      productSearchCondition.setShopId(shopId);
      IProductService productService = ServiceManager.getService(IProductService.class);
      INormalProductStatService normalProductStatService =
          ServiceManager.getService(INormalProductStatService.class);

      Map<Long, NormalProductDTO> normalProductDTOMap =
          productService.getSimpleNormalProductDTO(productSearchCondition);

      if (MapUtils.isEmpty(normalProductDTOMap)) {
        return null;
      }
      Long[] normalProductIds =
          normalProductDTOMap.keySet().toArray(new Long[normalProductDTOMap.keySet().size()]);

      Pager pager = new Pager();
      pager.setRowStart(productSearchCondition.getStart());
      pager.setPageSize(productSearchCondition.getLimit());

      NormalProductStatSearchResult normalProductStatSearchResult =
          normalProductStatService.getStatDateByCondition(
              shopIdList.toArray(new Long[shopIdList.size()]),
              normalProductIds,
              productSearchCondition.getNormalProductStatType(),
              pager,
              normalProductDTOMap);

      return normalProductStatSearchResult;
    } catch (Exception e) {
      LOG.error("normalProductStat.do method=getNormalProductStatByCondition");
      LOG.error(productSearchCondition.toString());
      LOG.error(e.getMessage(), e);
    }
    return null;
  }
示例#21
0
 /**
  * Assert that a Map has entries; that is, it must not be <code>null</code> and must have at least
  * one entry.
  *
  * <pre class="code">Assert.notEmpty(map, "Map must have entries");</pre>
  *
  * @param map the map to check
  * @param message the exception message to use if the assertion fails
  * @throws IllegalArgumentException if the map is <code>null</code> or has no entries
  */
 public static void notEmpty(Map map, String message) {
   if (MapUtils.isEmpty(map)) {
     throw new IllegalArgumentException(message);
   }
 }
  @Override
  public void run() {

    boolean active = true;

    do {
      try {
        Thread.sleep(100);

        while (active) {

          // take coincidences from buffer
          List<PartialCoincidenceTO> partialCoincidences =
              this.coincidenceBuffer.poll(30, TimeUnit.SECONDS);

          // not has coincidences
          if (CollectionUtils.isEmpty(partialCoincidences)
              && MapUtils.isEmpty(this.coincidenceMap)) {
            active = super.isActive();
            Thread.sleep(100);
            continue;
          }

          if (MapUtils.isNotEmpty(this.coincidenceMap)) {
            // consume jingle segment
            for (CoincidenceTO coincidenceTO : this.coincidenceMap.values()) {
              LOGGER.info(
                  "Jingle: {} has {} segments to match",
                  coincidenceTO.getJingleName(),
                  coincidenceTO.getJingleSegments());
              coincidenceTO.consumeJingleSegment();
            }
          }

          LOGGER.info("Has {} coincidences to process...", partialCoincidences.size());

          for (PartialCoincidenceTO partialCoincidenceTO : partialCoincidences) {

            // check if coincidence is into current coincidences map
            boolean hasPreviousCoincidence =
                this.coincidenceMap.containsKey(partialCoincidenceTO.getJingleName());

            if (hasPreviousCoincidence) {

              // take previous coincidence
              CoincidenceTO previousCoincidenceTO =
                  this.coincidenceMap.get(partialCoincidenceTO.getJingleName());

              // add match seconds to previous coincidence
              BigDecimal totalSeconds =
                  MathUtils.sum(
                      previousCoincidenceTO.getTotalSeconds(),
                      partialCoincidenceTO.getMatchSeconds());
              previousCoincidenceTO.setTotalSeconds(totalSeconds);

              // put updated coincidence
              this.coincidenceMap.put(previousCoincidenceTO.getJingleName(), previousCoincidenceTO);

              this.LOGGER.info(
                  "Update coincidence with name {} total match seconds {}",
                  partialCoincidenceTO.getJingleName(),
                  totalSeconds);

            } else {

              CoincidenceTO coincidenceTO = new CoincidenceTO(partialCoincidenceTO);

              // add first coincidence into current coincidences
              // map
              this.coincidenceMap.put(partialCoincidenceTO.getJingleName(), coincidenceTO);

              this.LOGGER.info(
                  "Save new coincidence with name {}", partialCoincidenceTO.getJingleName());
            }
          }

          if (MapUtils.isNotEmpty(this.coincidenceMap)) {
            // process finalized coincidences
            Iterator<CoincidenceTO> iterator = this.coincidenceMap.values().iterator();
            while (iterator.hasNext()) {
              CoincidenceTO coincidenceTO = iterator.next();
              if (coincidenceTO.getJingleSegments() == 0) {
                this.processCoincidence(coincidenceTO);
                // remove processed coincidence
                iterator.remove();
              }
            }
          }
        }

        active = super.isActive();

      } catch (InterruptedException e1) {
        LOGGER.warn("InterruptedException for radio {}", radioCode);
      } catch (Exception exception) {
        LOGGER.error("Unexpected exception", exception);
      }

      try {
        Thread.sleep(5000);
      } catch (InterruptedException e) {
      }

      active = super.isActive();

    } while (active);

    // mark as disconnected
    super.disconnect();
  }