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

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

Introduction

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

Prototype

public static boolean isEmpty(final Collection<?> coll) 

Source Link

Document

Null-safe check if the specified collection is empty.

Usage

From source file:org.apache.nifi.controller.StandardFlowSynchronizer.java

private static boolean isEmpty(final ProcessGroupDTO dto) {
    if (dto == null) {
        return true;
    }//from ww  w  .j  a v  a 2s  .  c o m

    final FlowSnippetDTO contents = dto.getContents();
    if (contents == null) {
        return true;
    }

    return CollectionUtils.isEmpty(contents.getProcessors())
            && CollectionUtils.isEmpty(contents.getConnections())
            && CollectionUtils.isEmpty(contents.getFunnels()) && CollectionUtils.isEmpty(contents.getLabels())
            && CollectionUtils.isEmpty(contents.getOutputPorts())
            && CollectionUtils.isEmpty(contents.getProcessGroups())
            && CollectionUtils.isEmpty(contents.getProcessors())
            && CollectionUtils.isEmpty(contents.getRemoteProcessGroups());
}

From source file:org.apache.nifi.processors.att.m2x.GetM2XStream.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final ProcessorLog logger = getLogger();
    final OkHttpClient httpClient = getHttpClient();
    final StateManager stateManager = context.getStateManager();
    final String apiKey = context.getProperty(M2X_API_KEY).getValue();
    final String apiUrl = context.getProperty(M2X_API_URL).getValue();
    final String deviceId = context.getProperty(M2X_DEVICE_ID).getValue();
    final String streamName = context.getProperty(M2X_STREAM_NAME).getValue();
    final String streamType = context.getProperty(M2X_STREAM_TYPE).getValue();
    final String startTime = getLastStartTime(context, stateManager);
    final String streamUrl = getStreamUrl(apiUrl, deviceId, streamName, startTime);

    String responseBody;//from w  w w  .j  av a2 s  . co  m
    try {
        final Request request = new Request.Builder().url(streamUrl).addHeader("X-M2X-KEY", apiKey).build();
        final Response response = httpClient.newCall(request).execute();

        if (!response.isSuccessful()) {
            logger.error(response.message());
            context.yield();
            return;
        }

        responseBody = response.body().string();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        context.yield();
        return;
    }

    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JodaModule());
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

    try {
        final M2XStreamValues m2xValues = mapper.readValue(responseBody, M2XStreamValues.class);
        final List<M2XStreamValue> m2xValueList = m2xValues.getValues();

        if (!CollectionUtils.isEmpty(m2xValueList)) {
            for (final M2XStreamValue m2xValue : m2xValueList) {
                final DateTime timestamp = m2xValue.getTimestamp();
                final Object valueObj = m2xValue.getValue();
                final Set<Map.Entry<String, Object>> properties = m2xValue.getAdditionalProperties().entrySet();
                final ByteArrayInputStream bytes = new ByteArrayInputStream(
                        String.valueOf(valueObj).getBytes(StandardCharsets.UTF_8));

                FlowFile newFlowFile = session.create();
                newFlowFile = session.importFrom(bytes, newFlowFile);
                newFlowFile = session.putAttribute(newFlowFile, "m2x.device.id", deviceId);
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.name", streamName);
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.start",
                        m2xValues.getStart().toString());
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.end",
                        m2xValues.getEnd().toString());
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.limit",
                        String.valueOf(m2xValues.getLimit()));
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.value.timestamp",
                        timestamp.toString());
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.value.millis",
                        String.valueOf(timestamp.getMillis()));
                for (final Map.Entry<String, Object> e : properties) {
                    newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.value." + e.getKey(),
                            String.valueOf(e.getValue()));
                }

                session.getProvenanceReporter().create(newFlowFile);
                session.transfer(newFlowFile, REL_SUCCESS);
            }
        }

        setLastStartTime(stateManager, m2xValues.getEnd().toString());
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        context.yield();
    }
}

From source file:org.apache.nutch.service.model.request.SeedList.java

@JsonIgnore
public int getSeedUrlsCount() {
    if (CollectionUtils.isEmpty(seedUrls)) {
        return 0;
    }
    return seedUrls.size();
}

From source file:org.apache.nutch.webui.client.impl.CrawlingCycle.java

private int calculateProgress() {
    if (CollectionUtils.isEmpty(remoteCommands)) {
        return 0;
    }/*  w  w  w  .  j  a va  2 s  . c om*/
    return (int) ((float) executedCommands.size() / (float) remoteCommands.size() * 100);
}

From source file:org.apache.ofbiz.content.cms.ContentJsonEvents.java

private static Map<String, Object> getTreeNode(GenericValue assoc) throws GenericEntityException {
    GenericValue content = assoc.getRelatedOne("ToContent", true);
    String contentName = assoc.getString("contentIdTo");
    if (content != null && content.getString("contentName") != null) {
        contentName = content.getString("contentName");
        if (contentName.length() > CONTENT_NAME_MAX_LENGTH) {
            contentName = contentName.substring(0, CONTENT_NAME_MAX_LENGTH);
        }// w w  w. ja v a2s  . c om
    }

    Map<String, Object> data = UtilMisc.toMap("title", (Object) contentName);

    Map<String, Object> attr = UtilMisc.toMap("id", assoc.get("contentIdTo"), "contentId",
            assoc.get("contentId"), "fromDate", assoc.getTimestamp("fromDate").toString(), "contentAssocTypeId",
            assoc.get("contentAssocTypeId"));

    Map<String, Object> node = UtilMisc.toMap("data", (Object) data, "attr", (Object) attr);

    List<GenericValue> assocChildren = content.getRelated("FromContentAssoc", null, null, true);
    assocChildren = EntityUtil.filterByDate(assocChildren);
    if (!CollectionUtils.isEmpty(assocChildren)) {
        node.put("state", "closed");
    }
    return node;
}

From source file:org.apache.syncope.client.console.bulk.BulkContent.java

public BulkContent(final String id, final BaseModal<?> modal, final Collection<T> items,
        final List<IColumn<T, S>> columns, final Collection<ActionLink.ActionType> actions,
        final RestClient bulkActionExecutor, final String keyFieldName) {

    super(id);//  w  w  w  .j ava2 s .  c  o m

    final WebMarkupContainer container = new WebMarkupContainer("container");
    container.setOutputMarkupId(true);
    add(container);

    final SortableDataProvider<T, S> dataProvider = new SortableDataProvider<T, S>() {

        private static final long serialVersionUID = 5291903859908641954L;

        @Override
        public Iterator<? extends T> iterator(final long first, final long count) {
            return items.iterator();
        }

        @Override
        public long size() {
            return items.size();
        }

        @Override
        public IModel<T> model(final T object) {
            return new CompoundPropertyModel<>(object);
        }
    };

    container
            .add(new AjaxFallbackDefaultDataTable<>("selectedObjects", columns, dataProvider, Integer.MAX_VALUE)
                    .setMarkupId("selectedObjects").setVisible(items != null && !items.isEmpty()));

    final ActionLinksPanel<Serializable> actionPanel = ActionLinksPanel.builder().build("actions");
    container.add(actionPanel);

    for (ActionLink.ActionType action : actions) {
        final ActionType actionToBeAddresed = action;

        actionPanel.add(new ActionLink<Serializable>() {

            private static final long serialVersionUID = -3722207913631435501L;

            @Override
            protected boolean statusCondition(final Serializable modelObject) {
                return CollectionUtils.isNotEmpty(items);
            }

            @Override
            public void onClick(final AjaxRequestTarget target, final Serializable ignore) {
                try {
                    if (CollectionUtils.isEmpty(items)) {
                        throw new IllegalArgumentException("Invalid items");
                    }

                    String fieldName = keyFieldName;

                    BulkActionResult res = null;
                    try {
                        if (items.iterator().next() instanceof StatusBean) {
                            throw new IllegalArgumentException("Invalid items");
                        }

                        final BulkAction bulkAction = new BulkAction();
                        bulkAction.setType(BulkAction.Type.valueOf(actionToBeAddresed.name()));
                        for (T item : items) {
                            try {
                                bulkAction.getTargets().add(getTargetId(item, keyFieldName).toString());
                            } catch (IllegalAccessException | InvocationTargetException e) {
                                LOG.error("Error retrieving item id {}", keyFieldName, e);
                            }
                        }
                        res = BulkActionResult.class
                                .cast(bulkActionExecutor.getClass().getMethod("bulkAction", BulkAction.class)
                                        .invoke(bulkActionExecutor, bulkAction));
                    } catch (IllegalArgumentException biae) {
                        if (!(items.iterator().next() instanceof StatusBean)) {
                            throw new IllegalArgumentException("Invalid items");
                        }

                        if (!(bulkActionExecutor instanceof AbstractAnyRestClient)) {
                            throw new IllegalArgumentException("Invalid bulk action executor");
                        }

                        final AbstractAnyRestClient<?, ?> anyRestClient = AbstractAnyRestClient.class
                                .cast(bulkActionExecutor);

                        // Group bean information by anyKey
                        final Map<String, List<StatusBean>> beans = new HashMap<>();
                        for (T bean : items) {
                            final StatusBean sb = StatusBean.class.cast(bean);
                            final List<StatusBean> sblist;
                            if (beans.containsKey(sb.getAnyKey())) {
                                sblist = beans.get(sb.getAnyKey());
                            } else {
                                sblist = new ArrayList<>();
                                beans.put(sb.getAnyKey(), sblist);
                            }
                            sblist.add(sb);
                        }

                        for (Map.Entry<String, List<StatusBean>> entry : beans.entrySet()) {
                            final String etag = anyRestClient.read(entry.getKey()).getETagValue();
                            switch (actionToBeAddresed.name()) {
                            case "DEPROVISION":
                                res = anyRestClient.deprovision(etag, entry.getKey(), entry.getValue());
                                break;
                            case "UNASSIGN":
                                res = anyRestClient.unassign(etag, entry.getKey(), entry.getValue());
                                break;
                            case "UNLINK":
                                res = anyRestClient.unlink(etag, entry.getKey(), entry.getValue());
                                break;
                            case "ASSIGN":
                                res = anyRestClient.assign(etag, entry.getKey(), entry.getValue());
                                break;
                            case "LINK":
                                res = anyRestClient.link(etag, entry.getKey(), entry.getValue());
                                break;
                            case "PROVISION":
                                res = anyRestClient.provision(etag, entry.getKey(), entry.getValue());
                                break;
                            case "REACTIVATE":
                                res = ((UserRestClient) anyRestClient).reactivate(etag, entry.getKey(),
                                        entry.getValue());
                                fieldName = "resourceName";
                                break;
                            case "SUSPEND":
                                res = ((UserRestClient) anyRestClient).suspend(etag, entry.getKey(),
                                        entry.getValue());
                                fieldName = "resourceName";
                                break;
                            default:
                                break;
                            }
                        }
                    }

                    if (modal != null) {
                        modal.changeCloseButtonLabel(getString("close", null, "Close"), target);
                    }

                    final List<IColumn<T, S>> newColumnList = new ArrayList<>(columns);
                    newColumnList.add(newColumnList.size(), new BulkActionResultColumn<T, S>(res, fieldName));

                    container.addOrReplace(new AjaxFallbackDefaultDataTable<>("selectedObjects", newColumnList,
                            dataProvider, Integer.MAX_VALUE).setVisible(!items.isEmpty()));

                    actionPanel.setEnabled(false);
                    actionPanel.setVisible(false);
                    target.add(container);
                    target.add(actionPanel);

                    SyncopeConsoleSession.get().info(getString(Constants.OPERATION_SUCCEEDED));
                } catch (Exception e) {
                    LOG.error("Bulk action failure", e);
                    SyncopeConsoleSession.get()
                            .error("Operation " + actionToBeAddresed.getActionId() + " not supported");
                }
                ((BasePage) getPage()).getNotificationPanel().refresh(target);
            }
        }, action, StandardEntitlement.CONFIGURATION_LIST, !items.isEmpty());
    }
}

From source file:org.apache.syncope.client.console.init.MIMETypesLoader.java

public void load() {
    if (CollectionUtils.isEmpty(mimeTypes)) {
        Set<String> mediaTypes = new HashSet<>();
        this.mimeTypes = new ArrayList<>();
        try {/*from w ww  .  ja  v a 2s  . c om*/
            final String mimeTypesFile = IOUtils.toString(getClass().getResourceAsStream("/MIMETypes"));
            for (String fileRow : mimeTypesFile.split("\n")) {
                if (StringUtils.isNotBlank(fileRow) && !fileRow.startsWith("#")) {
                    mediaTypes.add(fileRow);
                }
            }
            this.mimeTypes.addAll(mediaTypes);
            Collections.sort(this.mimeTypes);
        } catch (Exception e) {
            LOG.error("Error reading file MIMETypes from resources", e);
        }
    }
}

From source file:org.apache.syncope.client.console.notifications.NotificationWrapper.java

public Map<String, String> getAboutFIQLs() {
    if (CollectionUtils.isEmpty(this.aboutClauses)) {
        return this.notificationTO.getAbouts();
    } else {/*from   ww w  .java2s .c  o m*/
        Map<String, String> res = new HashMap<>();
        for (Pair<String, List<SearchClause>> pair : this.aboutClauses) {
            AbstractFiqlSearchConditionBuilder builder;
            switch (pair.getLeft()) {
            case "USER":
                builder = SyncopeClient.getUserSearchConditionBuilder();
                break;

            case "GROUP":
                builder = SyncopeClient.getGroupSearchConditionBuilder();
                break;

            default:
                builder = SyncopeClient.getAnyObjectSearchConditionBuilder(pair.getLeft());
            }
            res.put(pair.getLeft(), SearchUtils.buildFIQL(pair.getRight(), builder));
        }
        return res;
    }
}

From source file:org.apache.syncope.client.console.notifications.NotificationWrapper.java

private String getRecipientsFIQL() {
    if (CollectionUtils.isEmpty(this.recipientClauses)) {
        return null;
    } else {//from   w  w  w .j  av  a2s  .  c o m
        return SearchUtils.buildFIQL(this.recipientClauses, SyncopeClient.getUserSearchConditionBuilder());
    }
}

From source file:org.apache.syncope.client.console.pages.Audit.java

public Audit(final PageParameters parameters) {
    super(parameters);

    body.add(BookmarkablePageLinkBuilder.build("dashboard", "dashboardBr", Dashboard.class));

    final LoggerRestClient loggerRestClient = new LoggerRestClient();

    List<String> events = loggerRestClient.listAudits().stream()
            .map(audit -> AuditLoggerName.buildEvent(audit.getType(), audit.getCategory(),
                    audit.getSubcategory(), audit.getEvent(), audit.getResult()))
            .collect(Collectors.toList());

    WebMarkupContainer content = new WebMarkupContainer("content");
    content.setOutputMarkupId(true);//  w w  w .j  a  v  a 2 s . c  o m

    Form<?> form = new Form<>("auditForm");
    content.add(form);

    form.add(new EventCategoryPanel("auditPanel", loggerRestClient.listEvents(), new ListModel<>(events)) {

        private static final long serialVersionUID = 6113164334533550277L;

        @Override
        protected List<String> getListAuthRoles() {
            return Collections.singletonList(StandardEntitlement.AUDIT_LIST);
        }

        @Override
        protected List<String> getChangeAuthRoles() {
            return Arrays.asList(
                    new String[] { StandardEntitlement.AUDIT_ENABLE, StandardEntitlement.AUDIT_DISABLE });
        }

        @Override
        public void onEventAction(final IEvent<?> event) {
            if (event.getPayload() instanceof SelectedEventsPanel.EventSelectionChanged) {
                final SelectedEventsPanel.EventSelectionChanged eventSelectionChanged = (SelectedEventsPanel.EventSelectionChanged) event
                        .getPayload();

                eventSelectionChanged.getToBeRemoved().forEach(toBeRemoved -> {
                    Pair<EventCategoryTO, AuditElements.Result> eventCategory = AuditLoggerName
                            .parseEventCategory(toBeRemoved);

                    AuditLoggerName auditLoggerName = new AuditLoggerName(eventCategory.getKey().getType(),
                            eventCategory.getKey().getCategory(), eventCategory.getKey().getSubcategory(),
                            CollectionUtils.isEmpty(eventCategory.getKey().getEvents()) ? null
                                    : eventCategory.getKey().getEvents().iterator().next(),
                            eventCategory.getValue());

                    loggerRestClient.disableAudit(auditLoggerName);
                });

                eventSelectionChanged.getToBeAdded().forEach(toBeAdded -> {
                    Pair<EventCategoryTO, AuditElements.Result> eventCategory = AuditLoggerName
                            .parseEventCategory(toBeAdded);

                    AuditLoggerName auditLoggerName = new AuditLoggerName(eventCategory.getKey().getType(),
                            eventCategory.getKey().getCategory(), eventCategory.getKey().getSubcategory(),
                            CollectionUtils.isEmpty(eventCategory.getKey().getEvents()) ? null
                                    : eventCategory.getKey().getEvents().iterator().next(),
                            eventCategory.getValue());

                    loggerRestClient.enableAudit(auditLoggerName);
                });
            }
        }
    });

    body.add(content);
}