Example usage for org.apache.commons.collections4 MapUtils isEmpty

List of usage examples for org.apache.commons.collections4 MapUtils isEmpty

Introduction

In this page you can find the example usage for org.apache.commons.collections4 MapUtils isEmpty.

Prototype

public static boolean isEmpty(final Map<?, ?> map) 

Source Link

Document

Null-safe check if the specified map is empty.

Usage

From source file:fr.landel.utils.commons.StringUtils.java

/**
 * Injects all arguments in the specified char sequence. The arguments are
 * injected by replacement of keys between braces. To exclude keys, just
 * double braces (like {{key}} will return {key}). If some keys aren't
 * found, they are ignored./*  www .j  av a 2s  .c om*/
 * 
 * <p>
 * precondition: {@code charSequence} cannot be {@code null}
 * </p>
 * 
 * <pre>
 * StringUtils.injectKeys(Pair.of("${", "}"), Pair.of("${{", "}}"), "", Collections.singletonMap("key", "test"));
 * // =&gt; ""
 * 
 * StringUtils.injectKeys(Pair.of("${", "}"), Pair.of("${{", "}}"), "I'll go to the ${where} this {when}",
 *         MapUtils2.newHashMap(Pair.of("where", "beach"), Pair.of("when", "afternoon")));
 * // =&gt; "I'll go to the beach this afternoon"
 * 
 * StringUtils.injectKeys(Pair.of("${", "}"), Pair.of("${{", "}}"), "I'll go to ${key}${{key}}${key}",
 *         Collections.singletonMap("key", "beach"));
 * // =&gt; "I'll go to beach${key}beach"
 * </pre>
 * 
 * @param include
 *            the characters that surround the property key to replace
 * @param exclude
 *            the characters that surround the property key to exclude of
 *            replacement
 * @param charSequence
 *            the input char sequence
 * @param arguments
 *            the map of pairs to inject
 * @return the result with replacements
 */
public static String injectKeys(final Pair<String, String> include, final Pair<String, String> exclude,
        final CharSequence charSequence, final Map<String, Object> arguments) {
    if (charSequence == null) {
        throw new IllegalArgumentException("The input char sequence cannot be null");
    } else if (isEmpty(charSequence) || MapUtils.isEmpty(arguments)) {
        return charSequence.toString();
    }

    return injectKeys(include, exclude, charSequence,
            arguments.entrySet().toArray(CastUtils.cast(new Map.Entry[arguments.size()])));
}

From source file:org.aerogear.digger.client.services.BuildService.java

/**
 *
 * @param jenkinsServer Jenkins server client
 * @param jobName name of the job//  ww w . j  a va  2 s  .  c o  m
 * @param params build parameters to override defaults in the job
 * @return The QueueReference
 * @throws IOException if connection problems occur during connecting to Jenkins
 * @throws InterruptedException if a problem occurs during sleeping between checks
 */
public BuildTriggerStatus triggerBuild(JenkinsServer jenkinsServer, String jobName, Map<String, String> params)
        throws IOException, InterruptedException {
    LOG.debug("Getting QueueReference for Job '{}'", jobName);
    QueueReference queueReference = null;
    JobWithDetails job = jenkinsServer.getJob(jobName);
    if (job == null) {
        LOG.debug("Unable to find job for name '{}'", jobName);
        throw new IllegalArgumentException("Unable to find job for name '" + jobName + "'");
    } else {
        queueReference = MapUtils.isEmpty(params) ? job.build() : job.build(params);
        if (queueReference == null) {
            // this is probably an implementation problem we have here
            LOG.debug("Queue reference cannot be null!");
            throw new IllegalStateException("Queue reference cannot be null!");
        }
        LOG.debug("Queue item reference: {}", queueReference.getQueueItemUrlPart());
        return new BuildTriggerStatus(BuildTriggerStatus.State.TRIGGERED, job.getNextBuildNumber(),
                queueReference);
    }
}

From source file:org.apache.samza.container.grouper.task.GroupByContainerIds.java

/**
 * {@inheritDoc}//www. ja va  2  s .  c  o m
 *
 * When the are `t` tasks and `p` processors, where t &lt;= p, a fair task distribution should ideally assign
 * (t / p) tasks to each processor. In addition to guaranteeing a fair distribution, this {@link TaskNameGrouper}
 * implementation generates a locationId aware task assignment to processors where it makes best efforts in assigning
 * the tasks to processors with the same locality.
 *
 * Task assignment to processors is accomplished through the following two phases:
 *
 * 1. In the first phase, each task(T) is assigned to a processor(P) that satisfies the following constraints:
 *    A. The processor(P) should have the same locality of the task(T).
 *    B. Number of tasks already assigned to the processor should be less than the (number of tasks / number of processors).
 *
 * 2. Each unassigned task from phase 1 are then mapped to any processor with task count less than the
 * (number of tasks / number of processors). When no such processor exists, then the unassigned
 * task is mapped to any processor from available processors in a round robin fashion.
 */
@Override
public Set<ContainerModel> group(Set<TaskModel> taskModels, GrouperMetadata grouperMetadata) {
    // Validate that the task models are not empty.
    Map<TaskName, LocationId> taskLocality = grouperMetadata.getTaskLocality();
    Preconditions.checkArgument(!taskModels.isEmpty(),
            "No tasks found. Likely due to no input partitions. Can't run a job with no tasks.");

    // Invoke the default grouper when the processor locality does not exist.
    if (MapUtils.isEmpty(grouperMetadata.getProcessorLocality())) {
        LOG.info("ProcessorLocality is empty. Generating with the default group method.");
        return group(taskModels, new ArrayList<>());
    }

    Map<String, LocationId> processorLocality = new TreeMap<>(grouperMetadata.getProcessorLocality());
    /**
     * When there're more task models than processors then choose the lexicographically least `x` processors(where x = tasks.size()).
     */
    if (processorLocality.size() > taskModels.size()) {
        processorLocality = processorLocality.entrySet().stream().limit(taskModels.size())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }

    Map<LocationId, List<String>> locationIdToProcessors = new HashMap<>();
    Map<String, TaskGroup> processorIdToTaskGroup = new HashMap<>();

    // Generate the {@see LocationId} to processors mapping and processorId to {@see TaskGroup} mapping.
    processorLocality.forEach((processorId, locationId) -> {
        List<String> processorIds = locationIdToProcessors.getOrDefault(locationId, new ArrayList<>());
        processorIds.add(processorId);
        locationIdToProcessors.put(locationId, processorIds);
        processorIdToTaskGroup.put(processorId, new TaskGroup(processorId, new ArrayList<>()));
    });

    int numTasksPerProcessor = taskModels.size() / processorLocality.size();
    Set<TaskName> assignedTasks = new HashSet<>();

    /**
     * A processor is considered under-assigned when number of tasks assigned to it is less than
     * (number of tasks / number of processors).
     * Map the tasks to the under-assigned processors with same locality.
     */
    for (TaskModel taskModel : taskModels) {
        LocationId taskLocationId = taskLocality.get(taskModel.getTaskName());
        if (taskLocationId != null) {
            List<String> processorIds = locationIdToProcessors.getOrDefault(taskLocationId, new ArrayList<>());
            for (String processorId : processorIds) {
                TaskGroup taskGroup = processorIdToTaskGroup.get(processorId);
                if (taskGroup.size() < numTasksPerProcessor) {
                    taskGroup.addTaskName(taskModel.getTaskName().getTaskName());
                    assignedTasks.add(taskModel.getTaskName());
                    break;
                }
            }
        }
    }

    /**
     * In some scenarios, the task either might not have any previous locality or might not have any
     * processor that maps to its previous locality. This cyclic processorId's iterator helps us in
     * those scenarios to assign the processorIds to those kind of tasks in a round robin fashion.
     */
    Iterator<String> processorIdsCyclicIterator = Iterators.cycle(processorLocality.keySet());

    // Order the taskGroups to choose a task group in a deterministic fashion for unassigned tasks.
    List<TaskGroup> taskGroups = new ArrayList<>(processorIdToTaskGroup.values());
    taskGroups.sort(Comparator.comparing(TaskGroup::getContainerId));

    /**
     * For the tasks left over from the previous stage, map them to any under-assigned processor.
     * When a under-assigned processor doesn't exist, then map them to any processor from the
     * available processors in a round robin manner.
     */
    for (TaskModel taskModel : taskModels) {
        if (!assignedTasks.contains(taskModel.getTaskName())) {
            Optional<TaskGroup> underAssignedTaskGroup = taskGroups.stream()
                    .filter(taskGroup -> taskGroup.size() < numTasksPerProcessor).findFirst();
            if (underAssignedTaskGroup.isPresent()) {
                underAssignedTaskGroup.get().addTaskName(taskModel.getTaskName().getTaskName());
            } else {
                TaskGroup taskGroup = processorIdToTaskGroup.get(processorIdsCyclicIterator.next());
                taskGroup.addTaskName(taskModel.getTaskName().getTaskName());
            }
            assignedTasks.add(taskModel.getTaskName());
        }
    }

    return TaskGroup.buildContainerModels(taskModels, taskGroups);
}

From source file:org.apereo.openlrs.utils.StatementUtils.java

/**
 * Verifies the statement has all required properties:
 * Actor//from w  w w. ja v a 2  s  .  c om
 * Verb
 * Object
 * 
 * @param propertyMap the map containing the statement properties
 * @return true, if all required properties are present
 */
@SuppressWarnings("unchecked")
public static boolean hasAllRequiredProperties(Map<String, Object> propertyMap) {
    if (MapUtils.isEmpty(propertyMap)) {
        return false;
    }

    if (!propertyMap.containsKey("actor") || !propertyMap.containsKey("verb")
            || !propertyMap.containsKey("object")) {
        return false;
    }

    // Actor
    // check for the required Inverse Functional Identifier
    boolean actorValid = false;
    Map<String, String> actorMap = (Map<String, String>) propertyMap.get("actor");
    String mbox = actorMap.get("mbox");
    if (StringUtils.isNotBlank(mbox)) {
        actorValid = true;
    }

    // Verb
    // check for the required ID
    boolean verbValid = false;
    Map<String, String> verbMap = (Map<String, String>) propertyMap.get("verb");
    if (verbMap.containsKey("id")) {
        verbValid = StringUtils.isNotBlank(verbMap.get("id"));
    }

    // Object
    // check for the required ID
    boolean objectValid = false;
    Map<String, String> objectMap = (Map<String, String>) propertyMap.get("object");
    if (objectMap.containsKey("id")) {
        objectValid = StringUtils.isNotBlank(objectMap.get("id"));
    }

    return actorValid && verbValid && objectValid;
}

From source file:org.axe.util.CollectionUtil.java

/**
 *  Map ?
 */
public static boolean isEmpty(Map<?, ?> map) {
    return MapUtils.isEmpty(map);
}

From source file:org.blocks4j.reconf.client.factory.ConfigurationRepositoryElementFactory.java

private void validate(ConfigurationRepositoryElement arg) {
    if (arg == null) {
        throw new ReConfInitializationError(msg.get("error.internal"));
    }//  w w  w  .  j a  v a 2  s.  c om

    Map<String, String> violations = ConfigurationRepositoryElementValidator.validate(arg);
    if (MapUtils.isEmpty(violations)) {
        return;
    }

    List<String> errors = new ArrayList<String>();
    int i = 1;
    for (Entry<String, String> violation : violations.entrySet()) {
        errors.add(i++ + " - " + violation.getValue() + " @ "
                + StringUtils.replace(arg.getInterfaceClass().toString(), "interface ", "") + "."
                + violation.getKey());
    }

    if (configuration.isDebug()) {
        LoggerHolder.getLog().error(msg.format("error.factory", LineSeparator.value(),
                StringUtils.join(errors, LineSeparator.value())) + LineSeparator.value());
    } else {
        throw new ReConfInitializationError(msg.format("error.factory", LineSeparator.value(),
                StringUtils.join(errors, LineSeparator.value())) + LineSeparator.value());
    }
}

From source file:org.broadleafcommerce.core.payment.service.OrderPaymentServiceImpl.java

@Override
@Transactional(value = TransactionUtils.DEFAULT_TRANSACTION_MANAGER)
public OrderPayment createOrderPaymentFromCustomerPayment(Order order, CustomerPayment customerPayment,
        Money amount) {//  w  w  w  .  j av  a  2  s .c  o m
    OrderPayment orderPayment = create();
    orderPayment.setOrder(order);
    orderPayment.setBillingAddress(addressService.copyAddress(customerPayment.getBillingAddress()));

    PaymentGatewayType gatewayType = customerPayment.getPaymentGatewayType();
    PaymentType paymentType = customerPayment.getPaymentType();
    Map<String, String> additionalFields = customerPayment.getAdditionalFields();
    if (gatewayType == null || paymentType == null) {
        if (MapUtils.isEmpty(additionalFields)) {
            additionalFields = new HashMap<>();
        }
        String paymentTypeKey = PaymentAdditionalFieldType.PAYMENT_TYPE.getType();
        if (additionalFields.containsKey(paymentTypeKey)) {
            paymentType = PaymentType.getInstance(additionalFields.get(paymentTypeKey));
        }
        String gatewayTypeKey = PaymentAdditionalFieldType.GATEWAY_TYPE.getType();
        if (additionalFields.containsKey(gatewayTypeKey)) {
            gatewayType = PaymentGatewayType.getInstance(additionalFields.get(gatewayTypeKey));
        }
    }
    orderPayment.setPaymentGatewayType(gatewayType);
    orderPayment.setType(paymentType);

    orderPayment.setAmount(amount);

    PaymentTransaction unconfirmedTransaction = createTransaction();
    unconfirmedTransaction.setAmount(amount);
    unconfirmedTransaction.setType(PaymentTransactionType.UNCONFIRMED);
    unconfirmedTransaction.setOrderPayment(orderPayment);
    unconfirmedTransaction.getAdditionalFields().put(PaymentAdditionalFieldType.TOKEN.getType(),
            customerPayment.getPaymentToken());
    unconfirmedTransaction.getAdditionalFields().putAll(customerPayment.getAdditionalFields());

    orderPayment.getTransactions().add(unconfirmedTransaction);

    return save(orderPayment);
}

From source file:org.craftercms.core.controller.rest.ContentStoreRestControllerTest.java

private void testNotModified(CachingAwareObject cachingAwareObject, RestMethodCallback callback)
        throws Exception {
    cachingAwareObject.setCachingTime(System.currentTimeMillis());
    request.addHeader(IF_MODIFIED_SINCE_HEADER_NAME, cachingAwareObject.getCachingTime());

    Map<String, Object> model = callback.executeMethod();
    assertTrue(MapUtils.isEmpty(model));
    assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getStatus());
    assertEquals(MUST_REVALIDATE_HEADER_VALUE, response.getHeader(CACHE_CONTROL_HEADER_NAME));
}

From source file:org.duniter.elasticsearch.client.Duniter4jClientImpl.java

/**
 * Retrieve some field from a document id, and check if all field not null
 * @param index//w ww.  ja v a  2 s  .  co m
 * @param type
 * @param docId
 * @param fieldNames
 * @return
 */
@Override
public Map<String, Object> getMandatoryFieldsById(String index, String type, String docId,
        String... fieldNames) {
    Map<String, Object> fields = getFieldsById(index, type, docId, fieldNames);
    if (MapUtils.isEmpty(fields))
        throw new NotFoundException(String.format("Document [%s/%s/%s] not exists.", index, type, docId));
    Arrays.stream(fieldNames).forEach((fieldName) -> {
        if (!fields.containsKey(fieldName))
            throw new NotFoundException(
                    String.format("Document [%s/%s/%s] should have the mandatory field [%s].", index, type,
                            docId, fieldName));
    });
    return fields;
}

From source file:org.duniter.elasticsearch.client.Duniter4jClientImpl.java

/**
 * Retrieve a field from a document id//from  www  .j  ava 2 s. c om
 * @param docId
 * @return
 */
@Override
public Object getFieldById(String index, String type, String docId, String fieldName) {

    Map<String, Object> result = getFieldsById(index, type, docId, fieldName);
    if (MapUtils.isEmpty(result)) {
        return null;
    }
    return result.get(fieldName);
}