Example usage for org.apache.commons.lang3.tuple ImmutableTriple ImmutableTriple

List of usage examples for org.apache.commons.lang3.tuple ImmutableTriple ImmutableTriple

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple ImmutableTriple ImmutableTriple.

Prototype

public ImmutableTriple(final L left, final M middle, final R right) 

Source Link

Document

Create a new triple instance.

Usage

From source file:org.lightjason.agentspeak.agent.IBaseAgent.java

@Override
@SafeVarargs/*from   w w w.jav  a2 s  .com*/
public final <N extends IInspector> Stream<N> inspect(final N... p_inspector) {
    if (p_inspector == null)
        return Stream.of();

    return Arrays.stream(p_inspector).parallel().map(i -> {
        i.inspectcycle(m_cycle.get());
        i.inspectsleeping(m_sleepingcycles.get());
        i.inspectbelief(m_beliefbase.stream().parallel());
        i.inspectplans(m_plans.entries().parallelStream().map(j -> new ImmutableTriple<>(j.getValue().getLeft(),
                j.getValue().getMiddle().get(), j.getValue().getRight().get())));
        i.inspectrunningplans(m_runningplans.values().parallelStream());
        i.inspectstorage(m_storage.entrySet().parallelStream());
        i.inspectrules(m_rules.values().parallelStream());
        return i;
    });
}

From source file:org.lightjason.agentspeak.language.execution.action.achievement_test.IAchievementRule.java

/**
 * execute rule from context//  w  w w .  j  av a 2s . c  om
 *
 * @param p_context execution context
 * @param p_value execution literal
 * @param p_parallel parallel execution
 * @return boolean result
 */
@SuppressWarnings("unchecked")
protected static IFuzzyValue<Boolean> execute(final IContext p_context, final ILiteral p_value,
        final boolean p_parallel) {
    // read current rules, if not exists execution fails
    final Collection<IRule> l_rules = p_context.agent().rules().get(p_value.fqnfunctor());
    if (l_rules == null)
        return CFuzzyValue.from(false);

    // first step is the unification of the caller literal, so variables will be set from the current execution context
    final ILiteral l_unified = p_value.allocate(p_context);

    // second step execute backtracking rules sequential / parallel
    return (p_parallel ? l_rules.parallelStream() : l_rules.stream()).map(i -> {

        // instantiate variables by unification of the rule literal
        final Set<IVariable<?>> l_variables = p_context.agent().unifier().literal(i.getIdentifier(), l_unified);

        // execute rule
        final IFuzzyValue<Boolean> l_return = i.execute(i.instantiate(p_context.agent(), l_variables.stream()),
                false, Collections.<ITerm>emptyList(), Collections.<ITerm>emptyList(),
                Collections.<ITerm>emptyList());

        // create rule result with fuzzy- and defuzzificated value and instantiate variable set
        return new ImmutableTriple<>(p_context.agent().fuzzy().getDefuzzyfication().defuzzify(l_return),
                l_return, l_variables);

    })

            // find successfully ended rule
            .filter(ImmutableTriple::getLeft).findFirst()

            // realocate rule instantiated variables back to execution context
            .map(i -> {

                i.getRight().parallelStream().filter(j -> j instanceof IRelocateVariable)
                        .forEach(j -> ((IRelocateVariable) j).relocate());

                return i.getMiddle();

            })

            // otherwise rule fails (default behaviour)
            .orElse(CFuzzyValue.from(false));
}

From source file:org.lightjason.agentspeak.language.execution.action.CLambdaExpression.java

/**
 * create the local context structure of the expression
 *
 * @param p_context local context/* w w  w  .  j  a  va2s.  c  o  m*/
 * @return tripel with context, iterator variable and return variable
 */
private Triple<IContext, IVariable<?>, IVariable<?>> getLocalContext(final IContext p_context) {
    final IVariable<?> l_iterator = m_value.shallowcopy();
    final IVariable<?> l_return = m_return != null ? m_return.shallowcopy() : null;

    final Set<IVariable<?>> l_variables = new HashSet<>(p_context.instancevariables().values());

    m_body.stream().flatMap(IExecution::variables).forEach(l_variables::add);
    l_variables.remove(l_iterator);
    l_variables.add(l_iterator);

    if (l_return != null) {
        l_variables.remove(l_return);
        l_variables.add(l_return);
    }

    return new ImmutableTriple<>(new CContext(p_context.agent(), p_context.instance(), l_variables), l_iterator,
            l_return);
}

From source file:org.lightjason.examples.pokemon.CConfiguration.java

/**
 * loads the configuration from a file/*from  w  ww  . j a va  2s .co  m*/
 *
 * @param p_input YAML configuration file
 * @return instance
 *
 * @throws IOException on io errors
 * @throws URISyntaxException on URI syntax error
 */
@SuppressWarnings("unchecked")
public final CConfiguration load(final String p_input) throws IOException, URISyntaxException {
    final URL l_path = CCommon.getResourceURL(p_input);

    // read configuration
    final Map<String, Object> l_data = (Map<String, Object>) new Yaml().load(l_path.openStream());
    m_configurationpath = FilenameUtils.getPath(l_path.toString());

    // get initial values
    m_stacktrace = (boolean) l_data.getOrDefault("stacktrace", false);
    m_threadsleeptime = (int) l_data.getOrDefault("threadsleeptime", 0);
    m_simulationstep = (int) l_data.getOrDefault("steps", Integer.MAX_VALUE);
    if (!(boolean) l_data.getOrDefault("logging", false))
        LogManager.getLogManager().reset();

    m_windowweight = ((Map<String, Integer>) l_data.getOrDefault("window",
            Collections.<String, Integer>emptyMap())).getOrDefault("weight", 800);
    m_windowheight = ((Map<String, Integer>) l_data.getOrDefault("window",
            Collections.<String, Integer>emptyMap())).getOrDefault("height", 600);
    m_zoomspeed = ((Map<String, Integer>) l_data.getOrDefault("window",
            Collections.<String, Integer>emptyMap())).getOrDefault("zoomspeed", 2) / 100f;
    m_zoomspeed = m_zoomspeed <= 0 ? 0.02f : m_zoomspeed;
    m_dragspeed = ((Map<String, Integer>) l_data.getOrDefault("window",
            Collections.<String, Integer>emptyMap())).getOrDefault("dragspeed", 100) / 1000f;
    m_dragspeed = m_dragspeed <= 0 ? 1f : m_dragspeed;

    m_screenshot = new ImmutableTriple<>(
            (String) ((Map<String, Object>) l_data.getOrDefault("screenshot",
                    Collections.<String, Integer>emptyMap())).getOrDefault("file", ""),
            (String) ((Map<String, Object>) l_data.getOrDefault("screenshot",
                    Collections.<String, Integer>emptyMap())).getOrDefault("format", ""),
            (Integer) ((Map<String, Object>) l_data.getOrDefault("screenshot",
                    Collections.<String, Integer>emptyMap())).getOrDefault("step", -1));

    // create static objects - static object are needed by the environment
    final List<IItem> l_static = new LinkedList<>();
    this.createStatic((List<Map<String, Object>>) l_data.getOrDefault("element",
            Collections.<Map<String, Object>>emptyList()), l_static);
    m_staticelements = Collections.unmodifiableList(l_static);

    // create environment - static items must be exists
    m_environment = new CEnvironment(
            (Integer) ((Map<String, Object>) l_data.getOrDefault("environment",
                    Collections.<String, Integer>emptyMap())).getOrDefault("rows", -1),
            (Integer) ((Map<String, Object>) l_data.getOrDefault("environment",
                    Collections.<String, Integer>emptyMap())).getOrDefault("columns", -1),
            (Integer) ((Map<String, Object>) l_data.getOrDefault("environment",
                    Collections.<String, Integer>emptyMap())).getOrDefault("cellsize", -1),
            ERoutingFactory.valueOf(((String) ((Map<String, Object>) l_data.getOrDefault("environment",
                    Collections.<String, Integer>emptyMap())).getOrDefault("routing", "")).trim().toUpperCase())
                    .get(),
            m_staticelements);

    // create executable object list and check number of elements - environment must be exists
    final List<IAgent> l_agents = new LinkedList<>();
    this.createAgent((Map<String, Object>) l_data.getOrDefault("agent", Collections.<String, Object>emptyMap()),
            l_agents, (boolean) l_data.getOrDefault("agentprint", true));
    m_agents = Collections.unmodifiableList(l_agents);

    if (m_agents.size() + m_staticelements.size() > m_environment.column() * m_environment.row() / 2)
        throw new IllegalArgumentException(MessageFormat.format(
                "number of simulation elements are very large [{0}], so the environment size is too small, the environment "
                        + "[{1}x{2}] must define a number of cells which is greater than the two-time number of elements",
                m_agents.size(), m_environment.row(), m_environment.column()));

    // create evaluation
    m_evaluation = new CEvaluation(m_agents.parallelStream());

    // run initialization processes
    m_environment.initialize();

    return this;
}

From source file:org.lightjason.examples.pokemon.simulation.agent.pokemon.CDefinition.java

/**
 * ctor/*  ww  w. j a v a2  s  . c  o m*/
 */
private CDefinition() {
    Structure l_structure = null;
    try {
        // read structure
        l_structure = (Structure) JAXBContext.newInstance(Structure.class).createUnmarshaller()
                .unmarshal(CCommon.getResourceURL(CCommon.PACKAGEPATH + "data/character.xml"));

    } catch (final JAXBException | MalformedURLException | URISyntaxException l_exception) {
        System.out.println(l_exception);
        LOGGER.warning(l_exception.toString());
    }

    if (l_structure == null)
        m_pokemon = Collections.emptyMap();
    else {

        // read attributes
        final Map<String, CAttribute> l_attribute = Collections.unmodifiableMap(l_structure.getConfiguration()
                .getAttribute().getItem().stream()
                .map(i -> new CAttribute(i.getId(), EAccess.valueOf(i.getAgentaccess().trim().toUpperCase())))
                .collect(Collectors.toMap(CAttribute::name, i -> i)));

        // read atacks
        final Map<String, CAttack> l_attack = Collections.unmodifiableMap(l_structure.getConfiguration()
                .getAttack().getItem().stream().map(i -> new CAttack(i, l_attribute))
                .collect(Collectors.toMap(CAttack::name, i -> i)));

        // read pokemon character
        m_pokemon = Collections.unmodifiableMap(l_structure.getCharacter().getPokemon().stream()
                .collect(Collectors.toMap(i -> i.getId().trim().toLowerCase(), i -> new ImmutablePair<>(

                        i.getExperience(),

                        Collections.unmodifiableList(IntStream.range(0, i.getLevel().size())
                                .mapToObj(j -> new CLevel(i.getId().trim().toLowerCase(), j,

                                        i.getLevel().get(j).getEthnicity().stream().map(Ilevelitem::getId),
                                        i.getLevel().get(j).getEthnicity().stream()
                                                .map(n -> new ImmutableTriple<Number, Number, Number>(
                                                        n.getExpected(), n.getMinimum(), n.getMaximum())),

                                        i.getLevel().get(j).getMotivation().stream().map(Ilevelitem::getId),

                                        i.getLevel().get(j).getMotivation().stream()
                                                .map(n -> new ImmutableTriple<Number, Number, Number>(
                                                        n.getExpected(), n.getMinimum(), n.getMaximum())),

                                        i.getLevel().get(j).getAttribute().stream()
                                                .map(n -> l_attribute.get(n.getId().trim().toLowerCase())),

                                        i.getLevel().get(j).getAttribute().stream()
                                                .map(n -> new ImmutableTriple<Number, Number, Number>(
                                                        n.getExpected(), n.getMinimum(), n.getMaximum())),

                                        i.getLevel().get(j).getAttack().stream()
                                                .map(n -> l_attack.get(n.getId().trim().toLowerCase()))

                                )).collect(Collectors.toList())))

        )));

    }
}

From source file:org.lightjason.examples.pokemon.simulation.agent.pokemon.CLevel.java

/**
 * generates the random distribution for the values
 *
 * @param p_keys keys/*from   ww w  .j  a  v a 2  s  . c o m*/
 * @param p_value tripel value set (initial value, min, max bounding)
 * @return map
 *
 * @tparam T key type
 */
private static <T> Map<T, ImmutableTriple<AbstractRealDistribution, Number, Number>> initialize(
        final Stream<T> p_keys, final Stream<ImmutableTriple<Number, Number, Number>> p_value) {
    return Collections.unmodifiableMap(StreamUtils
            .zip(p_keys, p_value,
                    (n, v) -> new ImmutablePair<>(n,
                            new ImmutableTriple<AbstractRealDistribution, Number, Number>(
                                    new NormalDistribution(CMath.RANDOMGENERATOR, v.getLeft().doubleValue(),
                                            Math.sqrt(0.5 * (v.getRight().doubleValue()
                                                    - v.getMiddle().doubleValue()))),
                                    v.getMiddle(), v.getRight())))
            .collect(Collectors.toMap(ImmutablePair::getLeft, ImmutablePair::getRight)));
}

From source file:org.mxupdate.test.data.util.KeyValueList.java

/**
 * Defines key / value for given {@code _tag}.
 *
 * @param _tag          used tag (name) of the flag
 * @param _key          key/* w w w  .j ava  2 s  . co m*/
 * @param _value        value
 */
public void addKeyValue(final String _tag, final String _key, final String _value) {
    this.keyValues.add(new ImmutableTriple<>(_tag, _key, _value));
}

From source file:org.mxupdate.test.data.util.KeyValueList.java

/**
 * Defines key / value for given {@code _tag}.
 *
 * @param _tag          used tag (name) of the flag
 * @param _key          key/*w w  w.  j  av  a  2s  .  co  m*/
 * @param _value        value
 */
public void addKeyValue(final String _tag, final AbstractData<?> _key, final String _value) {
    this.keyValues.add(new ImmutableTriple<>(_tag, _key.getName(), _value));
    this.datas.add(_key);
}

From source file:org.opendaylight.vtn.manager.internal.util.concurrent.FutureCancellerTest.java

/**
 * Test method for/*from  w  w w .  j av  a  2  s  .c  om*/
 * {@link FutureCanceller#set(Timer,long,ListenableFuture)} and
 * {@link FutureCanceller#set(Timer,long,ListenableFuture,boolean)}.
 *
 * @throws Exception  An error occurred.
 */
@Test
public void testSet() throws Exception {
    TestTimer timer = new TestTimer();
    List<Triple<SettableVTNFuture<Void>, Long, Boolean>> list = new ArrayList<>();
    IllegalStateException cause = new IllegalStateException();
    ListenableFuture<Void> succeeded = Futures.<Void>immediateFuture(null);
    ListenableFuture<Void> failed = Futures.<Void>immediateFailedFuture(cause);
    ListenableFuture<Void> cancelled = Futures.<Void>immediateCancelledFuture();
    List<ListenableFuture<Void>> ignored = new ArrayList<>();
    Collections.addAll(ignored, succeeded, failed, cancelled);

    long[] timeouts = { 1L, 10L, 333333L };
    boolean[] bools = { true, false };
    for (long timeout : timeouts) {
        SettableVTNFuture<Void> f = new SettableVTNFuture<>();
        f.setThread(Thread.currentThread());
        Triple<SettableVTNFuture<Void>, Long, Boolean> expected = new ImmutableTriple<>(f, timeout, false);
        list.add(expected);
        FutureCanceller.set(timer, timeout, f);

        // Completed future should be ignored.
        for (ListenableFuture<Void> completed : ignored) {
            FutureCanceller.set(timer, timeout, completed);
        }

        for (boolean intr : bools) {
            f = new SettableVTNFuture<>();
            f.setThread(Thread.currentThread());
            expected = new ImmutableTriple<>(f, timeout, intr);
            list.add(expected);
            FutureCanceller.set(timer, timeout, f, intr);

            // Completed future should be ignored.
            for (ListenableFuture<Void> completed : ignored) {
                FutureCanceller.set(timer, timeout, completed, intr);
            }
        }
    }

    Iterator<Triple<SettableVTNFuture<Void>, Long, Boolean>> it = list.iterator();
    for (Pair<Long, TimerTask> pair : timer.getTasks()) {
        assertTrue(it.hasNext());
        Triple<SettableVTNFuture<Void>, Long, Boolean> expected = it.next();

        // Check delay.
        assertEquals(expected.getMiddle(), pair.getLeft());

        // Check the target future.
        TimerTask task = pair.getRight();
        assertTrue(task instanceof FutureCanceller<?>);
        ListenableFuture target = getFieldValue(task, ListenableFuture.class, "targetTask");
        SettableVTNFuture<Void> f = expected.getLeft();
        assertEquals(target, f);

        // Check intr flag.
        Boolean intr = getFieldValue(task, Boolean.class, "needInterrupt");
        assertEquals(intr, expected.getRight());

        // Cancel the target future.
        assertEquals(false, f.isCancelled());
        assertEquals(false, f.isDone());
        task.run();
        assertEquals(intr.booleanValue(), Thread.interrupted());
        assertEquals(true, f.isCancelled());
        assertEquals(true, f.isDone());
    }

    assertFalse(it.hasNext());
}

From source file:org.opendaylight.vtn.manager.internal.util.vnode.VTNMacMapStatus.java

/**
 * Activate MAC mapping for the specified MAC address.
 *
 * @param mapId  The identifier for the target MAC mapping.
 * @param mvlan  A {@link MacVlan} instance corresponding to a host to be
 *               activated.// w ww .j a v a2s  .  c om
 * @param sport  A {@link SalPort} instance corresponding to a switch port
 *               where the MAC address is detected.
 * @return
 *   <p>
 *     A {@link Triple} instance is returned if the MAC mapping was
 *     successfully activated.
 *   </p>
 *   <ul>
 *     <li>
 *       A boolean value that indicates the result is set to the left.
 *       {@code true} means that the target MAC mapping has been activated.
 *       {@code false} means that the target MAC mapping is already
 *       activated.
 *     </li>
 *     <li>
 *       A {@link SalPort} instance that specifies the physical switch port
 *       previously associated with the L2 host in the MAC mapping is set
 *       to the middle.
 *     </li>
 *     <li>
 *       A {@link PortVlan} instance that specifies the VLAN to be released
 *       is set to the right.
 *     </li>
 *   </ul>
 *   <p>
 *     {@code null} is returned if the MAC mapping for the specified
 *     host is already activated.
 *   </p>
 * @throws MacMapDuplicateException
 *    The specified MAC address is already mapped by this MAC mapping.
 */
public Triple<Boolean, SalPort, PortVlan> activate(MacMapIdentifier mapId, MacVlan mvlan, SalPort sport)
        throws MacMapDuplicateException {
    int vid = mvlan.getVlanId();
    long mac = mvlan.getAddress();
    boolean empty = activeMap.isEmpty();
    Entry<MacVlan, SalPort> entry = getDuplicateEntry(mac);
    SalPort oldPort;
    PortVlan released = null;
    if (entry == null) {
        activeMap.put(mvlan, sport);
        oldPort = null;
    } else {
        MacVlan dup = entry.getKey();
        if (!dup.equals(mvlan)) {
            throw new MacMapDuplicateException(mvlan, mapId, dup);
        }

        oldPort = entry.getValue();
        if (sport.equals(oldPort)) {
            return null;
        }

        // Update the port associated with the specified host.
        activeMap.put(dup, sport);

        // Remove old port information.
        PortVlan pvlan = new PortVlan(oldPort, vid);
        Set<MacVlan> mvSet = mappedPorts.get(pvlan);
        mvSet.remove(mvlan);
        if (mvSet.isEmpty()) {
            mappedPorts.remove(pvlan);
            released = pvlan;
        }
    }

    PortVlan pvlan = new PortVlan(sport, vid);
    Set<MacVlan> mvSet = mappedPorts.get(pvlan);
    if (mvSet == null) {
        mvSet = new HashSet<>();
        mappedPorts.put(pvlan, mvSet);
    }

    mvSet.add(mvlan);
    setDirty();

    return new ImmutableTriple<Boolean, SalPort, PortVlan>(empty, oldPort, released);
}