Example usage for org.apache.commons.collections4 ListUtils emptyIfNull

List of usage examples for org.apache.commons.collections4 ListUtils emptyIfNull

Introduction

In this page you can find the example usage for org.apache.commons.collections4 ListUtils emptyIfNull.

Prototype

public static <T> List<T> emptyIfNull(final List<T> list) 

Source Link

Document

Returns an immutable empty list if the argument is null, or the argument itself otherwise.

Usage

From source file:org.apache.samza.execution.ExecutionPlanner.java

/**
 * Groups streams participating in joins together.
 *///w  ww.  j av a  2s . com
private static List<StreamSet> groupJoinedStreams(JobGraph jobGraph) {
    // Group input operator specs (input/intermediate streams) by the joins they participate in.
    Multimap<OperatorSpec, InputOperatorSpec> joinOpSpecToInputOpSpecs = OperatorSpecGraphAnalyzer
            .getJoinToInputOperatorSpecs(jobGraph.getApplicationDescriptorImpl().getInputOperators().values());

    Map<String, TableDescriptor> tableDescriptors = jobGraph.getTables().stream()
            .collect(Collectors.toMap(TableDescriptor::getTableId, Function.identity()));

    // Convert every group of input operator specs into a group of corresponding stream edges.
    List<StreamSet> streamSets = new ArrayList<>();
    for (OperatorSpec joinOpSpec : joinOpSpecToInputOpSpecs.keySet()) {
        Collection<InputOperatorSpec> joinedInputOpSpecs = joinOpSpecToInputOpSpecs.get(joinOpSpec);
        StreamSet streamSet = getStreamSet(joinOpSpec.getOpId(), joinedInputOpSpecs, jobGraph);

        // If current join is a stream-table join, add the stream edges corresponding to side-input
        // streams associated with the joined table (if any).
        if (joinOpSpec instanceof StreamTableJoinOperatorSpec) {
            StreamTableJoinOperatorSpec streamTableJoinOperatorSpec = (StreamTableJoinOperatorSpec) joinOpSpec;
            TableDescriptor tableDescriptor = tableDescriptors.get(streamTableJoinOperatorSpec.getTableId());
            if (tableDescriptor instanceof LocalTableDescriptor) {
                LocalTableDescriptor localTableDescriptor = (LocalTableDescriptor) tableDescriptor;
                Collection<String> sideInputs = ListUtils.emptyIfNull(localTableDescriptor.getSideInputs());
                Iterable<StreamEdge> sideInputStreams = sideInputs.stream()
                        .map(jobGraph::getStreamEdge)::iterator;
                Iterable<StreamEdge> streams = streamSet.getStreamEdges();
                streamSet = new StreamSet(streamSet.getSetId(), Iterables.concat(streams, sideInputStreams));
            }
        }

        streamSets.add(streamSet);
    }

    return Collections.unmodifiableList(streamSets);
}

From source file:org.apache.syncope.core.misc.utils.MappingUtils.java

/**
 * Set attribute values, according to the given {@link MappingItem}, to any object from attribute received from
 * connector./*from   w ww . j av  a2s .  co m*/
 *
 * @param <T> any object
 * @param mappingItem mapping item
 * @param attr attribute received from connector
 * @param anyTO any object
 * @param anyUtils any utils
 */
@Transactional(readOnly = true)
public <T extends AnyTO> void setIntValues(final MappingItem mappingItem, final Attribute attr, final T anyTO,
        final AnyUtils anyUtils) {

    List<Object> values = null;
    if (attr != null) {
        values = attr.getValue();
        for (MappingItemTransformer transformer : getMappingItemTransformers(mappingItem)) {
            values = transformer.beforeSync(values);
        }
    }
    values = ListUtils.emptyIfNull(values);

    switch (mappingItem.getIntMappingType()) {
    case UserKey:
    case GroupKey:
    case AnyObjectKey:
        break;

    case Password:
        if (anyTO instanceof UserTO && !values.isEmpty()) {
            ((UserTO) anyTO).setPassword(ConnObjectUtils.getPassword(values.get(0)));
        }
        break;

    case Username:
        if (anyTO instanceof UserTO) {
            ((UserTO) anyTO)
                    .setUsername(values.isEmpty() || values.get(0) == null ? null : values.get(0).toString());
        }
        break;

    case GroupName:
        if (anyTO instanceof GroupTO) {
            ((GroupTO) anyTO)
                    .setName(values.isEmpty() || values.get(0) == null ? null : values.get(0).toString());
        }
        break;

    case GroupOwnerSchema:
        if (anyTO instanceof GroupTO && attr != null) {
            // using a special attribute (with schema "", that will be ignored) for carrying the
            // GroupOwnerSchema value
            AttrTO attrTO = new AttrTO();
            attrTO.setSchema(StringUtils.EMPTY);
            if (values.isEmpty() || values.get(0) == null) {
                attrTO.getValues().add(StringUtils.EMPTY);
            } else {
                attrTO.getValues().add(values.get(0).toString());
            }

            ((GroupTO) anyTO).getPlainAttrs().add(attrTO);
        }
        break;

    case UserPlainSchema:
    case GroupPlainSchema:
    case AnyObjectPlainSchema:
        AttrTO attrTO = new AttrTO();
        attrTO.setSchema(mappingItem.getIntAttrName());

        PlainSchema schema = plainSchemaDAO.find(mappingItem.getIntAttrName());

        for (Object value : values) {
            AttrSchemaType schemaType = schema == null ? AttrSchemaType.String : schema.getType();
            if (value != null) {
                PlainAttrValue attrValue = anyUtils.newPlainAttrValue();
                switch (schemaType) {
                case String:
                    attrValue.setStringValue(value.toString());
                    break;

                case Binary:
                    attrValue.setBinaryValue((byte[]) value);
                    break;

                default:
                    try {
                        attrValue.parseValue(schema, value.toString());
                    } catch (ParsingValidationException e) {
                        LOG.error("While parsing provided value {}", value, e);
                        attrValue.setStringValue(value.toString());
                        schemaType = AttrSchemaType.String;
                    }
                    break;
                }
                attrTO.getValues().add(attrValue.getValueAsString(schemaType));
            }
        }

        anyTO.getPlainAttrs().add(attrTO);
        break;

    case UserDerivedSchema:
    case GroupDerivedSchema:
    case AnyObjectDerivedSchema:
        attrTO = new AttrTO();
        attrTO.setSchema(mappingItem.getIntAttrName());
        anyTO.getDerAttrs().add(attrTO);
        break;

    case UserVirtualSchema:
    case GroupVirtualSchema:
    case AnyObjectVirtualSchema:
        attrTO = new AttrTO();
        attrTO.setSchema(mappingItem.getIntAttrName());

        // virtual attributes don't get transformed, iterate over original attr.getValue()
        for (Object value : (attr == null || attr.getValue() == null) ? Collections.emptyList()
                : attr.getValue()) {

            if (value != null) {
                attrTO.getValues().add(value.toString());
            }
        }

        anyTO.getVirAttrs().add(attrTO);
        break;

    default:
    }
}

From source file:org.apache.syncope.core.provisioning.java.VirAttrHandlerImpl.java

@Override
public List<String> getValues(final Any<?> any, final VirSchema schema) {
    if (!anyUtilsFactory.getInstance(any).getAllowedSchemas(any, VirSchema.class).forSelfContains(schema)) {

        LOG.debug("{} not allowed for {}", schema, any);
        return Collections.emptyList();
    }//from  w ww . j  ava  2  s . com

    return ListUtils.emptyIfNull(getValues(any, Collections.singleton(schema)).get(schema));
}

From source file:org.apache.syncope.core.provisioning.java.VirAttrHandlerImpl.java

@Override
public List<String> getValues(final Any<?> any, final Membership<?> membership, final VirSchema schema) {
    if (!anyUtilsFactory.getInstance(any).getAllowedSchemas(any, VirSchema.class)
            .getForMembership(membership.getRightEnd()).contains(schema)) {

        LOG.debug("{} not allowed for {}", schema, any);
        return Collections.emptyList();
    }/*  ww  w.ja  v a2s  .  co  m*/

    return ListUtils.emptyIfNull(getValues(any, Collections.singleton(schema)).get(schema));
}

From source file:org.apache.tez.dag.app.TaskCommunicatorManager.java

public TaskHeartbeatResponse heartbeat(TaskHeartbeatRequest request) throws IOException, TezException {
    ContainerId containerId = ConverterUtils.toContainerId(request.getContainerIdentifier());
    if (LOG.isDebugEnabled()) {
        LOG.debug("Received heartbeat from container" + ", request=" + request);
    }/*  w  w  w.j a v a2s . c o m*/

    if (!registeredContainers.containsKey(containerId)) {
        LOG.warn("Received task heartbeat from unknown container with id: " + containerId
                + ", asking it to die");
        return RESPONSE_SHOULD_DIE;
    }

    // A heartbeat can come in anytime. The AM may have made a decision to kill a running task/container
    // meanwhile. If the decision is processed through the pipeline before the heartbeat is processed,
    // the heartbeat will be dropped. Otherwise the heartbeat will be processed - and the system
    // know how to handle this - via FailedInputEvents for example (relevant only if the heartbeat has events).
    // So - avoiding synchronization.

    pingContainerHeartbeatHandler(containerId);
    TaskAttemptEventInfo eventInfo = new TaskAttemptEventInfo(0, null, 0);
    TezTaskAttemptID taskAttemptID = request.getTaskAttemptId();
    if (taskAttemptID != null) {
        ContainerId containerIdFromMap = registeredAttempts.get(taskAttemptID);
        if (containerIdFromMap == null || !containerIdFromMap.equals(containerId)) {
            // This can happen when a task heartbeats. Meanwhile the container is unregistered.
            // The information will eventually make it through to the plugin via a corresponding unregister.
            // There's a race in that case between the unregister making it through, and this method returning.
            // TODO TEZ-2003 (post) TEZ-2666. An exception back is likely a better approach than sending a shouldDie = true,
            // so that the plugin can handle the scenario. Alternately augment the response with error codes.
            // Error codes would be better than exceptions.
            LOG.info("Attempt: " + taskAttemptID + " is not recognized for heartbeats");
            return RESPONSE_SHOULD_DIE;
        }

        List<TezEvent> inEvents = request.getEvents();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Ping from " + taskAttemptID.toString() + " events: "
                    + (inEvents != null ? inEvents.size() : -1));
        }

        long currTime = context.getClock().getTime();
        // taFinishedEvents - means the TaskAttemptFinishedEvent
        // taGeneratedEvents - for recovery, means the events generated by this task attempt and is needed by its downstream vertices
        // eventsForVertex - including all the taGeneratedEvents and other events such as INPUT_READ_ERROR_EVENT/INPUT_FAILED_EVENT
        // taGeneratedEvents is routed both to TaskAttempt & Vertex. Route to Vertex is for performance consideration
        // taFinishedEvents must be routed before taGeneratedEvents
        List<TezEvent> taFinishedEvents = new ArrayList<TezEvent>();
        List<TezEvent> taGeneratedEvents = new ArrayList<TezEvent>();
        List<TezEvent> eventsForVertex = new ArrayList<TezEvent>();
        TaskAttemptEventStatusUpdate taskAttemptEvent = null;
        boolean readErrorReported = false;
        for (TezEvent tezEvent : ListUtils.emptyIfNull(inEvents)) {
            // for now, set the event time on the AM when it is received.
            // this avoids any time disparity between machines.
            tezEvent.setEventReceivedTime(currTime);
            final EventType eventType = tezEvent.getEventType();
            if (eventType == EventType.TASK_STATUS_UPDATE_EVENT) {
                // send TA_STATUS_UPDATE before TA_DONE/TA_FAILED/TA_KILLED otherwise Status may be missed
                taskAttemptEvent = new TaskAttemptEventStatusUpdate(taskAttemptID,
                        (TaskStatusUpdateEvent) tezEvent.getEvent());
            } else if (eventType == EventType.TASK_ATTEMPT_COMPLETED_EVENT
                    || eventType == EventType.TASK_ATTEMPT_FAILED_EVENT
                    || eventType == EventType.TASK_ATTEMPT_KILLED_EVENT) {
                taFinishedEvents.add(tezEvent);
            } else {
                if (eventType == EventType.INPUT_READ_ERROR_EVENT) {
                    readErrorReported = true;
                }
                if (eventType == EventType.DATA_MOVEMENT_EVENT
                        || eventType == EventType.COMPOSITE_DATA_MOVEMENT_EVENT
                        || eventType == EventType.ROOT_INPUT_INITIALIZER_EVENT
                        || eventType == EventType.VERTEX_MANAGER_EVENT) {
                    taGeneratedEvents.add(tezEvent);
                }
                eventsForVertex.add(tezEvent);
            }
        }
        if (taskAttemptEvent != null) {
            taskAttemptEvent.setReadErrorReported(readErrorReported);
            sendEvent(taskAttemptEvent);
        }
        // route taGeneratedEvents to TaskAttempt
        if (!taGeneratedEvents.isEmpty()) {
            sendEvent(new TaskAttemptEventTezEventUpdate(taskAttemptID, taGeneratedEvents));
        }
        // route events to TaskAttempt
        Preconditions.checkArgument(taFinishedEvents.size() <= 1, "Multiple TaskAttemptFinishedEvent");
        for (TezEvent e : taFinishedEvents) {
            EventMetaData sourceMeta = e.getSourceInfo();
            switch (e.getEventType()) {
            case TASK_ATTEMPT_FAILED_EVENT:
            case TASK_ATTEMPT_KILLED_EVENT:
                TaskAttemptTerminationCause errCause = null;
                switch (sourceMeta.getEventGenerator()) {
                case INPUT:
                    errCause = TaskAttemptTerminationCause.INPUT_READ_ERROR;
                    break;
                case PROCESSOR:
                    errCause = TaskAttemptTerminationCause.APPLICATION_ERROR;
                    break;
                case OUTPUT:
                    errCause = TaskAttemptTerminationCause.OUTPUT_WRITE_ERROR;
                    break;
                case SYSTEM:
                    errCause = TaskAttemptTerminationCause.FRAMEWORK_ERROR;
                    break;
                default:
                    throw new TezUncheckedException(
                            "Unknown EventProducerConsumerType: " + sourceMeta.getEventGenerator());
                }
                if (e.getEventType() == EventType.TASK_ATTEMPT_FAILED_EVENT) {
                    TaskAttemptFailedEvent taskFailedEvent = (TaskAttemptFailedEvent) e.getEvent();
                    sendEvent(new TaskAttemptEventAttemptFailed(sourceMeta.getTaskAttemptID(),
                            TaskAttemptEventType.TA_FAILED, taskFailedEvent.getTaskFailureType(),
                            "Error: " + taskFailedEvent.getDiagnostics(), errCause));
                } else { // Killed
                    TaskAttemptKilledEvent taskKilledEvent = (TaskAttemptKilledEvent) e.getEvent();
                    sendEvent(new TaskAttemptEventAttemptKilled(sourceMeta.getTaskAttemptID(),
                            "Error: " + taskKilledEvent.getDiagnostics(), errCause));
                }
                break;
            case TASK_ATTEMPT_COMPLETED_EVENT:
                sendEvent(new TaskAttemptEvent(sourceMeta.getTaskAttemptID(), TaskAttemptEventType.TA_DONE));
                break;
            default:
                throw new TezUncheckedException("Unhandled tez event type: " + e.getEventType());
            }
        }
        if (!eventsForVertex.isEmpty()) {
            TezVertexID vertexId = taskAttemptID.getTaskID().getVertexID();
            sendEvent(new VertexEventRouteEvent(vertexId, Collections.unmodifiableList(eventsForVertex)));
        }
        taskHeartbeatHandler.pinged(taskAttemptID);
        eventInfo = context.getCurrentDAG().getVertex(taskAttemptID.getTaskID().getVertexID())
                .getTaskAttemptTezEvents(taskAttemptID, request.getStartIndex(),
                        request.getPreRoutedStartIndex(), request.getMaxEvents());
    }
    return new TaskHeartbeatResponse(false, eventInfo.getEvents(), eventInfo.getNextFromEventId(),
            eventInfo.getNextPreRoutedFromEventId());
}

From source file:org.dspace.discovery.DiscoverResult.java

public List<FacetResult> getFacetResult(String facet) {
    return ListUtils.emptyIfNull(facetResults.get(facet));
}

From source file:org.dspace.discovery.DiscoverResult.java

public List<FacetResult> getFacetResult(DiscoverySearchFilterFacet field) {
    List<DiscoverResult.FacetResult> facetValues = getFacetResult(field.getIndexFieldName());
    //Check if we are dealing with a date, sometimes the facet values arrive as dates !
    if (facetValues.size() == 0 && field.getType().equals(DiscoveryConfigurationParameters.TYPE_DATE)) {
        facetValues = getFacetResult(field.getIndexFieldName() + ".year");
    }//from  w  w  w .j ava2s  . c om
    return ListUtils.emptyIfNull(facetValues);
}

From source file:org.heliosphere.thot.akka.chat.client.TerminalActor.java

/**
 * Handles a command response./* w w  w  .j  ava 2  s .  c o  m*/
 * <hr>
 * @param response Command response to handle.
 */
@SuppressWarnings("nls")
protected void handleResponse(final @NonNull ICommandResponse response) {
    switch ((DefaultCommandCodeType) response.getOrder()) {
    case DISPLAY_TERMINAL:

        // Display the status of the command execution then the exceptions and then the messages.
        terminal.getTerminal().println("[status: " + response.getStatus() + " for command: "
                + response.getCommand().getMetadata().getName() + "]");

        for (Exception e : ListUtils.emptyIfNull(response.getExceptions())) {
            terminal.getTerminal().println("   Error: " + e.getMessage());
        }

        for (String element : ListUtils.emptyIfNull(response.getMessages())) {
            terminal.getTerminal().println(element);
        }
        break;

    case QUIT:
        getContext().system().terminate();
        terminal.getTerminal().println("System is shutting down...");
        break;

    default:
        break;
    }

    // Resumes the terminal thread.
    terminal.resume();
}

From source file:org.kuali.coeus.common.budget.impl.core.category.BudgetCategoryMapServiceImpl.java

private <T extends BusinessObject> List<T> findByMappingName(String mappingName, Class<T> clazz) {
    if (StringUtils.isBlank(mappingName)) {
        throw new IllegalArgumentException("mappingName is blank");
    }//from w  w w.  j a v  a 2  s .  c om
    return ListUtils.emptyIfNull((List<T>) businessObjectService.findMatching(clazz,
            Collections.singletonMap(KEY_MAPPING_NAME, mappingName)));
}

From source file:org.kuali.coeus.common.budget.impl.core.category.BudgetCategoryMapServiceImpl.java

private <T extends BusinessObject> List<T> findByTargetAndMappingName(String targetCategoryCode,
        String mappingName, Class<T> clazz) {
    if (StringUtils.isBlank(targetCategoryCode)) {
        throw new IllegalArgumentException("targetCategoryCode is blank");
    }//from  w  w  w  . j av  a2  s .  c  o m

    if (StringUtils.isBlank(mappingName)) {
        throw new IllegalArgumentException("mappingName is blank");
    }

    final Map<String, String> conditionMap = new HashMap<String, String>();
    conditionMap.put(KEY_MAPPING_NAME, mappingName);
    conditionMap.put(KEY_TARGET_CATEGORY_CODE, targetCategoryCode);
    return ListUtils.emptyIfNull((List<T>) businessObjectService.findMatching(clazz, conditionMap));
}