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

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

Introduction

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

Prototype

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

Source Link

Document

Null-safe check if the specified map is not empty.

Usage

From source file:org.openscore.lang.cli.services.SyncTriggerEventListener.java

public static Map<String, Serializable> extractOutputs(Map<String, Serializable> data) {
    if (data.containsKey(LanguageEventData.OUTPUTS) && data.containsKey(LanguageEventData.PATH)
            && data.get(LanguageEventData.PATH).equals(EXEC_START_PATH)) {

        @SuppressWarnings("unchecked")
        Map<String, Serializable> outputs = (Map<String, Serializable>) data.get(LanguageEventData.OUTPUTS);
        if (MapUtils.isNotEmpty(outputs)) {
            Iterator<Map.Entry<String, Serializable>> iterator = outputs.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Serializable> output = iterator.next();
                if (StringUtils.isEmpty(output.getValue().toString())) {
                    iterator.remove();/*from   ww  w .j a va 2s  .  com*/
                } else {
                    outputs.put(output.getKey(),
                            StringUtils.abbreviate(output.getValue().toString(), 0, OUTPUT_VALUE_LIMIT));
                }
            }
        }
        return outputs;
    }
    return new HashMap<>();
}

From source file:org.openscore.lang.compiler.modeller.ExecutableBuilder.java

private Workflow compileWorkFlow(List<Map<String, Map<String, Object>>> workFlowRawData,
        Map<String, String> imports, Workflow onFailureWorkFlow, boolean onFailureSection) {

    Deque<Task> tasks = new LinkedList<>();

    Validate.notEmpty(workFlowRawData, "Flow must have tasks in its workflow");

    PeekingIterator<Map<String, Map<String, Object>>> iterator = new PeekingIterator<>(
            workFlowRawData.iterator());

    boolean isOnFailureDefined = onFailureWorkFlow != null;

    String defaultFailure = isOnFailureDefined ? onFailureWorkFlow.getTasks().getFirst().getName()
            : FAILURE_RESULT;/*from  w w  w  .ja  va 2s  . com*/

    Set<String> taskNames = new HashSet<>();

    while (iterator.hasNext()) {
        Map<String, Map<String, Object>> taskRawData = iterator.next();
        Map<String, Map<String, Object>> nextTaskData = iterator.peek();
        String taskName = taskRawData.keySet().iterator().next();
        if (taskNames.contains(taskName)) {
            throw new RuntimeException("Task name: \'" + taskName
                    + "\' appears more than once in the workflow. Each task name in the workflow must be unique");
        }
        taskNames.add(taskName);
        Map<String, Object> taskRawDataValue;
        String message = "Task: " + taskName
                + " syntax is illegal.\nBelow task name, there should be a map of values in the format:\ndo:\n\top_name:";
        try {
            taskRawDataValue = taskRawData.values().iterator().next();
            if (MapUtils.isNotEmpty(taskRawDataValue) && taskRawDataValue.containsKey(LOOP_KEY)) {
                message = "Task: " + taskName
                        + " syntax is illegal.\nBelow the 'loop' keyword, there should be a map of values in the format:\nfor:\ndo:\n\top_name:";
                taskRawDataValue.putAll((Map<String, Object>) taskRawDataValue.remove(LOOP_KEY));
            }
        } catch (ClassCastException ex) {
            throw new RuntimeException(message);
        }

        String defaultSuccess;
        if (nextTaskData != null) {
            defaultSuccess = nextTaskData.keySet().iterator().next();
        } else {
            defaultSuccess = onFailureSection ? FAILURE_RESULT : SUCCESS_RESULT;
        }
        Task task = compileTask(taskName, taskRawDataValue, defaultSuccess, imports, defaultFailure);
        tasks.add(task);
    }

    if (isOnFailureDefined) {
        tasks.addAll(onFailureWorkFlow.getTasks());
    }

    return new Workflow(tasks);
}

From source file:org.openscore.lang.compiler.scorecompiler.ExecutionStepFactory.java

public ExecutionStep createActionStep(Long index, Map<String, Serializable> actionRawData) {
    Validate.notNull(actionRawData, "actionData is null");
    Map<String, Serializable> actionData = new HashMap<>();
    ActionType actionType;/*from   w w w.  ja  v a 2  s.c  om*/

    @SuppressWarnings("unchecked")
    Map<String, String> javaActionData = (Map<String, String>) actionRawData.get(SlangTextualKeys.JAVA_ACTION);
    @SuppressWarnings("unchecked")
    String pythonScript = (String) actionRawData.get(ScoreLangConstants.PYTHON_SCRIPT_KEY);
    boolean javaActionFound = MapUtils.isNotEmpty(javaActionData);
    boolean pythonScriptFound = StringUtils.isNotEmpty(pythonScript);

    if (javaActionFound) {
        actionType = ActionType.JAVA;
        actionData.putAll(javaActionData);
    } else if (pythonScriptFound) {
        actionType = ActionType.PYTHON;
        actionData.putAll(actionRawData);
    } else {
        // java action or python script data is missing
        throw new RuntimeException("Invalid action data");
    }

    actionData.put(ScoreLangConstants.ACTION_TYPE, actionType);
    actionData.put(ScoreLangConstants.NEXT_STEP_ID_KEY, index + 1);
    return createGeneralStep(index, ACTION_STEPS_CLASS, "doAction", actionData);
}

From source file:org.openscore.lang.compiler.SlangCompilerImpl.java

@Override
public CompilationArtifact compile(SlangSource source, String operationName, Set<SlangSource> path) {

    Executable executable = transformToExecutable(source, operationName);

    Map<String, Executable> filteredDependencies = new HashMap<>();
    //we handle dependencies only if the file has imports
    boolean hasDependencies = MapUtils.isNotEmpty(executable.getDependencies())
            && executable.getType().equals(SlangTextualKeys.FLOW_TYPE);
    if (hasDependencies) {
        Validate.notEmpty(path,/*w  w w  .  j  a va2  s. co m*/
                "Source " + source.getName() + " has dependencies but no path was given to the compiler");
        Validate.noNullElements(path, "Source " + source.getName() + " has empty dependencies");

        //we transform also all of the files in the given path to model objects
        Map<String, Executable> pathExecutables = transformDependencies(path);

        //we add the current executable since a dependency can require it
        List<Executable> availableExecutables = new ArrayList<>(pathExecutables.values());
        availableExecutables.add(executable);

        //than we match the references to the actual dependencies
        filteredDependencies = dependenciesHelper.matchReferences(executable, availableExecutables);
    }

    //next we create an execution plan for the required executable
    ExecutionPlan executionPlan = compileToExecutionPlan(executable);

    //and also create execution plans for all other dependencies
    Map<String, ExecutionPlan> dependencies = convertMap(filteredDependencies,
            new Converter<Executable, ExecutionPlan>() {
                @Override
                public ExecutionPlan convert(Executable compiledExecutable) {
                    return compileToExecutionPlan(compiledExecutable);
                }
            });

    return new CompilationArtifact(executionPlan, dependencies, executable.getInputs());
}

From source file:org.openscore.lang.compiler.utils.ExecutableBuilder.java

public Executable transformToExecutable(ParsedSlang parsedSlang, String execName,
        Map<String, Object> executableRawData) {

    Validate.notEmpty(executableRawData,
            "Error compiling " + parsedSlang.getName() + ". Executable data for: " + execName + " is empty");
    Validate.notNull(parsedSlang, "Slang source for " + execName + " is null");

    Map<String, Serializable> preExecutableActionData = new HashMap<>();
    Map<String, Serializable> postExecutableActionData = new HashMap<>();

    transformersHandler.validateKeyWords(execName, executableRawData,
            ListUtils.union(preExecTransformers, postExecTransformers), execAdditionalKeywords);

    preExecutableActionData.putAll(transformersHandler.runTransformers(executableRawData, preExecTransformers));
    postExecutableActionData//from ww  w  .  j a v  a 2 s . c  o m
            .putAll(transformersHandler.runTransformers(executableRawData, postExecTransformers));

    @SuppressWarnings("unchecked")
    List<Input> inputs = (List<Input>) preExecutableActionData.remove(SlangTextualKeys.INPUTS_KEY);
    @SuppressWarnings("unchecked")
    List<Output> outputs = (List<Output>) postExecutableActionData.remove(SlangTextualKeys.OUTPUTS_KEY);
    @SuppressWarnings("unchecked")
    List<Result> results = (List<Result>) postExecutableActionData.remove(SlangTextualKeys.RESULTS_KEY);

    String namespace = parsedSlang.getNamespace();
    Map<String, String> imports = parsedSlang.getImports();
    resolveSystemProperties(inputs, imports);
    Map<String, SlangFileType> dependencies;
    switch (parsedSlang.getType()) {
    case FLOW:

        if (!executableRawData.containsKey(SlangTextualKeys.WORKFLOW_KEY)) {
            throw new RuntimeException("Error compiling " + parsedSlang.getName() + ". Flow: " + execName
                    + " has no workflow property");
        }
        LinkedHashMap<String, Map<String, Object>> workFlowRawData;
        try {
            workFlowRawData = (LinkedHashMap) executableRawData.get(SlangTextualKeys.WORKFLOW_KEY);
        } catch (ClassCastException ex) {
            throw new RuntimeException("Flow: '" + execName
                    + "' syntax is illegal.\nBelow 'workflow' property there should be a map of tasks and not a list");
        }
        if (MapUtils.isEmpty(workFlowRawData)) {
            throw new RuntimeException("Error compiling " + parsedSlang.getName() + ". Flow: " + execName
                    + " has no workflow data");
        }

        Workflow onFailureWorkFlow = null;
        LinkedHashMap<String, Map<String, Object>> onFailureData;
        try {
            onFailureData = (LinkedHashMap) workFlowRawData.remove(SlangTextualKeys.ON_FAILURE_KEY);
        } catch (ClassCastException ex) {
            throw new RuntimeException("Flow: '" + execName
                    + "' syntax is illegal.\nBelow 'on_failure' property there should be a map of tasks and not a list");
        }
        if (MapUtils.isNotEmpty(onFailureData)) {
            onFailureWorkFlow = compileWorkFlow(onFailureData, imports, null, true);
        }

        Workflow workflow = compileWorkFlow(workFlowRawData, imports, onFailureWorkFlow, false);
        //todo: add system properties dependencies?
        dependencies = fetchDirectTasksDependencies(workflow);
        return new Flow(preExecutableActionData, postExecutableActionData, workflow, namespace, execName,
                inputs, outputs, results, dependencies);

    case OPERATIONS:
        Map<String, Object> actionRawData;
        try {
            actionRawData = (Map<String, Object>) executableRawData.get(SlangTextualKeys.ACTION_KEY);
        } catch (ClassCastException ex) {
            throw new RuntimeException("Operation: '" + execName
                    + "' syntax is illegal.\nBelow 'action' property there should be a map of values such as: 'python_script:' or 'java_action:'");
        }

        if (MapUtils.isEmpty(actionRawData)) {
            throw new RuntimeException("Error compiling " + parsedSlang.getName() + ". Operation: " + execName
                    + " has no action data");
        }
        Action action = compileAction(actionRawData);
        //todo: add system properties dependencies?
        dependencies = new HashMap<>();
        return new Operation(preExecutableActionData, postExecutableActionData, action, namespace, execName,
                inputs, outputs, results, dependencies);
    default:
        throw new RuntimeException(
                "Error compiling " + parsedSlang.getName() + ". It is not of flow or operations type");
    }
}

From source file:org.openscore.lang.compiler.utils.ExecutionStepFactory.java

public ExecutionStep createActionStep(Long index, Map<String, Serializable> actionRawData) {
    Validate.notNull(actionRawData, "actionData is null");
    Map<String, Serializable> actionData = new HashMap<>();
    @SuppressWarnings("unchecked")
    Map<String, String> javaActionData = (Map<String, String>) actionRawData
            .remove(SlangTextualKeys.JAVA_ACTION);
    ActionType actionType = ActionType.PYTHON;
    if (MapUtils.isNotEmpty(javaActionData)) {
        actionType = ActionType.JAVA;/*from  ww w. j a va  2s .c om*/
        actionData.putAll(javaActionData);
    }
    actionData.putAll(actionRawData);
    actionData.put(ScoreLangConstants.ACTION_TYPE, actionType);
    actionData.put(ScoreLangConstants.NEXT_STEP_ID_KEY, index + 1);
    return createGeneralStep(index, ACTION_STEPS_CLASS, "doAction", actionData);
}

From source file:org.openscore.lang.runtime.bindings.OutputsBinding.java

public Map<String, String> bindOutputs(Map<String, Serializable> inputs, Map<String, String> actionReturnValues,
        List<Output> possibleOutputs) {

    Map<String, String> outputs = new LinkedHashMap<>();
    if (possibleOutputs != null) {
        for (Output output : possibleOutputs) {
            String outputKey = output.getName();
            String outputExpr = output.getExpression();
            if (outputExpr != null) {
                //construct script context
                Map<String, Serializable> scriptContext = new HashMap<>();
                //put action outputs
                scriptContext.putAll(actionReturnValues);
                //put operation inputs as a map
                if (MapUtils.isNotEmpty(inputs)) {
                    scriptContext.put(BIND_OUTPUT_FROM_INPUTS_KEY, (Serializable) inputs);
                }//  www  . j a va 2s . co m

                //evaluate expression
                Serializable scriptResult = scriptEvaluator.evalExpr(outputExpr, scriptContext);

                if (scriptResult != null) {
                    try {
                        outputs.put(outputKey, (String) scriptResult);
                    } catch (ClassCastException ex) {
                        throw new RuntimeException(
                                "The output expression " + outputExpr + " does not return String value", ex);
                    }
                }
            } else {
                throw new RuntimeException("Output: " + outputKey + " has no expression");
            }
        }
    }
    return outputs;
}

From source file:org.openscore.lang.runtime.bindings.ResultsBinding.java

/**
 * Resolves the result name of an executable based on the list of all the possible results, the run context
 * and in the case of a flow, also the already preset result name
 *
 * Throws a runtime exception in the following cases:
 * 1. No possible results were given//from w  ww.  ja  v a2  s.c  om
 * 2. In the case of a flow, the preset result name is not present in the possible results list
 * 3. One or more of the results contains an illegal expression - not evaluated to true\false value
 * 4. No result was resolved - none of the results expression returned true
 *
 * @param inputs the executable's inputs
 * @param context the run context
 * @param possibleResults list of all the possible Result objects of the executable
 * @param presetResult a given result name. Will be not null only in the case of resolving a result of a flow
 * @return the resolved result name
 */
public String resolveResult(Map<String, Serializable> inputs, Map<String, String> context,
        List<Result> possibleResults, String presetResult) {

    // We must have possible results
    if (CollectionUtils.isEmpty(possibleResults)) {
        throw new RuntimeException("No results were found");
    }

    // In case of calculating the result of a flow, we already have a preset result from the last task of the flow,
    // we look for it in the possible results of the flow.
    // If the flow has it as a possible result, we return it as the resolved result.
    // If not, we throw an exception
    if (presetResult != null) {
        for (Result possibleResult : possibleResults) {
            if (presetResult.equals(possibleResult.getName())) {
                return presetResult;
            }
        }
        throw new RuntimeException("Result: " + presetResult
                + " that was calculated in the last task is not a possible result of the flow.");
    }

    // In the case of operation, we resolve the result by searching for the first result with a true expression
    // An empty expression passes as true
    for (Result result : possibleResults) {
        String expression = result.getExpression();
        // If the answer has no expression, we treat it as a true expression, and choose it
        if (StringUtils.isEmpty(expression)) {
            return result.getName();
        }
        //construct script context
        Map<String, Serializable> scriptContext = new HashMap<>();
        //put action outputs
        scriptContext.putAll(context);
        //put executable inputs as a map
        if (MapUtils.isNotEmpty(inputs)) {
            scriptContext.put(BIND_OUTPUT_FROM_INPUTS_KEY, (Serializable) inputs);
        }

        try {
            Boolean evaluatedResult = (Boolean) scriptEvaluator.evalExpr(expression, scriptContext);
            if (evaluatedResult == null) {
                throw new RuntimeException("Expression of the operation result: " + expression
                        + " cannot be evaluated correctly to true or false value");
            }
            if (evaluatedResult) {
                return result.getName();
            }
        } catch (ClassCastException ex) {
            throw new RuntimeException("Error resolving the result. The expression " + expression
                    + " does not return boolean value", ex);
        }
    }
    throw new RuntimeException("No possible result was resolved");
}

From source file:org.tdar.core.bean.resource.InformationResource.java

@Override
@XmlTransient//w  w w .ja v  a2  s .co  m
public String getAdditonalKeywords() {
    StringBuilder sb = new StringBuilder();
    sb.append(getCopyLocation()).append(" ").append(date);
    if (getResourceProviderInstitution() != null) {
        sb.append(" ").append(getResourceProviderInstitution().getName());
    }
    sb.append(" ").append(getPublisherName());
    sb.append(" ").append(getDoi());
    if (MapUtils.isNotEmpty(relatedDatasetData)) {
        for (String v : relatedDatasetData.values()) {
            sb.append(v);
            sb.append(" ");
        }
    }

    if (CollectionUtils.isNotEmpty(getActiveInformationResourceFiles())) {
        for (InformationResourceFile file : getActiveInformationResourceFiles()) {
            sb.append(file.getFilename());
            sb.append(" ");
            sb.append(file.getDescription());
            sb.append(" ");
        }
    }

    // if (getProject() != null) {
    // getProject().getTitle();
    // }
    return sb.toString();
}

From source file:org.tdar.struts.action.TdarActionSupport.java

public boolean isErrorWarningSectionVisible() {
    if (hideExceptionArea) {
        return false;
    }/*from   w  ww  .j a va 2s. c  o m*/

    if (CollectionUtils.isNotEmpty(getActionErrors())) {
        return true;
    }
    if (MapUtils.isNotEmpty(getFieldErrors())) {
        return true;
    }
    if (this instanceof AbstractInformationResourceController) {
        AbstractInformationResourceController<?> cast = (AbstractInformationResourceController<?>) this;
        if (cast.authorize() && CollectionUtils.isNotEmpty(cast.getHistoricalFileErrors())) {
            return true;
        }

    }
    return false;
}