Esempio n. 1
0
 @Test
 public void getMovieById() {
   Movie movie = _movieService.getMovieById(1548); // Star Wars
   Set<Tag> tags = movie.getTags();
   assertNotNull("Tag set is unexpectedly null", tags);
   assertEquals("Number of tags", 5, tags.size());
   Set<MovieCrewPerson> movieCrewPersons = movie.getMovieCrewPersons();
   assertNotNull("MovieCrewPerson set is unexpectedly null", movieCrewPersons);
   assertEquals("Number of crew persons", 3, movieCrewPersons.size());
   Set<MovieOscar> movieOscars = movie.getMovieOscars();
   assertNotNull("MovieOscar set is unexpectedly null", movieOscars);
   assertEquals("Number of oscars", 4, movieOscars.size());
   Set<MovieTyler> movieTylers = movie.getMovieTylers();
   assertTrue("MovieTyler set unexpectedly not empty", CollectionUtils.isEmpty(movieTylers));
   Set<ListMovie> listMovies = movie.getListMovies();
   assertNotNull("ListMovie set unexpectedly null", listMovies);
   assertEquals("Number of lists", 1, listMovies.size());
   Set<MovieLink> movieLinks = movie.getMovieLinks();
   assertTrue("Movie-links-from set unexpectedly not empty", CollectionUtils.isEmpty(movieLinks));
   Set<MovieSequenceMovie> sequenceMovies = movie.getMovieSequenceMovies();
   assertNotNull("MovieSequenceMovie set is unexpectedly null", sequenceMovies);
   assertEquals("Number of sequences", 2, sequenceMovies.size());
   Movie parent = movie.getParent();
   assertNull("Parent movie unexpectedly not null", parent);
   Set<Movie> children = movie.getChildren();
   assertTrue("Child movies set unexpectedly not empty", CollectionUtils.isEmpty(children));
 }
  public int getItemCountInUncloseOrders(long userId, int itemId) {
    List<OrderItemsModel> orderItems = orderItemsDAO.getListByUserIdAndItemId(userId, itemId);
    if (org.apache.commons.collections.CollectionUtils.isEmpty(orderItems)) {
      return 0;
    }

    Set<Long> orderIds = new HashSet<>();
    for (OrderItemsModel orderItem : orderItems) {
      orderIds.add(orderItem.getOrderid());
    }

    if (org.apache.commons.collections.CollectionUtils.isEmpty(orderIds)) {
      return 0;
    }

    List<OrdersModel> orders = ordersDAO.getsByIds(orderIds);
    Map<Long, OrdersModel> ordersMap = new HashMap<>();
    for (OrdersModel order : orders) {
      ordersMap.put(order.getId(), order);
    }

    int itemCount = 0;
    for (OrderItemsModel orderItem : orderItems) {
      OrdersModel ordersModel = ordersMap.get(orderItem.getOrderid());
      if (ordersModel == null) {
        continue;
      }
      if (ordersModel.getStatus() != OrdersModel.STATUS_CLOSED) {
        itemCount += orderItem.getQuantity();
      }
    }
    return itemCount;
  }
  @RequestMapping(value = "/productDetails.do", method = RequestMethod.GET)
  public String viewProductDetails(
      @RequestParam(value = "productId", required = true) final Long productId, ModelMap modelMap) {
    Product product = productService.getProductDetails(productId);

    List<String> models = new ArrayList<String>();

    models.add(product.getModel());

    List<com.ombillah.ecom4j.remix.domain.Products.Product> products =
        remixService.getRemixProducts(models);

    if (CollectionUtils.isEmpty(products)) {
      // this is for demonstration only to display a similar result!
      products =
          remixService.getProductOfCategory(
              product.getMake(), product.getCategory().getCategoryId());
    }

    if (!CollectionUtils.isEmpty(products)) {
      List<String> skus = new ArrayList<String>();
      skus.add(Integer.toString(products.get(0).getSku()));
      List<Review> reviews = remixService.getRemixReviews(skus);

      modelMap.put("remixProduct", products.get(0));
      modelMap.put("reviews", reviews);
    }

    return "productDetails";
  }
Esempio n. 4
0
 private void deleteJsonJobs(ApplicationInfo appInfo, List<CIJob> selectedJobs)
     throws PhrescoException {
   try {
     if (CollectionUtils.isEmpty(selectedJobs)) {
       return;
     }
     Gson gson = new Gson();
     List<CIJob> jobs = getJobs(appInfo);
     if (CollectionUtils.isEmpty(jobs)) {
       return;
     }
     // all values
     Iterator<CIJob> iterator = jobs.iterator();
     // deletable values
     for (CIJob selectedInfo : selectedJobs) {
       while (iterator.hasNext()) {
         CIJob itrCiJob = iterator.next();
         if (itrCiJob.getName().equals(selectedInfo.getName())) {
           iterator.remove();
           break;
         }
       }
     }
     writeJsonJobs(appInfo, jobs, CI_CREATE_NEW_JOBS);
   } catch (Exception e) {
     throw new PhrescoException(e);
   }
 }
  /**
   * 重置订单优惠信息(主要用于京东订单)
   *
   * @param originalOrderList
   */
  public void resetDiscountInfo(List<OriginalOrder> originalOrderList) {
    if (CollectionUtils.isEmpty(originalOrderList)) {
      return;
    }

    for (OriginalOrder originalOrder : originalOrderList) {
      originalOrder.setDiscountFee(getDiscountFee(originalOrder.getPromotionInfoList()));
      originalOrder.setSelfDiscountFee(getSelfDiscountFee(originalOrder.getPromotionInfoList()));

      if (CollectionUtils.isEmpty(originalOrder.getOriginalOrderItemList())) {
        continue;
      }

      Money totalPayableFee = getTotalPayableFee(originalOrder);

      for (OriginalOrderItem originalOrderItem : originalOrder.getOriginalOrderItemList()) {
        originalOrderItem.setPartMjzDiscount(
            getItemMjzDiscountFee(
                originalOrderItem.getPayableFee(),
                totalPayableFee,
                originalOrder.getDiscountFee()));
        originalOrderItem.setSelfPartMjzDiscount(
            getItemMjzDiscountFee(
                originalOrderItem.getPayableFee(),
                totalPayableFee,
                originalOrder.getSelfDiscountFee()));
        saveOriginalOrderItem(originalOrderItem);
      }

      saveOriginalOrder(originalOrder);
    }
  }
  private void getCustomerOptions(
      Model model, Customer customer, MerchantStore store, Language language) throws Exception {

    Map<Long, CustomerOption> options = new HashMap<Long, CustomerOption>();
    // get options
    List<CustomerOptionSet> optionSet = customerOptionSetService.listByStore(store, language);
    if (!CollectionUtils.isEmpty(optionSet)) {

      CustomerOptionPopulator optionPopulator = new CustomerOptionPopulator();

      Set<CustomerAttribute> customerAttributes = customer.getAttributes();

      for (CustomerOptionSet optSet : optionSet) {

        com.wms.core.business.customer.model.attribute.CustomerOption custOption =
            optSet.getCustomerOption();
        if (!custOption.isActive()) {
          continue;
        }
        CustomerOption customerOption = options.get(custOption.getId());

        optionPopulator.setOptionSet(optSet);

        if (customerOption == null) {
          customerOption = new CustomerOption();
          customerOption.setId(custOption.getId());
          customerOption.setType(custOption.getCustomerOptionType());
          customerOption.setName(custOption.getDescriptionsSettoList().get(0).getName());
        }

        optionPopulator.populate(custOption, customerOption, store, language);
        options.put(customerOption.getId(), customerOption);

        if (!CollectionUtils.isEmpty(customerAttributes)) {
          for (CustomerAttribute customerAttribute : customerAttributes) {
            if (customerAttribute.getCustomerOption().getId().longValue()
                == customerOption.getId()) {
              CustomerOptionValue selectedValue = new CustomerOptionValue();
              com.wms.core.business.customer.model.attribute.CustomerOptionValue attributeValue =
                  customerAttribute.getCustomerOptionValue();
              selectedValue.setId(attributeValue.getId());
              CustomerOptionValueDescription optValue =
                  attributeValue.getDescriptionsSettoList().get(0);
              selectedValue.setName(optValue.getName());
              customerOption.setDefaultValue(selectedValue);
              if (customerOption.getType().equalsIgnoreCase(CustomerOptionType.Text.name())) {
                selectedValue.setName(customerAttribute.getTextValue());
              }
            }
          }
        }
      }
    }

    model.addAttribute("options", options.values());
  }
  /**
   * Can the user read from this CategoryOptionGroupSet (COGS)?
   *
   * <p>If the COGS is null, then the user must have no dimension constraints. (In other words, the
   * user must be able to read across all category option groups.)
   *
   * <p>If the COGS is not null, then the user must be able to read at least one category option
   * group from the category option group set.
   *
   * @param cogs The category option group set to test
   * @return true if user can read at least one category option group.
   */
  private boolean canReadCOGS(User user, CategoryOptionGroupSet cogs) {
    if (cogs == null) {
      UserCredentials userCredentials = user.getUserCredentials();

      return CollectionUtils.isEmpty(userCredentials.getCogsDimensionConstraints())
          && CollectionUtils.isEmpty(userCredentials.getCatDimensionConstraints());
    }

    return !CollectionUtils.isEmpty(categoryService.getCategoryOptionGroups(cogs));
  }
  private <T> void constraintChoices(
      PropertyDefinition<T> definition, PropertyData<T> propertyData, String objectId) {
    // Check OpenChoice
    boolean openChoice = (definition.isOpenChoice() == null) ? true : false;
    if (openChoice) return;

    List<T> data = propertyData.getValues();
    // null or blank String value should be permitted within any choice list
    if (CollectionUtils.isEmpty(data)) return;

    List<Choice<T>> choices = definition.getChoices();
    if (CollectionUtils.isEmpty(choices) || CollectionUtils.isEmpty(data)) return;

    boolean included = false;
    if (definition.getCardinality() == Cardinality.SINGLE) {
      T d = data.get(0);

      if (d instanceof String && StringUtils.isBlank((String) d) || d == null) {
        return;
      } else {
        for (Choice<T> choice : choices) {
          List<T> value = choice.getValue();
          T v = value.get(0);
          if (v.equals(d)) {
            included = true;
            break;
          }
        }
      }

    } else if (definition.getCardinality() == Cardinality.MULTI) {
      List<T> values = new ArrayList<T>();
      for (Choice<T> choice : choices) {
        values.addAll(choice.getValue());
      }

      for (T d : data) {
        if (values.contains(d)) {
          included = true;
        } else {
          if (d instanceof String && StringUtils.isBlank((String) d) || d == null) {
            included = true;
          } else {
            included = false;
            break;
          }
        }
      }
    }

    if (!included) {
      constraint(objectId, propertyData.getId() + " property value must be one of choices");
    }
  }
 @SuppressWarnings("unchecked")
 @Override
 public void visit(PlainSelect select) {
   if (!CollectionUtils.isEmpty(select.getGroupByColumnReferences())
       || !CollectionUtils.isEmpty(select.getJoins())) {
     isSimple = false;
   } else {
     select.getFromItem().accept(this);
     for (SelectItem item : (List<SelectItem>) select.getSelectItems()) {
       item.accept(this);
     }
   }
 }
  private <T> List<T> flattenChoiceValues(List<Choice<T>> choices) {
    if (CollectionUtils.isEmpty(choices)) return null;

    List<T> result = new ArrayList<T>();
    for (Choice<T> choice : choices) {
      List<T> value = choice.getValue();
      if (CollectionUtils.isEmpty(value)) continue;
      for (T v : value) {
        result.add(v);
      }

      result.addAll(flattenChoiceValues(choice.getChoice()));
    }
    return result;
  }
  /**
   * Subtracts collection b from a (a-b) in safe manner. Following rules apply:
   *
   * <p>- If collection a is <code>null</code> or empty, then result is empty list<br>
   * - If collection b is <code>null</code> or empty, then result is a new list with same content as
   * a <br>
   * - If both collections have at least one element, results is {@link
   * CollectionUtils#subtract(Collection, Collection)}.<br>
   *
   * @param <E> Element types in collections.
   * @param a collection to subtract from
   * @param b collection to use in subtract
   * @return subtraction result
   * @see {@link CollectionUtils#subtract(Collection, Collection)}.
   */
  @SuppressWarnings("unchecked")
  public static <E> Collection<E> subtractSafe(Collection<E> a, Collection<E> b) {
    // if a is empty then return empty
    if (CollectionUtils.isEmpty(a)) {
      return Collections.emptyList();
    }

    // if b is empty, then return complete a as new list
    if (CollectionUtils.isEmpty(b)) {
      return new ArrayList<>(a);
    }

    // otherwise perform subtract
    return CollectionUtils.subtract(a, b);
  }
  /**
   * 保存指定状态的原始订单至数据库
   *
   * @param originalOrderList
   */
  public void saveOriginalOrders(List<OriginalOrder> originalOrderList) {

    if (CollectionUtils.isEmpty(originalOrderList)) {
      return;
    }

    for (OriginalOrder originalOrder : originalOrderList) {

      if (!(StringUtils.equalsIgnoreCase(
              originalOrder.getStatus(), OriginalOrderStatus.WAIT_SELLER_SEND_GOODS.toString())
          || StringUtils.equalsIgnoreCase(
              originalOrder.getStatus(), OriginalOrderStatus.WAIT_BUYER_CONFIRM_GOODS.toString())
          || StringUtils.equalsIgnoreCase(
              originalOrder.getStatus(), OriginalOrderStatus.TRADE_FINISHED.toString()))) {
        continue;
      }
      // 保存原始订单
      saveOriginalOrder(originalOrder);
      for (OriginalOrderItem originalOrderItem : originalOrder.getOriginalOrderItemList()) {
        // 保存原始订单项
        originalOrderItem.setOriginalOrderId(originalOrder.getId());
        saveOriginalOrderItem(originalOrderItem);
      }
      for (PromotionInfo promotionInfo : originalOrder.getPromotionInfoList()) {
        // 保存订单优惠记录
        promotionInfo.setOriginalOrderId(originalOrder.getId());
        savePromotionInfo(promotionInfo);
      }
    }
  }
Esempio n. 13
0
  @Override
  public void removeSubcommunity(
      Context context, Community parentCommunity, Community childCommunity)
      throws SQLException, AuthorizeException, IOException {
    // Check authorisation
    authorizeService.authorizeAction(context, parentCommunity, Constants.REMOVE);

    ArrayList<String> removedIdentifiers = getIdentifiers(context, childCommunity);
    String removedHandle = childCommunity.getHandle();
    UUID removedId = childCommunity.getID();

    parentCommunity.removeSubCommunity(childCommunity);
    childCommunity.getParentCommunities().remove(parentCommunity);
    if (CollectionUtils.isEmpty(childCommunity.getParentCommunities())) {
      rawDelete(context, childCommunity);
    }
    log.info(
        LogManager.getHeader(
            context,
            "remove_subcommunity",
            "parent_comm_id="
                + parentCommunity.getID()
                + ",child_comm_id="
                + childCommunity.getID()));

    context.addEvent(
        new Event(
            Event.REMOVE,
            Constants.COMMUNITY,
            parentCommunity.getID(),
            Constants.COMMUNITY,
            removedId,
            removedHandle,
            removedIdentifiers));
  }
Esempio n. 14
0
  @Override
  public Map<String, List<Application>> getInactiveAgents(
      String applicationName, int durationDays) {
    if (applicationName == null) {
      throw new NullPointerException("applicationName must not be null");
    }
    if (durationDays < 30) {
      throw new IllegalArgumentException("duration may not be less than 30 days");
    }
    if (durationDays > 180) {
      throw new IllegalArgumentException("duration may not be greater than 180 days");
    }
    List<String> agentIds = this.applicationIndexDao.selectAgentIds(applicationName);
    if (CollectionUtils.isEmpty(agentIds)) {
      return Collections.emptyMap();
    }

    final long toTimestamp = System.currentTimeMillis();
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, durationDays * -1);
    final long fromTimestamp = cal.getTimeInMillis();
    Range queryRange = new Range(fromTimestamp, toTimestamp);

    Map<String, List<Application>> agentIdMap = this.getAgentIdMap();

    Map<String, List<Application>> inactiveAgentMap = new TreeMap<>(Ordering.usingToString());
    for (String agentId : agentIds) {
      boolean dataExists = this.agentStatDao.agentStatExists(agentId, queryRange);
      if (!dataExists) {
        List<Application> applications = agentIdMap.get(agentId);
        inactiveAgentMap.put(agentId, applications);
      }
    }
    return inactiveAgentMap;
  }
 @Override
 public List<String> handleSentinelConfig(
     String masterName, String host, int port, int sentinelPort) {
   List<InstanceConfig> instanceConfigList =
       instanceConfigDao.getByType(ConstUtils.CACHE_REDIS_SENTINEL);
   if (CollectionUtils.isEmpty(instanceConfigList)) {
     return Collections.emptyList();
   }
   List<String> configs = new ArrayList<String>();
   for (InstanceConfig instanceConfig : instanceConfigList) {
     if (!instanceConfig.isEffective()) {
       continue;
     }
     String configKey = instanceConfig.getConfigKey();
     String configValue = instanceConfig.getConfigValue();
     if (StringUtils.isBlank(configValue)) {
       configValue = SPECIAL_EMPTY_STR;
     }
     if (RedisSentinelConfigEnum.PORT.getKey().equals(configKey)) {
       configValue = String.format(configValue, sentinelPort);
     } else if (RedisSentinelConfigEnum.MONITOR.getKey().equals(configKey)) {
       configValue = String.format(configValue, masterName, host, port);
     } else if (RedisSentinelConfigEnum.DOWN_AFTER_MILLISECONDS.getKey().equals(configKey)
         || RedisSentinelConfigEnum.FAILOVER_TIMEOUT.getKey().equals(configKey)
         || RedisSentinelConfigEnum.PARALLEL_SYNCS.getKey().equals(configKey)) {
       configValue = String.format(configValue, masterName);
     } else if (RedisConfigEnum.DIR.getKey().equals(configKey)) {
       configValue = MachineProtocol.DATA_DIR;
     }
     configs.add(combineConfigKeyValue(configKey, configValue));
   }
   return configs;
 }
 private void checkQueryFour(Query query) {
   Assert.assertEquals(query.getId(), "query-4");
   Assert.assertEquals(
       query.getBody(),
       "{'body' : 'query-4'},{'body' : 'query-4-fragment'},{'body' : 'query-4-continue'}");
   Assert.assertTrue(CollectionUtils.isEmpty(query.getCases()));
 }
 @Override
 public List<MerchantRouter> batchSelect(List<Long> idList) {
   if (CollectionUtils.isEmpty(idList)) {
     return new ArrayList<MerchantRouter>();
   }
   return merchantRouterMapper.batchSelect(idList);
 }
 @Override
 public int batchUpdate(List<MerchantRouter> merchantRouterList) {
   if (CollectionUtils.isEmpty(merchantRouterList)) {
     return 0;
   }
   return merchantRouterMapper.batchUpdate(merchantRouterList);
 }
 @Override
 public int batchDelete(List<Long> idList) {
   if (CollectionUtils.isEmpty(idList)) {
     return 0;
   }
   return merchantRouterMapper.batchDelete(idList);
 }
Esempio n. 20
0
  private List<Customer> checkForOnlyBillableCustomers(
      UserCriteria userCriteria, List<Customer> customers) {
    List<Customer> billableCustomers = new ArrayList<Customer>();

    LOGGER.debug("Finding on billable only: " + userCriteria.isOnlyBillableProjects());

    if (userCriteria.isOnlyBillableProjects()) {
      for (Customer customer : customers) {
        List<Project> billableProjects;

        if (userCriteria.isOnlyActiveProjects()) {
          billableProjects = ProjectUtil.getBillableProjects(customer.getActiveProjects());
        } else {
          billableProjects = ProjectUtil.getBillableProjects(customer.getProjects());
        }

        if (!CollectionUtils.isEmpty(billableProjects)) {
          billableCustomers.add(customer);
        }
      }
    } else {
      return customers;
    }

    return billableCustomers;
  }
  protected PeopleFlowBo getPeopleFlowBoByName(String namespaceCode, String name) {
    if (StringUtils.isBlank(namespaceCode)) {
      throw new RiceIllegalArgumentException("namespaceCode was a null or blank value");
    }
    if (StringUtils.isBlank(name)) {
      throw new RiceIllegalArgumentException("name was a null or blank value");
    }

    QueryByCriteria.Builder criteria = QueryByCriteria.Builder.create();
    criteria.setPredicates(
        equal(KewImplConstants.PropertyConstants.NAMESPACE_CODE, namespaceCode),
        equal(KewImplConstants.PropertyConstants.NAME, name));
    Collection<PeopleFlowBo> peopleFlows =
        dataObjectService.findMatching(PeopleFlowBo.class, criteria.build()).getResults();

    if (CollectionUtils.isEmpty(peopleFlows)) {
      return null;
    } else if (peopleFlows.size() > 1) {
      throw new RiceIllegalStateException(
          "Found more than one PeopleFlow with the given namespace code '"
              + namespaceCode
              + "' and name '"
              + name
              + "'");
    }
    return peopleFlows.iterator().next();
  }
 private static final int[] toDocArray(List<Integer> docList) {
   if (CollectionUtils.isEmpty(docList)) return null;
   int[] docArray = new int[docList.size()];
   int i = 0;
   for (Integer docId : docList) docArray[i++] = docId;
   return docArray;
 }
  @Override
  public PropertySerializabilityEvaluator getPropertySerizabilityEvaluator(Object businessObject) {
    PropertySerializabilityEvaluator evaluator = null;

    String docTypeName =
        getDocumentDictionaryService().getMaintenanceDocumentTypeName(businessObject.getClass());
    MaintenanceDocumentEntry maintenanceDocumentEntry =
        getDocumentDictionaryService().getMaintenanceDocumentEntry(docTypeName);

    if (maintenanceDocumentEntry
        instanceof org.kuali.rice.kns.datadictionary.MaintenanceDocumentEntry) {
      List<MaintainableSectionDefinition> maintainableSectionDefinitions =
          ((org.kuali.rice.kns.datadictionary.MaintenanceDocumentEntry) maintenanceDocumentEntry)
              .getMaintainableSections();
      if (CollectionUtils.isEmpty(maintainableSectionDefinitions)) {
        evaluator = new AlwaysTruePropertySerializibilityEvaluator();
      } else {
        evaluator = new MaintenanceDocumentPropertySerializibilityEvaluator();
        evaluator.initializeEvaluatorForDataObject(businessObject);
      }
    } else {
      evaluator = new AlwaysTruePropertySerializibilityEvaluator();
    }

    return evaluator;
  }
 private boolean saveChangeLog(
     AbstractBuild build,
     Launcher launcher,
     BuildListener listener,
     File changelogFile,
     ClearToolLauncher clearToolLauncher,
     VariableResolver<String> variableResolver,
     SaveChangeLogAction saveChangeLogAction,
     String coNormalizedViewName,
     boolean returnValue)
     throws IOException, InterruptedException {
   List<? extends ChangeLogSet.Entry> changelogEntries;
   @SuppressWarnings("unchecked")
   Run prevBuild = build.getPreviousBuild();
   Date lastBuildTime = getBuildTime(prevBuild);
   HistoryAction historyAction = createHistoryAction(variableResolver, clearToolLauncher, build);
   changelogEntries =
       historyAction.getChanges(
           lastBuildTime,
           getViewPath(variableResolver),
           coNormalizedViewName,
           getBranchNames(variableResolver),
           getViewPaths(variableResolver, build, launcher));
   // Save change log
   if (CollectionUtils.isEmpty(changelogEntries)) {
     // no changes
     returnValue = createEmptyChangeLog(changelogFile, listener, "changelog");
   } else {
     saveChangeLogAction.saveChangeLog(changelogFile, changelogEntries);
   }
   return returnValue;
 }
 @Override
 public List<String> handleCommonConfig(int port, int maxMemory) {
   List<InstanceConfig> instanceConfigList = getByType(ConstUtils.CACHE_REDIS_STANDALONE);
   if (CollectionUtils.isEmpty(instanceConfigList)) {
     return Collections.emptyList();
   }
   List<String> configs = new ArrayList<String>();
   for (InstanceConfig instanceConfig : instanceConfigList) {
     // 无效配置过滤
     if (!instanceConfig.isEffective()) {
       continue;
     }
     String configKey = instanceConfig.getConfigKey();
     String configValue = instanceConfig.getConfigValue();
     if (StringUtils.isBlank(configValue)) {
       configValue = SPECIAL_EMPTY_STR;
     }
     if (RedisConfigEnum.MAXMEMORY.getKey().equals(configKey)) {
       configValue = String.format(configValue, maxMemory);
     } else if (RedisConfigEnum.DBFILENAME.getKey().equals(configKey)
         || RedisConfigEnum.APPENDFILENAME.getKey().equals(configKey)
         || RedisConfigEnum.PORT.getKey().equals(configKey)) {
       configValue = String.format(configValue, port);
     } else if (RedisConfigEnum.DIR.getKey().equals(configKey)) {
       configValue = MachineProtocol.DATA_DIR;
     } else if (RedisConfigEnum.AUTO_AOF_REWRITE_PERCENTAGE.getKey().equals(configKey)) {
       // 随机比例 auto-aof-rewrite-percentage
       int percent = 69 + new Random().nextInt(30);
       configValue = String.format(configValue, percent);
     }
     configs.add(combineConfigKeyValue(configKey, configValue));
   }
   return configs;
 }
 private MoveSelector buildMoveSelector(HeuristicConfigPolicy configPolicy) {
   MoveSelector moveSelector;
   SelectionCacheType defaultCacheType = SelectionCacheType.JUST_IN_TIME;
   SelectionOrder defaultSelectionOrder = SelectionOrder.RANDOM;
   if (CollectionUtils.isEmpty(moveSelectorConfigList)) {
     // Default to changeMoveSelector and swapMoveSelector
     UnionMoveSelectorConfig unionMoveSelectorConfig = new UnionMoveSelectorConfig();
     unionMoveSelectorConfig.setMoveSelectorConfigList(
         Arrays.asList(new ChangeMoveSelectorConfig(), new SwapMoveSelectorConfig()));
     moveSelector =
         unionMoveSelectorConfig.buildMoveSelector(
             configPolicy, defaultCacheType, defaultSelectionOrder);
   } else if (moveSelectorConfigList.size() == 1) {
     moveSelector =
         moveSelectorConfigList
             .get(0)
             .buildMoveSelector(configPolicy, defaultCacheType, defaultSelectionOrder);
   } else {
     // TODO moveSelectorConfigList is only a List because of XStream limitations.
     throw new IllegalArgumentException(
         "The moveSelectorConfigList ("
             + moveSelectorConfigList
             + ") must be a singleton or empty. Use a single "
             + UnionMoveSelectorConfig.class
             + " or "
             + CartesianProductMoveSelectorConfig.class
             + " element to nest multiple MoveSelectors.");
   }
   return moveSelector;
 }
Esempio n. 27
0
  @Override
  public void removeCollection(Context context, Community community, Collection collection)
      throws SQLException, AuthorizeException, IOException {
    // Check authorisation
    authorizeService.authorizeAction(context, community, Constants.REMOVE);

    community.removeCollection(collection);
    ArrayList<String> removedIdentifiers = collectionService.getIdentifiers(context, collection);
    String removedHandle = collection.getHandle();
    UUID removedId = collection.getID();

    collection.removeCommunity(community);
    if (CollectionUtils.isEmpty(collection.getCommunities())) {
      collectionService.delete(context, collection);
    }

    log.info(
        LogManager.getHeader(
            context,
            "remove_collection",
            "community_id=" + community.getID() + ",collection_id=" + collection.getID()));

    // Remove any mappings
    context.addEvent(
        new Event(
            Event.REMOVE,
            Constants.COMMUNITY,
            community.getID(),
            Constants.COLLECTION,
            removedId,
            removedHandle,
            removedIdentifiers));
  }
Esempio n. 28
0
  @Override
  public List<ObjectData> getAppliedPolicies(
      CallContext callContext, String objectId, String filter, ExtensionsData extension) {
    // //////////////////
    // General Exception
    // //////////////////
    exceptionService.invalidArgumentRequiredString("objectId", objectId);
    Content content = contentService.getContent(objectId);
    exceptionService.objectNotFound(DomainType.OBJECT, content, objectId);
    exceptionService.permissionDenied(
        callContext, PermissionMapping.CAN_GET_APPLIED_POLICIES_OBJECT, content);

    // //////////////////
    // Body of the method
    // //////////////////
    List<Policy> policies = contentService.getAppliedPolicies(objectId, extension);
    List<ObjectData> objects = new ArrayList<ObjectData>();
    if (!CollectionUtils.isEmpty(policies)) {
      for (Policy policy : policies) {
        objects.add(
            compileObjectService.compileObjectData(callContext, policy, filter, true, true, null));
      }
    }
    return objects;
  }
  @Override
  public void run() {
    // clone a copy of the killable tasks
    Set<TaskID> killableTasks = Sets.newHashSet(schedulerState.getKillableTasks());

    if (CollectionUtils.isEmpty(killableTasks)) {
      return;
    }

    Status driverStatus = driverManager.getDriverStatus();
    if (Status.DRIVER_RUNNING != driverStatus) {
      LOGGER.warn("Cannot kill tasks, as driver is not running. Status: {}", driverStatus);
      return;
    }

    for (TaskID taskIdToKill : killableTasks) {
      if (this.schedulerState.getPendingTaskIds().contains(taskIdToKill)) {
        this.schedulerState.removeTask(taskIdToKill);
      } else {
        Status status = this.driverManager.kill(taskIdToKill);
        NodeTask task = schedulerState.getTask(taskIdToKill);
        if (task != null) {
          offerLifeCycleManager.declineOutstandingOffers(task.getHostname());
          this.schedulerState.removeTask(taskIdToKill);
        } else {
          schedulerState.removeTask(taskIdToKill);
          LOGGER.warn("NodeTask with taskId: {} does not exist", taskIdToKill);
        }
        Preconditions.checkState(status == Status.DRIVER_RUNNING);
      }
    }
  }
Esempio n. 30
0
 /**
  * 如果没有设定可更新字段,则认为该对象不支持更新<br>
  * <功能详细描述>
  *
  * @return [参数说明]
  * @return boolean [返回类型说明]
  * @exception throws [异常类型] [异常说明]
  * @see [类、类#方法、类#成员]
  */
 public boolean isUpdateAble() {
   if (CollectionUtils.isEmpty(this.updateAblePropertyNames)) {
     return false;
   } else {
     return true;
   }
 }