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

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

Introduction

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

Prototype

public static <E> List<E> union(final List<? extends E> list1, final List<? extends E> list2) 

Source Link

Document

Returns a new list containing the second list appended to the first list.

Usage

From source file:com.ejisto.util.collector.MockedFieldCollectorTest.java

@Test
public void testFinisher() throws Exception {
    Map<String, List<MockedField>> map = new TreeMap<>();
    map.put("com.ejisto.test.Test", ListUtils.union(testClassFields, otherFields));
    map.put("com.ejisto.test2.Test", test2ClassFields);
    final FieldNode result = instance.finisher().apply(map);
    assertNotNull(result);/*from  w w w .j a v  a 2s. c  o m*/
    assertTrue(result.isRoot());
    assertFalse(result.getChildren().isEmpty());
    assertEquals(2, result.getChildren().size()); // /ejisto-test and /another-one
    FieldNode anotherOne = result.getChildren().first();
    assertNotNull(anotherOne);
    assertEquals("/another-one", anotherOne.getLabel());
    assertFalse(anotherOne.getChildren().isEmpty());
    assertEquals(1, anotherOne.getChildren().size());
    FieldNode ejistoTest = result.getChildren().last();
    assertEquals("/ejisto-test", ejistoTest.getLabel());
    assertFalse(ejistoTest.getChildren().isEmpty());
    assertEquals(1, ejistoTest.getChildren().size());
}

From source file:it.baywaylabs.jumpersumo.utility.Finder.java

/**
 * This method joins commands list in one List.
 *
 * @param params List to join.//from  ww  w .j a  v a 2  s.c  o m
 * @return List of all commands.
 */
public List<String> joinListCommands(List<String>... params) {

    List<String> result = new ArrayList<String>();
    if (params.length != 0) {
        for (int i = 0; i < params.length; i++)
            result = ListUtils.union(result, params[i]);
    }

    return result;
}

From source file:io.cloudslang.lang.compiler.modeller.ExecutableBuilder.java

public void initScopedTransformersAndKeys() {
    //executable transformers
    preExecTransformers = filterTransformers(Transformer.Scope.BEFORE_EXECUTABLE);
    postExecTransformers = filterTransformers(Transformer.Scope.AFTER_EXECUTABLE);

    //action transformers and keys
    actionTransformers = filterTransformers(Transformer.Scope.ACTION);

    allExecutableAdditionalKeywords = new ArrayList<>(executableAdditionalKeywords.size()
            + operationAdditionalKeywords.size() + flowAdditionalKeywords.size());
    allExecutableAdditionalKeywords.addAll(executableAdditionalKeywords);
    allExecutableAdditionalKeywords.addAll(operationAdditionalKeywords);
    allExecutableAdditionalKeywords.addAll(flowAdditionalKeywords);

    // keys excluding each other
    executableConstraintGroups = new ArrayList<>();
    executableConstraintGroups.add(ListUtils.union(singletonList(WORKFLOW_KEY), operationAdditionalKeywords));

    //step transformers
    preStepTransformers = filterTransformers(Transformer.Scope.BEFORE_STEP);
    postStepTransformers = filterTransformers(Transformer.Scope.AFTER_STEP);

    final List<Transformer> tempPreStepTransformers = filterTransformers(Transformer.Scope.BEFORE_STEP);
    final List<Transformer> tempPostStepTransformers = filterTransformers(Transformer.Scope.AFTER_STEP);

    preStepTransformers = tempPreStepTransformers.stream().filter(t -> t.getType() != Transformer.Type.EXTERNAL)
            .collect(Collectors.toList());

    postStepTransformers = tempPostStepTransformers.stream()
            .filter(t -> t.getType() != Transformer.Type.EXTERNAL).collect(Collectors.toList());

    externalPreStepTransformers = tempPreStepTransformers.stream()
            .filter(t -> t.getType() != Transformer.Type.INTERNAL).collect(Collectors.toList());

    externalPostStepTransformers = tempPostStepTransformers.stream()
            .filter(t -> t.getType() != Transformer.Type.INTERNAL).collect(Collectors.toList());

}

From source file:io.cloudslang.lang.compiler.modeller.ExecutableBuilder.java

public ExecutableModellingResult transformToExecutable(ParsedSlang parsedSlang,
        Map<String, Object> executableRawData, SensitivityLevel sensitivityLevel) {
    List<RuntimeException> errors = new ArrayList<>();
    String execName = preCompileValidator.validateExecutableRawData(parsedSlang, executableRawData, errors);
    String workerGroup = (String) executableRawData.get(SlangTextualKeys.WORKER_GROUP);

    errors.addAll(preCompileValidator.checkKeyWords(execName, "", executableRawData,
            ListUtils.union(preExecTransformers, postExecTransformers),
            ParsedSlang.Type.DECISION.equals(parsedSlang.getType()) ? executableAdditionalKeywords
                    : allExecutableAdditionalKeywords,
            executableConstraintGroups));

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

    String errorMessagePrefix = "For " + parsedSlang.getType().toString().toLowerCase() + " '" + execName
            + "' syntax is illegal.\n";
    preExecutableActionData.putAll(transformersHandler.runTransformers(executableRawData, preExecTransformers,
            errors, errorMessagePrefix, sensitivityLevel));
    postExecutableActionData.putAll(transformersHandler.runTransformers(executableRawData, postExecTransformers,
            errors, errorMessagePrefix, sensitivityLevel));

    @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);
    results = results == null ? new ArrayList<Result>() : results;

    String namespace = parsedSlang.getNamespace();
    Set<String> systemPropertyDependencies = null;

    Executable executable;/*from  w w w . jav  a2  s .  c o m*/
    boolean isSeqAction = false;

    switch (parsedSlang.getType()) {
    case FLOW:
        resultsTransformer.addDefaultResultsIfNeeded((List) executableRawData.get(SlangTextualKeys.RESULTS_KEY),
                ExecutableType.FLOW, results, errors);

        Map<String, String> imports = parsedSlang.getImports();

        List<Map<String, Map<String, Object>>> workFlowRawData = preCompileValidator
                .validateWorkflowRawData(parsedSlang, executableRawData.get(WORKFLOW_KEY), execName, errors);

        Workflow onFailureWorkFlow = getOnFailureWorkflow(workFlowRawData, imports, errors, namespace, execName,
                sensitivityLevel);

        WorkflowModellingResult workflowModellingResult = compileWorkFlow(workFlowRawData, imports,
                onFailureWorkFlow, false, namespace, sensitivityLevel);
        errors.addAll(workflowModellingResult.getErrors());
        Workflow workflow = workflowModellingResult.getWorkflow();

        preCompileValidator.validateResultsHaveNoExpression(results, execName, errors);

        Pair<Set<String>, Set<String>> pair = fetchDirectStepsDependencies(workflow);
        Set<String> executableDependencies = pair.getLeft();
        Set<String> externalExecutableDependencies = pair.getRight();
        try {
            systemPropertyDependencies = dependenciesHelper.getSystemPropertiesForFlow(inputs, outputs, results,
                    workflow.getSteps());

        } catch (RuntimeException ex) {
            errors.add(ex);
        }
        executable = new Flow(preExecutableActionData, postExecutableActionData, workflow, namespace, execName,
                workerGroup, inputs, outputs, results, executableDependencies, externalExecutableDependencies,
                systemPropertyDependencies);

        break;

    case OPERATION:
        resultsTransformer.addDefaultResultsIfNeeded((List) executableRawData.get(SlangTextualKeys.RESULTS_KEY),
                ExecutableType.OPERATION, results, errors);

        Map<String, Object> actionRawData = getActionRawData(executableRawData, errors, parsedSlang, execName);
        ActionModellingResult actionModellingResult = compileAction(actionRawData, sensitivityLevel);
        errors.addAll(actionModellingResult.getErrors());
        final Action action = actionModellingResult.getAction();
        executableDependencies = new HashSet<>();

        isSeqAction = actionRawData.containsKey(SlangTextualKeys.SEQ_ACTION_KEY);
        if (!isSeqAction) {
            preCompileValidator.validateResultTypes(results, execName, errors);
            preCompileValidator.validateDefaultResult(results, execName, errors);
        } else {
            preCompileValidator.validateResultsHaveNoExpression(results, execName, errors);
            preCompileValidator.validateResultsWithWhitelist(results, seqSupportedResults, execName, errors);
        }

        try {
            systemPropertyDependencies = dependenciesHelper.getSystemPropertiesForOperation(inputs, outputs,
                    results);

        } catch (RuntimeException ex) {
            errors.add(ex);
        }
        executable = new Operation(preExecutableActionData, postExecutableActionData, action, namespace,
                execName, inputs, outputs, results, executableDependencies, systemPropertyDependencies);

        break;

    case DECISION:
        resultsTransformer.addDefaultResultsIfNeeded((List) executableRawData.get(SlangTextualKeys.RESULTS_KEY),
                ExecutableType.DECISION, results, errors);

        preCompileValidator.validateResultTypes(results, execName, errors);
        preCompileValidator.validateDecisionResultsSection(executableRawData, execName, errors);
        preCompileValidator.validateDefaultResult(results, execName, errors);

        try {
            systemPropertyDependencies = dependenciesHelper.getSystemPropertiesForDecision(inputs, outputs,
                    results);
        } catch (RuntimeException ex) {
            errors.add(ex);
        }
        executable = new Decision(preExecutableActionData, postExecutableActionData, namespace, execName,
                inputs, outputs, results, Collections.<String>emptySet(), systemPropertyDependencies);

        break;

    default:
        throw new RuntimeException("Error compiling " + parsedSlang.getName()
                + ". It is not of flow, operations or decision type");
    }

    if (!isSeqAction && outputs != null) {
        errors.addAll(validateOutputs(outputs));
    }

    return preCompileValidator.validateResult(parsedSlang, execName,
            new ExecutableModellingResult(executable, errors));
}

From source file:de.tor.tribes.util.algo.BruteForce.java

@Override
public List<TroopMovement> calculateAttacks(HashMap<UnitHolder, List<Village>> pSources,
        HashMap<UnitHolder, List<Village>> pFakes, List<Village> pTargets, List<Village> pFakeTargets,
        HashMap<Village, Integer> pMaxAttacksTable, TimeFrame pTimeFrame, boolean pFakeOffTargets) {

    List<Village> allTargets = Arrays.asList(pTargets.toArray(new Village[pTargets.size()]));
    List<Village> allFakeTargets = Arrays.asList(pFakeTargets.toArray(new Village[pFakeTargets.size()]));

    HashMap<Village, HashMap<UnitHolder, List<Village>>> attacks = new HashMap<>();
    logger.debug("Assigning offs");
    logText("Starte zufllige Berechnung");

    int maxStatus = allTargets.size() + allFakeTargets.size();
    int currentStatus = 0;

    // <editor-fold defaultstate="collapsed" desc=" Assign Offs">
    logInfo(" Starte Berechnung fr Offs");
    for (UnitHolder unit : pSources.keySet()) {
        logInfo(" - Starte Berechnung fr Einheit '" + unit.getName() + "'");
        List<Village> sources = pSources.get(unit);

        if (sources != null) {
            logInfo(" - Verwende " + sources.size() + " Herkunftsdrfer");
            for (Village source : sources) {

                //time when the attacks should arrive
                Village vTarget = null;/*w  ww. j  ava  2s .  c  o  m*/

                //distribute targets randomly
                Collections.shuffle(pTargets);
                currentStatus = allTargets.size() - pTargets.size();
                updateStatus(currentStatus, maxStatus);
                //search all targets
                logInfo(" - Teste " + pTargets.size() + " mgliche Ziele");
                for (Village v : pTargets.toArray(new Village[pTargets.size()])) {
                    if (isAborted()) {
                        return new LinkedList<>();
                    }
                    int maxAttacksPerVillage = pMaxAttacksTable.get(v);
                    double time = DSCalculator.calculateMoveTimeInSeconds(source, v, unit.getSpeed());
                    if (unit.getPlainName().equals("snob")) {
                        if (DSCalculator.calculateDistance(source, v) > ServerSettings.getSingleton()
                                .getSnobRange()) {
                            //continue with the next destination Village
                            continue;
                        }
                    }

                    long runtime = (long) time * 1000;
                    //check if attack is somehow possible
                    if (pTimeFrame.isMovementPossible(runtime)) {
                        //only calculate if time is in time frame
                        //get list of source villages for current target
                        HashMap<UnitHolder, List<Village>> attacksForVillage = attacks.get(v);
                        if (attacksForVillage == null) {
                            //create new table of attacks
                            attacksForVillage = new HashMap<>();
                            List<Village> sourceList = new LinkedList<>();
                            logInfo("   * Neue Truppenbewegung: " + source + " -> " + v);
                            sourceList.add(source);
                            attacksForVillage.put(unit, sourceList);
                            attacks.put(v, attacksForVillage);
                            vTarget = v;
                        } else {
                            int currentAttacks = 0;
                            for (List<Village> l : attacksForVillage.values()) {
                                currentAttacks += l.size();
                            }
                            //there are already attacks on this village
                            if (currentAttacks < maxAttacksPerVillage) {
                                //more attacks on this village are allowed
                                boolean added = false;
                                //max number of attacks neither for villages nor for player reached
                                List<Village> attsPerUnit = attacksForVillage.get(unit);
                                if (attsPerUnit != null) {
                                    if (!attsPerUnit.contains(source) || (unit
                                            .equals(DataHolder.getSingleton().getUnitByPlainName("snob"))
                                            && multipleSameSnobsAllowed())) {
                                        //only add source if it does not attack current target yet
                                        added = true;
                                        logInfo("   * Neue Truppenbewegung: " + source + " -> " + v);
                                        attsPerUnit.add(source);
                                    }
                                } else {
                                    attsPerUnit = new LinkedList<>();
                                    //only add source if it does not attack current target yet
                                    added = true;
                                    logInfo("   * Neue Truppenbewegung: " + source + " -> " + v);
                                    attsPerUnit.add(source);
                                    attacksForVillage.put(unit, attsPerUnit);
                                }
                                if (added) {
                                    //only increment attack count if source was added
                                    vTarget = v;

                                    //check if last missing attack was added. 
                                    if (currentAttacks + 1 == maxAttacksPerVillage) {
                                        logInfo("   * Entferne vollstndiges Ziel " + v);
                                        pTargets.remove(v);
                                    }

                                } else {
                                    vTarget = null;
                                }
                            } else {
                                //max number of attacks per village reached, continue search
                                logInfo("   * Entferne vollstndiges Ziel " + v);
                                pTargets.remove(v);
                                vTarget = null;
                            }
                        }
                    }

                    if (vTarget != null) {
                        break;
                    }
                }

                if (vTarget == null) {
                    logInfo(" - Keine Ziele fr Herkunftsdorf " + source + " gefunden");
                }
            }
        } else {
            logInfo(" - Keine Herkunftsdrfer fr aktuelle Einheit");
        }
    }
    // </editor-fold>

    if (pFakeOffTargets) {
        /*
         *  why would we do this? We should allow one fake for each missing off, so we can simply use pTargets as is?
         *  
         logger.debug("Removing assigned off targets from fake list");
         Enumeration<Village> targets = attacks.keys();
         while (targets.hasMoreElements()) {
        Village target = targets.nextElement();
        pTargets.remove(target);
         }*/
        logger.debug("Keeping remaining Off targets for fake search");
    } else {
        //clear target list
        pTargets.clear();
    }

    //adding fake targets
    for (Village fakeTarget : pFakeTargets) {
        pTargets.add(fakeTarget);
    }
    logger.debug("Assigning fakes");
    logText(" Starte Berechnung fr Fakes.");
    // <editor-fold defaultstate="collapsed" desc=" Assign fakes">
    HashMap<Village, HashMap<UnitHolder, List<Village>>> fakes = new HashMap<>();
    for (UnitHolder unit : pFakes.keySet()) {
        logInfo(" - Starte Berechnung fr Einheit '" + unit.getName() + "'");
        List<Village> sources = pFakes.get(unit);

        if (sources != null) {
            logInfo(" - Verwende " + sources.size() + " Herkunftsdrfer");
            for (Village source : sources) {

                //time when the attacks should arrive
                Village vTarget = null;

                //distribute targets randomly
                Collections.shuffle(pTargets);
                currentStatus = allTargets.size() + allFakeTargets.size() - pTargets.size();
                updateStatus(currentStatus, maxStatus);
                //search all targets
                logInfo(" - Teste " + pTargets.size() + " mgliche Ziele");
                for (Village v : pTargets.toArray(new Village[pTargets.size()])) {
                    if (isAborted()) {
                        return new LinkedList<>();
                    }
                    int maxAttacksPerVillage = pMaxAttacksTable.get(v);
                    double time = DSCalculator.calculateMoveTimeInSeconds(source, v, unit.getSpeed());
                    if (unit.getPlainName().equals("snob")) {
                        if (DSCalculator.calculateDistance(source, v) > ServerSettings.getSingleton()
                                .getSnobRange()) {
                            //continue with the next destination Village
                            continue;
                        }
                    }

                    long runtime = (long) time * 1000;
                    //check if attack is somehow possible
                    if (pTimeFrame.isMovementPossible(runtime)) {
                        //only calculate if time is in time frame
                        //get list of source villages for current target
                        HashMap<UnitHolder, List<Village>> attacksForVillage = attacks.get(v);
                        HashMap<UnitHolder, List<Village>> fakesForVillage = fakes.get(v);
                        if (attacksForVillage == null) {
                            //create empty table of attacks (will stay empty, but is used for maxAttacks calculation)
                            attacksForVillage = new HashMap<>();
                            List<Village> sourceList = new LinkedList<>();
                            attacksForVillage.put(unit, sourceList);
                        }
                        if (fakesForVillage == null) {
                            //create new table of fakes 
                            fakesForVillage = new HashMap<>();
                            List<Village> sourceList = new LinkedList<>();
                            logInfo("   * Neue Truppenbewegung: " + source + " -> " + v);
                            sourceList.add(source);
                            fakesForVillage.put(unit, sourceList);
                            fakes.put(v, fakesForVillage);
                            vTarget = v;
                        } else {
                            int currentAttacks = 0;
                            for (List<Village> listV : attacksForVillage.values()) {
                                currentAttacks += listV.size();
                            }
                            int currentFakes = 0;
                            for (List<Village> listV : fakesForVillage.values()) {
                                currentFakes += listV.size();
                            }

                            //there are already attacks or fakes on this village
                            if (currentAttacks + currentFakes < maxAttacksPerVillage) {
                                //more attacks on this village are allowed
                                boolean added = false;
                                //max number of attacks neither for villages nor for player reached
                                List<Village> attsPerUnit = attacksForVillage.get(unit);
                                List<Village> fakesPerUnit = fakesForVillage.get(unit);
                                if (fakesPerUnit != null) {
                                    if (!attsPerUnit.contains(source)
                                            && (attsPerUnit == null || !attsPerUnit.contains(source))) {
                                        //only add source if it does not attack current target yet
                                        added = true;
                                        logInfo("   * Neue Truppenbewegung: " + source + " -> " + v);
                                        fakesPerUnit.add(source);
                                    }
                                } else {
                                    fakesPerUnit = new LinkedList<>();
                                    //only add source if it does not attack current target yet
                                    added = true;
                                    logInfo("   * Neue Truppenbewegung: " + source + " -> " + v);
                                    fakesPerUnit.add(source);
                                    fakesForVillage.put(unit, attsPerUnit);
                                }
                                if (added) {
                                    //only increment attack count if source was added
                                    vTarget = v;

                                    //check if last missing attack was added. 
                                    if (currentAttacks + currentFakes + 1 == maxAttacksPerVillage) {
                                        logInfo("   * Entferne vollstndiges Ziel " + v);
                                        pTargets.remove(v);
                                    }

                                } else {
                                    vTarget = null;
                                }
                            } else {
                                //max number of attacks per village reached, continue search
                                logInfo("   * Entferne vollstndiges Ziel " + v);
                                pTargets.remove(v);
                                vTarget = null;
                            }
                        }
                    }

                    if (vTarget != null) {
                        break;
                    }
                }

                if (vTarget == null) {
                    logInfo(" - Keine Ziele fr Herkunftsdorf " + source + " gefunden");
                }
            }
        } else {
            logInfo(" - Keine Herkunftsdrfer fr aktuelle Einheit");
        }
    }

    updateStatus(maxStatus, maxStatus);
    // </editor-fold>

    logText(" - Erstelle Ergebnisliste");
    //convert to result list
    List<TroopMovement> movements = new LinkedList<>();
    logger.debug(" - adding offs");

    logText(String.format(" %d Offs berechnet", attacks.size()));
    for (Village target : allTargets) {
        HashMap<UnitHolder, List<Village>> sourcesForTarget = attacks.get(target);
        TroopMovement f = new TroopMovement(target, pMaxAttacksTable.get(target), Attack.CLEAN_TYPE);

        if (sourcesForTarget != null) {
            for (UnitHolder sourceUnit : sourcesForTarget.keySet()) {
                List<Village> unitVillages = attacks.get(target).get(sourceUnit);
                for (Village source : unitVillages) {
                    f.addOff(sourceUnit, source);
                }
            }
        }
        if (sourcesForTarget == null && fakes.get(target) != null) {
            //ignore Off targets, when there are Fakes assigned and no Offs
            continue;
        }
        movements.add(f);
    }

    logger.debug(" - adding fakes");
    logText(String.format(" %d Fakes berechnet", fakes.size()));

    for (Village target : (List<Village>) ListUtils.union(allFakeTargets, allTargets)) {
        HashMap<UnitHolder, List<Village>> sourcesForTarget = fakes.get(target);
        TroopMovement f = new TroopMovement(target, pMaxAttacksTable.get(target), Attack.FAKE_TYPE);
        if (sourcesForTarget != null) {
            for (UnitHolder sourceUnit : sourcesForTarget.keySet()) {
                List<Village> unitVillages = fakes.get(target).get(sourceUnit);
                for (Village source : unitVillages) {
                    f.addOff(sourceUnit, source);
                }
            }
        }
        if (sourcesForTarget == null && allTargets.contains(target)) {
            //ignore Off targets, where no Fakes were assigned
            continue;
        }
        movements.add(f);
    }

    logText("Berechnung abgeschlossen.");
    return movements;
}

From source file:io.cloudslang.lang.compiler.modeller.ExecutableBuilder.java

private StepModellingResult compileStep(String stepName, Map<String, Object> stepRawData, String defaultSuccess,
        Map<String, String> imports, String defaultFailure, String namespace, String onFailureStepName,
        boolean onFailureSection, SensitivityLevel sensitivityLevel) {

    List<RuntimeException> errors = new ArrayList<>();
    if (MapUtils.isEmpty(stepRawData)) {
        stepRawData = new HashMap<>();
        errors.add(new RuntimeException("Step: " + stepName + " has no data"));
    }/*from www. jav a2  s.c  o  m*/

    final boolean isExternal = stepRawData.containsKey(DO_EXTERNAL_KEY);
    final List<Transformer> localPreStepTransformers = isExternal ? externalPreStepTransformers
            : preStepTransformers;
    final List<Transformer> localPostStepTransformers = isExternal ? externalPostStepTransformers
            : postStepTransformers;

    Map<String, Serializable> preStepData = new HashMap<>();
    Map<String, Serializable> postStepData = new HashMap<>();

    errors.addAll(preCompileValidator.checkKeyWords(stepName, "", stepRawData,
            ListUtils.union(localPreStepTransformers, localPostStepTransformers), stepAdditionalKeyWords,
            null));

    String errorMessagePrefix = "For step '" + stepName + "' syntax is illegal.\n";
    preStepData.putAll(transformersHandler.runTransformers(stepRawData, localPreStepTransformers, errors,
            errorMessagePrefix, sensitivityLevel));
    postStepData.putAll(transformersHandler.runTransformers(stepRawData, localPostStepTransformers, errors,
            errorMessagePrefix, sensitivityLevel));

    replaceOnFailureReference(postStepData, onFailureStepName);

    String workerGroup = (String) stepRawData.get(SlangTextualKeys.WORKER_GROUP);

    String refId = "";
    final List<Argument> arguments = getArgumentsFromDoStep(preStepData);
    final Map<String, Object> doRawData = getRawDataFromDoStep(stepRawData);

    if (MapUtils.isNotEmpty(doRawData)) {
        try {
            String refString = doRawData.keySet().iterator().next();
            refId = resolveReferenceId(refString, imports, namespace, preStepData);
        } catch (RuntimeException rex) {
            errors.add(rex);
        }
    }

    List<Map<String, String>> navigationStrings = getNavigationStrings(postStepData, defaultSuccess,
            defaultFailure, errors);

    Step step = createStep(stepName, onFailureSection, preStepData, postStepData, arguments, workerGroup, refId,
            navigationStrings);
    return new StepModellingResult(step, errors);
}

From source file:org.openscore.lang.compiler.modeller.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, null);

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

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

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

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

        Workflow onFailureWorkFlow = null;
        List<Map<String, Map<String, Object>>> onFailureData;
        Iterator<Map<String, Map<String, Object>>> tasksIterator = workFlowRawData.iterator();
        while (tasksIterator.hasNext()) {
            Map<String, Map<String, Object>> taskData = tasksIterator.next();
            String taskName = taskData.keySet().iterator().next();
            if (taskName.equals(ON_FAILURE_KEY)) {
                try {
                    onFailureData = (List<Map<String, Map<String, Object>>>) taskData.values().iterator()
                            .next();
                } catch (ClassCastException ex) {
                    throw new RuntimeException("Flow: '" + execName
                            + "' syntax is illegal.\nBelow 'on_failure' property there should be a list of tasks and not a map");
                }
                if (CollectionUtils.isNotEmpty(onFailureData)) {
                    onFailureWorkFlow = compileWorkFlow(onFailureData, imports, null, true);
                }
                tasksIterator.remove();
                break;
            }
        }

        Workflow workflow = compileWorkFlow(workFlowRawData, imports, onFailureWorkFlow, false);
        dependencies = fetchDirectTasksDependencies(workflow);
        return new Flow(preExecutableActionData, postExecutableActionData, workflow, namespace, execName,
                inputs, outputs, results, dependencies);

    case OPERATION:
        Map<String, Object> actionRawData;
        try {
            actionRawData = (Map<String, Object>) executableRawData.get(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);
        dependencies = new HashSet<>();
        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.modeller.ExecutableBuilder.java

private Task compileTask(String taskName, Map<String, Object> taskRawData, String defaultSuccess,
        Map<String, String> imports, String defaultFailure) {

    if (MapUtils.isEmpty(taskRawData)) {
        throw new RuntimeException("Task: " + taskName + " has no data");
    }/*from   ww w .  ja  va2s  .c  o  m*/

    Map<String, Serializable> preTaskData = new HashMap<>();
    Map<String, Serializable> postTaskData = new HashMap<>();

    transformersHandler.validateKeyWords(taskName, taskRawData,
            ListUtils.union(preTaskTransformers, postTaskTransformers), TaskAdditionalKeyWords, null);

    try {
        preTaskData.putAll(transformersHandler.runTransformers(taskRawData, preTaskTransformers));
        postTaskData.putAll(transformersHandler.runTransformers(taskRawData, postTaskTransformers));
    } catch (Exception ex) {
        throw new RuntimeException("For task: " + taskName + " syntax is illegal.\n" + ex.getMessage(), ex);
    }
    List<Input> inputs = (List<Input>) preTaskData.get(DO_KEY);
    @SuppressWarnings("unchecked")
    Map<String, Object> doRawData = (Map<String, Object>) taskRawData.get(DO_KEY);
    if (MapUtils.isEmpty(doRawData)) {
        throw new RuntimeException("Task: \'" + taskName + "\' has no reference information");
    }
    String refString = doRawData.keySet().iterator().next();
    String refId = resolveRefId(refString, imports);

    @SuppressWarnings("unchecked")
    Map<String, String> navigationStrings = (Map<String, String>) postTaskData.get(NAVIGATION_KEY);

    //default navigation
    if (MapUtils.isEmpty(navigationStrings)) {
        navigationStrings = new HashMap<>();
        navigationStrings.put(SUCCESS_RESULT, defaultSuccess);
        navigationStrings.put(FAILURE_RESULT, defaultFailure);
    }

    return new Task(taskName, preTaskData, postTaskData, inputs, navigationStrings, refId);
}

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  w w w  . j a  va 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.ExecutableBuilder.java

private Task compileTask(String taskName, Map<String, Object> taskRawData, String defaultSuccess,
        Map<String, String> imports, String defaultFailure) {

    if (MapUtils.isEmpty(taskRawData)) {
        throw new RuntimeException("Task: " + taskName + " has no data");
    }//  www . j av a2  s .c o  m

    Map<String, Serializable> preTaskData = new HashMap<>();
    Map<String, Serializable> postTaskData = new HashMap<>();

    transformersHandler.validateKeyWords(taskName, taskRawData,
            ListUtils.union(preTaskTransformers, postTaskTransformers), TaskAdditionalKeyWords);

    try {
        preTaskData.putAll(transformersHandler.runTransformers(taskRawData, preTaskTransformers));
        postTaskData.putAll(transformersHandler.runTransformers(taskRawData, postTaskTransformers));
    } catch (Exception ex) {
        throw new RuntimeException("For task: " + taskName + " syntax is illegal.\n" + ex.getMessage(), ex);
    }
    List<Input> inputs = (List<Input>) preTaskData.get(SlangTextualKeys.DO_KEY);
    resolveSystemProperties(inputs, imports);
    @SuppressWarnings("unchecked")
    Map<String, Object> doRawData = (Map<String, Object>) taskRawData.get(SlangTextualKeys.DO_KEY);
    if (MapUtils.isEmpty(doRawData)) {
        throw new RuntimeException("Task: " + taskName + " has no reference information");
    }
    String refString = doRawData.keySet().iterator().next();
    String refId = resolveRefId(refString, imports);

    @SuppressWarnings("unchecked")
    Map<String, String> navigationStrings = (Map<String, String>) postTaskData
            .get(SlangTextualKeys.NAVIGATION_KEY);

    //default navigation
    if (MapUtils.isEmpty(navigationStrings)) {
        navigationStrings = new HashMap<>();
        navigationStrings.put(SUCCESS_RESULT, defaultSuccess);
        navigationStrings.put(FAILURE_RESULT, defaultFailure);
    }

    return new Task(taskName, preTaskData, postTaskData, navigationStrings, refId);
}