text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.network.ovs;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import javax.inject.Inject;
import javax.naming.ConfigurationException;
import javax.persistence.EntityExistsException;

import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.framework.messagebus.MessageBus;
import org.apache.cloudstack.framework.messagebus.MessageSubscriber;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.cloud.agent.AgentManager;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.OvsCreateTunnelAnswer;
import com.cloud.agent.api.OvsCreateTunnelCommand;
import com.cloud.agent.api.OvsDestroyBridgeCommand;
import com.cloud.agent.api.OvsDestroyTunnelCommand;
import com.cloud.agent.api.OvsFetchInterfaceAnswer;
import com.cloud.agent.api.OvsFetchInterfaceCommand;
import com.cloud.agent.api.OvsSetupBridgeCommand;
import com.cloud.agent.api.OvsVpcPhysicalTopologyConfigCommand;
import com.cloud.agent.api.OvsVpcRoutingPolicyConfigCommand;
import com.cloud.agent.manager.Commands;
import com.cloud.configuration.Config;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.Network;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.PhysicalNetworkTrafficType;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NetworkVO;
import com.cloud.network.dao.PhysicalNetworkTrafficTypeDao;
import com.cloud.network.ovs.dao.OvsTunnel;
import com.cloud.network.ovs.dao.OvsTunnelInterfaceDao;
import com.cloud.network.ovs.dao.OvsTunnelInterfaceVO;
import com.cloud.network.ovs.dao.OvsTunnelNetworkDao;
import com.cloud.network.ovs.dao.OvsTunnelNetworkVO;
import com.cloud.network.ovs.dao.VpcDistributedRouterSeqNoDao;
import com.cloud.network.ovs.dao.VpcDistributedRouterSeqNoVO;
import com.cloud.network.vpc.NetworkACLItemDao;
import com.cloud.network.vpc.NetworkACLItemVO;
import com.cloud.network.vpc.NetworkACLVO;
import com.cloud.network.vpc.VpcManager;
import com.cloud.network.vpc.VpcVO;
import com.cloud.network.vpc.dao.NetworkACLDao;
import com.cloud.network.vpc.dao.VpcDao;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.TransactionCallback;
import com.cloud.utils.db.TransactionStatus;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.fsm.StateListener;
import com.cloud.utils.fsm.StateMachine2;
import com.cloud.vm.Nic;
import com.cloud.vm.NicVO;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.NicDao;
import com.cloud.vm.dao.VMInstanceDao;

@Component
public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManager, StateListener<VirtualMachine.State, VirtualMachine.Event, VirtualMachine> {
    public static final Logger s_logger = Logger.getLogger(OvsTunnelManagerImpl.class.getName());

    // boolean _isEnabled;
    ScheduledExecutorService _executorPool;
    ScheduledExecutorService _cleanupExecutor;

    @Inject
    ConfigurationDao _configDao;
    @Inject
    NicDao _nicDao;
    @Inject
    HostDao _hostDao;
    @Inject
    PhysicalNetworkTrafficTypeDao _physNetTTDao;

    @Inject
    DomainRouterDao _routerDao;
    @Inject
    OvsTunnelNetworkDao _tunnelNetworkDao;
    @Inject
    OvsTunnelInterfaceDao _tunnelInterfaceDao;
    @Inject
    AgentManager _agentMgr;
    @Inject
    OvsNetworkTopologyGuru _ovsNetworkToplogyGuru;
    @Inject
    VpcDao _vpcDao;
    @Inject
    VpcManager _vpcMgr;
    @Inject
    protected VMInstanceDao _vmInstanceDao;
    @Inject
    NetworkDao _networkDao;
    @Inject
    MessageBus _messageBus;
    @Inject
    NetworkACLDao _networkACLDao;
    @Inject
    NetworkACLItemDao _networkACLItemDao;
    @Inject
    VpcDistributedRouterSeqNoDao _vpcDrSeqNoDao;

    @Override
    public boolean configure(String name, Map<String, Object> params)
            throws ConfigurationException {
        _executorPool = Executors.newScheduledThreadPool(10, new NamedThreadFactory("OVS"));
        _cleanupExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("OVS-Cleanup"));

        // register for network ACL updated for a VPC.
        _messageBus.subscribe("Network_ACL_Replaced", new NetworkAclEventsSubscriber());

        // register for VM state transition updates
        VirtualMachine.State.getStateMachine().registerListener(this);

        return true;
    }

    @DB
    protected OvsTunnelInterfaceVO createInterfaceRecord(String ip,
            String netmask, String mac, long hostId, String label) {
        OvsTunnelInterfaceVO ti = null;
        try {
            ti = new OvsTunnelInterfaceVO(ip, netmask, mac, hostId, label);
            // TODO: Is locking really necessary here?
            OvsTunnelInterfaceVO lock = _tunnelInterfaceDao
                    .acquireInLockTable(Long.valueOf(1));
            if (lock == null) {
                s_logger.warn("Cannot lock table ovs_tunnel_account");
                return null;
            }
            _tunnelInterfaceDao.persist(ti);
            _tunnelInterfaceDao.releaseFromLockTable(lock.getId());
        } catch (EntityExistsException e) {
            s_logger.debug("A record for the interface for network " + label
                    + " on host id " + hostId + " already exists");
        }
        return ti;
    }

    private String handleFetchInterfaceAnswer(Answer[] answers, Long hostId) {
        OvsFetchInterfaceAnswer ans = (OvsFetchInterfaceAnswer)answers[0];
        if (ans.getResult()) {
            if (ans.getIp() != null && !("".equals(ans.getIp()))) {
                OvsTunnelInterfaceVO ti = createInterfaceRecord(ans.getIp(),
                        ans.getNetmask(), ans.getMac(), hostId, ans.getLabel());
                return ti.getIp();
            }
        }
        // Fetch interface failed!
        s_logger.warn("Unable to fetch the IP address for the GRE tunnel endpoint"
                + ans.getDetails());
        return null;
    }

    @DB
    protected OvsTunnelNetworkVO createTunnelRecord(long from, long to, long networkId, int key) {
        OvsTunnelNetworkVO ta = null;
        try {
            ta = new OvsTunnelNetworkVO(from, to, key, networkId);
            OvsTunnelNetworkVO lock = _tunnelNetworkDao.acquireInLockTable(Long.valueOf(1));
            if (lock == null) {
                s_logger.warn("Cannot lock table ovs_tunnel_account");
                return null;
            }
            _tunnelNetworkDao.persist(ta);
            _tunnelNetworkDao.releaseFromLockTable(lock.getId());
        } catch (EntityExistsException e) {
            s_logger.debug("A record for the tunnel from " + from + " to " + to + " already exists");
        }
        return ta;
    }

    private void handleCreateTunnelAnswer(Answer[] answers) {
        OvsCreateTunnelAnswer r = (OvsCreateTunnelAnswer)answers[0];
        String s =
                String.format("(hostIP:%1$s, remoteIP:%2$s, bridge:%3$s," + "greKey:%4$s, portName:%5$s)",
                        r.getFromIp(), r.getToIp(), r.getBridge(), r.getKey(), r.getInPortName());
        Long from = r.getFrom();
        Long to = r.getTo();
        long networkId = r.getNetworkId();
        OvsTunnelNetworkVO tunnel = _tunnelNetworkDao.findByFromToNetwork(from, to, networkId);
        if (tunnel == null) {
            throw new CloudRuntimeException(
                    String.format("Unable find tunnelNetwork record" +
                            "(from=%1$s,to=%2$s, account=%3$s",
                            from, to, networkId));
        }
        if (!r.getResult()) {
            tunnel.setState(OvsTunnel.State.Failed.name());
            s_logger.warn("Create GRE tunnel from " + from + " to " + to + " failed due to " + r.getDetails()
                    + s);
        } else {
            tunnel.setState(OvsTunnel.State.Established.name());
            tunnel.setPortName(r.getInPortName());
            s_logger.info("Create GRE tunnel from " + from + " to " + to + " succeeded." + r.getDetails() + s);
        }
        _tunnelNetworkDao.update(tunnel.getId(), tunnel);
    }

    private String getGreEndpointIP(Host host, Network nw)
            throws AgentUnavailableException, OperationTimedoutException {
        String endpointIp = null;
        // Fetch fefault name for network label from configuration
        String physNetLabel = _configDao.getValue(Config.OvsTunnelNetworkDefaultLabel.key());
        Long physNetId = nw.getPhysicalNetworkId();
        PhysicalNetworkTrafficType physNetTT =
                _physNetTTDao.findBy(physNetId, TrafficType.Guest);
        HypervisorType hvType = host.getHypervisorType();

        String label = null;
        switch (hvType) {
        case XenServer:
            label = physNetTT.getXenNetworkLabel();
            if ((label != null) && (!label.equals(""))) {
                physNetLabel = label;
            }
            break;
        case KVM:
            label = physNetTT.getKvmNetworkLabel();
            if ((label != null) && (!label.equals(""))) {
                physNetLabel = label;
            }
            break;
        default:
            throw new CloudRuntimeException("Hypervisor " +
                    hvType.toString() +
                    " unsupported by OVS Tunnel Manager");
        }

        // Try to fetch GRE endpoint IP address for cloud db
        // If not found, then find it on the hypervisor
        OvsTunnelInterfaceVO tunnelIface =
                _tunnelInterfaceDao.getByHostAndLabel(host.getId(),
                        physNetLabel);
        if (tunnelIface == null) {
            //Now find and fetch configuration for physical interface
            //for network with label on target host
            Commands fetchIfaceCmds =
                    new Commands(new OvsFetchInterfaceCommand(physNetLabel));
            s_logger.debug("Ask host " + host.getId() +
                    " to retrieve interface for phy net with label:" +
                    physNetLabel);
            Answer[] fetchIfaceAnswers = _agentMgr.send(host.getId(), fetchIfaceCmds);
            //And finally save it for future use
            endpointIp = handleFetchInterfaceAnswer(fetchIfaceAnswers, host.getId());
        } else {
            endpointIp = tunnelIface.getIp();
        }
        return endpointIp;
    }

    private int getGreKey(Network network) {
        int key = 0;
        try {
            //The GRE key is actually in the host part of the URI
            String keyStr = network.getBroadcastUri().getAuthority();
            if (keyStr.contains(".")) {
                String[] parts = keyStr.split("\\.");
                key = Integer.parseInt(parts[1]);
            } else {
                key = Integer.parseInt(keyStr);
            }

            return key;
        } catch (NumberFormatException e) {
            s_logger.debug("Well well, how did '" + key
                    + "' end up in the broadcast URI for the network?");
            throw new CloudRuntimeException(String.format(
                    "Invalid GRE key parsed from"
                            + "network broadcast URI (%s)", network
                            .getBroadcastUri().toString()));
        }
    }

    @DB
    protected void checkAndCreateTunnel(Network nw, Host host) {

        s_logger.debug("Creating tunnels with OVS tunnel manager");

        long hostId = host.getId();
        int key = getGreKey(nw);
        String bridgeName = generateBridgeName(nw, key);
        List<Long> toHostIds = new ArrayList<Long>();
        List<Long> fromHostIds = new ArrayList<Long>();
        List<Long> networkSpannedHosts = _ovsNetworkToplogyGuru.getNetworkSpanedHosts(nw.getId());
        for (Long rh : networkSpannedHosts) {
            if (rh == hostId) {
                continue;
            }
            OvsTunnelNetworkVO ta = _tunnelNetworkDao.findByFromToNetwork(hostId, rh.longValue(), nw.getId());
            // Try and create the tunnel even if a previous attempt failed
            if (ta == null || ta.getState().equals(OvsTunnel.State.Failed.name())) {
                s_logger.debug("Attempting to create tunnel from:" + hostId + " to:" + rh.longValue());
                if (ta == null) {
                    createTunnelRecord(hostId, rh.longValue(), nw.getId(), key);
                }
                if (!toHostIds.contains(rh)) {
                    toHostIds.add(rh);
                }
            }

            ta = _tunnelNetworkDao.findByFromToNetwork(rh.longValue(),
                    hostId, nw.getId());
            // Try and create the tunnel even if a previous attempt failed
            if (ta == null || ta.getState().equals(OvsTunnel.State.Failed.name())) {
                s_logger.debug("Attempting to create tunnel from:" +
                        rh.longValue() + " to:" + hostId);
                if (ta == null) {
                    createTunnelRecord(rh.longValue(), hostId,
                            nw.getId(), key);
                }
                if (!fromHostIds.contains(rh)) {
                    fromHostIds.add(rh);
                }
            }
        }
        //TODO: Should we propagate the exception here?
        try {
            String myIp = getGreEndpointIP(host, nw);
            if (myIp == null)
                throw new GreTunnelException("Unable to retrieve the source " + "endpoint for the GRE tunnel." + "Failure is on host:" + host.getId());
            boolean noHost = true;
            for (Long i : toHostIds) {
                HostVO rHost = _hostDao.findById(i);
                String otherIp = getGreEndpointIP(rHost, nw);
                if (otherIp == null)
                    throw new GreTunnelException(
                            "Unable to retrieve the remote "
                                    + "endpoint for the GRE tunnel."
                                    + "Failure is on host:" + rHost.getId());
                Commands cmds = new Commands(
                        new OvsCreateTunnelCommand(otherIp, key,
                                Long.valueOf(hostId), i, nw.getId(), myIp, bridgeName, nw.getUuid()));
                s_logger.debug("Attempting to create tunnel from:" + hostId + " to:" + i + " for the network " + nw.getId());
                s_logger.debug("Ask host " + hostId
                        + " to create gre tunnel to " + i);
                Answer[] answers = _agentMgr.send(hostId, cmds);
                handleCreateTunnelAnswer(answers);
                noHost = false;
            }

            for (Long i : fromHostIds) {
                HostVO rHost = _hostDao.findById(i);
                String otherIp = getGreEndpointIP(rHost, nw);
                Commands cmds = new Commands(new OvsCreateTunnelCommand(myIp,
                        key, i, Long.valueOf(hostId), nw.getId(), otherIp, bridgeName, nw.getUuid()));
                s_logger.debug("Ask host " + i + " to create gre tunnel to "
                        + hostId);
                Answer[] answers = _agentMgr.send(i, cmds);
                handleCreateTunnelAnswer(answers);
                noHost = false;
            }

            // If no tunnels have been configured, perform the bridge setup
            // anyway. This will ensure VIF rules will be triggered
            if (noHost) {
                Commands cmds = new Commands(new OvsSetupBridgeCommand(bridgeName, hostId, nw.getId()));
                s_logger.debug("Ask host " + hostId + " to configure bridge for network:" + nw.getId());
                Answer[] answers = _agentMgr.send(hostId, cmds);
                handleSetupBridgeAnswer(answers);
            }
        } catch (GreTunnelException | OperationTimedoutException | AgentUnavailableException e) {
            // I really thing we should do a better handling of these exceptions
            s_logger.warn("Ovs Tunnel network created tunnel failed", e);
        }
    }

    @Override
    public boolean isOvsTunnelEnabled() {
        return true;
    }

    boolean isVpcEnabledForDistributedRouter(long vpcId) {
        VpcVO vpc = _vpcDao.findById(vpcId);
        return vpc.usesDistributedRouter();
    }

    @Override
    public void checkAndPrepareHostForTunnelNetwork(Network nw, Host host) {
        if (nw.getVpcId() != null && isVpcEnabledForDistributedRouter(nw.getVpcId())) {
            // check and setup host to be in full tunnel mesh with each of the network in the VPC
            checkAndCreateVpcTunnelNetworks(host, nw.getVpcId());
        } else {
            // check and setup host to be in full tunnel mesh with the network
            checkAndCreateTunnel(nw, host);
        }
    }

    @DB
    private void handleDestroyTunnelAnswer(Answer ans, long from, long to, long networkId) {
        if (ans.getResult()) {
            OvsTunnelNetworkVO lock = _tunnelNetworkDao.acquireInLockTable(Long.valueOf(1));
            if (lock == null) {
                s_logger.warn(String.format("failed to lock" +
                        "ovs_tunnel_account, remove record of " +
                        "tunnel(from=%1$s, to=%2$s account=%3$s) failed",
                        from, to, networkId));
                return;
            }

            _tunnelNetworkDao.removeByFromToNetwork(from, to, networkId);
            _tunnelNetworkDao.releaseFromLockTable(lock.getId());

            s_logger.debug(String.format("Destroy tunnel(account:%1$s," +
                    "from:%2$s, to:%3$s) successful",
                    networkId, from, to));
        } else {
            s_logger.debug(String.format("Destroy tunnel(account:%1$s," + "from:%2$s, to:%3$s) failed", networkId, from, to));
        }
    }

    @DB
    private void handleDestroyBridgeAnswer(Answer ans, long hostId, long networkId) {

        if (ans.getResult()) {
            OvsTunnelNetworkVO lock = _tunnelNetworkDao.acquireInLockTable(Long.valueOf(1));
            if (lock == null) {
                s_logger.warn("failed to lock ovs_tunnel_network," + "remove record");
                return;
            }

            _tunnelNetworkDao.removeByFromNetwork(hostId, networkId);
            _tunnelNetworkDao.releaseFromLockTable(lock.getId());

            s_logger.debug(String.format("Destroy bridge for" +
                    "network %1$s successful", networkId));
        } else {
            s_logger.debug(String.format("Destroy bridge for" +
                    "network %1$s failed", networkId));
        }
    }

    private void handleSetupBridgeAnswer(Answer[] answers) {
        //TODO: Add some error management here?
        s_logger.debug("Placeholder for something more meanginful to come");
    }

    @Override
    public void checkAndRemoveHostFromTunnelNetwork(Network nw, Host host) {

        if (nw.getVpcId() != null && isVpcEnabledForDistributedRouter(nw.getVpcId())) {
            List<Long> vmIds = _ovsNetworkToplogyGuru.getActiveVmsInVpcOnHost(nw.getVpcId(), host.getId());

            if (vmIds != null && !vmIds.isEmpty()) {
                return;
            }

            // there are not active VM's on this host belonging to any of the tiers in the VPC, so remove
            // the host from the tunnel mesh network and destroy the bridge
            List<? extends Network> vpcNetworks =  _vpcMgr.getVpcNetworks(nw.getVpcId());
            try {
                for (Network network: vpcNetworks) {
                    int key = getGreKey(nw);
                    String bridgeName = generateBridgeName(nw, key);
                    /* Then ask hosts have peer tunnel with me to destroy them */
                    List<OvsTunnelNetworkVO> peers = _tunnelNetworkDao.listByToNetwork(host.getId(),nw.getId());
                    for (OvsTunnelNetworkVO p : peers) {
                        // If the tunnel was not successfully created don't bother to remove it
                        if (p.getState().equals(OvsTunnel.State.Established.name())) {
                            Command cmd= new OvsDestroyTunnelCommand(p.getNetworkId(), bridgeName,
                                    p.getPortName());
                            s_logger.debug("Destroying tunnel to " + host.getId() +
                                    " from " + p.getFrom());
                            Answer ans = _agentMgr.send(p.getFrom(), cmd);
                            handleDestroyTunnelAnswer(ans, p.getFrom(), p.getTo(), p.getNetworkId());
                        }
                    }
                }

                Command cmd = new OvsDestroyBridgeCommand(nw.getId(), generateBridgeNameForVpc(nw.getVpcId()),
                        host.getId());
                s_logger.debug("Destroying bridge for network " + nw.getId() + " on host:" + host.getId());
                Answer ans = _agentMgr.send(host.getId(), cmd);
                handleDestroyBridgeAnswer(ans, host.getId(), nw.getId());
            } catch (Exception e) {
                s_logger.info("[ignored]"
                        + "exception while removing host from networks: " + e.getLocalizedMessage());
            }
        } else {
            List<Long> vmIds = _ovsNetworkToplogyGuru.getActiveVmsInNetworkOnHost(nw.getId(), host.getId(), true);
            if (vmIds != null && !vmIds.isEmpty()) {
                return;
            }
            try {
                /* Now we are last one on host, destroy the bridge with all
                * the tunnels for this network  */
                int key = getGreKey(nw);
                String bridgeName = generateBridgeName(nw, key);
                Command cmd = new OvsDestroyBridgeCommand(nw.getId(), bridgeName, host.getId());
                s_logger.debug("Destroying bridge for network " + nw.getId() + " on host:" + host.getId());
                Answer ans = _agentMgr.send(host.getId(), cmd);
                handleDestroyBridgeAnswer(ans, host.getId(), nw.getId());

                /* Then ask hosts have peer tunnel with me to destroy them */
                List<OvsTunnelNetworkVO> peers =
                        _tunnelNetworkDao.listByToNetwork(host.getId(),
                                nw.getId());
                for (OvsTunnelNetworkVO p : peers) {
                    // If the tunnel was not successfully created don't bother to remove it
                    if (p.getState().equals(OvsTunnel.State.Established.name())) {
                        cmd = new OvsDestroyTunnelCommand(p.getNetworkId(), bridgeName,
                                p.getPortName());
                        s_logger.debug("Destroying tunnel to " + host.getId() +
                                " from " + p.getFrom());
                        ans = _agentMgr.send(p.getFrom(), cmd);
                        handleDestroyTunnelAnswer(ans, p.getFrom(),
                                p.getTo(), p.getNetworkId());
                    }
                }
            } catch (Exception e) {
                s_logger.warn("Destroy tunnel failed", e);
            }
        }
    }

    private String generateBridgeName(Network nw, int key) {
        if (nw.getVpcId() != null && isVpcEnabledForDistributedRouter(nw.getVpcId())) {
            return "OVS-DR-VPC-Bridge" + nw.getVpcId();
        } else {
            return "OVSTunnel"+key;
        }
    }
    private String generateBridgeNameForVpc(long vpcId) {
        return "OVS-DR-VPC-Bridge" + vpcId;
    }

    @DB
    protected void checkAndCreateVpcTunnelNetworks(Host host, long vpcId) {

        long hostId = host.getId();
        String bridgeName=generateBridgeNameForVpc(vpcId);

        List<Long> vmIds = _ovsNetworkToplogyGuru.getActiveVmsInVpcOnHost(vpcId, hostId);

        if (vmIds == null || vmIds.isEmpty()) {

            // since this is the first VM from the VPC being launched on the host, first setup the bridge
            try {
                Commands cmds = new Commands(new OvsSetupBridgeCommand(bridgeName, hostId, null));
                s_logger.debug("Ask host " + hostId + " to create bridge for vpc " + vpcId + " and configure the "
                        + " bridge for distributed routing.");
                Answer[] answers = _agentMgr.send(hostId, cmds);
                handleSetupBridgeAnswer(answers);
            } catch (OperationTimedoutException | AgentUnavailableException e) {
                s_logger.warn("Ovs Tunnel network created bridge failed", e);
            }

            // now that bridge is setup, populate network acl's before the VM gets created
            OvsVpcRoutingPolicyConfigCommand cmd = prepareVpcRoutingPolicyUpdate(vpcId);
            cmd.setSequenceNumber(getNextRoutingPolicyUpdateSequenceNumber(vpcId));

            if (!sendVpcRoutingPolicyChangeUpdate(cmd, hostId, bridgeName)) {
                s_logger.debug("Failed to send VPC routing policy change update to host : " + hostId +
                        ". But moving on with sending the updates to the rest of the hosts.");
            }
        }

        List<? extends Network> vpcNetworks =  _vpcMgr.getVpcNetworks(vpcId);
        List<Long> vpcSpannedHostIds = _ovsNetworkToplogyGuru.getVpcSpannedHosts(vpcId);
        for (Network vpcNetwork: vpcNetworks) {
            if (vpcNetwork.getState() != Network.State.Implemented &&
                    vpcNetwork.getState() != Network.State.Implementing && vpcNetwork.getState() != Network.State.Setup)
                continue;

            int key = getGreKey(vpcNetwork);
            List<Long> toHostIds = new ArrayList<Long>();
            List<Long> fromHostIds = new ArrayList<Long>();
            OvsTunnelNetworkVO tunnelRecord = null;

            for (Long rh : vpcSpannedHostIds) {
                if (rh == hostId) {
                    continue;
                }
                tunnelRecord = _tunnelNetworkDao.findByFromToNetwork(hostId, rh.longValue(), vpcNetwork.getId());
                // Try and create the tunnel if does not exit or previous attempt failed
                if (tunnelRecord == null || tunnelRecord.getState().equals(OvsTunnel.State.Failed.name())) {
                    s_logger.debug("Attempting to create tunnel from:" + hostId + " to:" + rh.longValue());
                    if (tunnelRecord == null) {
                        createTunnelRecord(hostId, rh.longValue(), vpcNetwork.getId(), key);
                    }
                    if (!toHostIds.contains(rh)) {
                        toHostIds.add(rh);
                    }
                }
                tunnelRecord = _tunnelNetworkDao.findByFromToNetwork(rh.longValue(), hostId, vpcNetwork.getId());
                // Try and create the tunnel if does not exit or previous attempt failed
                if (tunnelRecord == null || tunnelRecord.getState().equals(OvsTunnel.State.Failed.name())) {
                    s_logger.debug("Attempting to create tunnel from:" + rh.longValue() + " to:" + hostId);
                    if (tunnelRecord == null) {
                        createTunnelRecord(rh.longValue(), hostId, vpcNetwork.getId(), key);
                    }
                    if (!fromHostIds.contains(rh)) {
                        fromHostIds.add(rh);
                    }
                }
            }

            try {
                String myIp = getGreEndpointIP(host, vpcNetwork);
                if (myIp == null)
                    throw new GreTunnelException("Unable to retrieve the source " + "endpoint for the GRE tunnel."
                            + "Failure is on host:" + host.getId());
                boolean noHost = true;

                for (Long i : toHostIds) {
                    HostVO rHost = _hostDao.findById(i);
                    String otherIp = getGreEndpointIP(rHost, vpcNetwork);
                    if (otherIp == null)
                        throw new GreTunnelException(
                                "Unable to retrieve the remote endpoint for the GRE tunnel."
                                        + "Failure is on host:" + rHost.getId());
                    Commands cmds = new Commands( new OvsCreateTunnelCommand(otherIp, key, Long.valueOf(hostId),
                                     i, vpcNetwork.getId(), myIp, bridgeName, vpcNetwork.getUuid()));
                    s_logger.debug("Attempting to create tunnel from:" + hostId + " to:" + i + " for the network "
                            + vpcNetwork.getId());
                    s_logger.debug("Ask host " + hostId
                            + " to create gre tunnel to " + i);
                    Answer[] answers = _agentMgr.send(hostId, cmds);
                    handleCreateTunnelAnswer(answers);
                }

                for (Long i : fromHostIds) {
                    HostVO rHost = _hostDao.findById(i);
                    String otherIp = getGreEndpointIP(rHost, vpcNetwork);
                    Commands cmds = new Commands(new OvsCreateTunnelCommand(myIp,
                            key, i, Long.valueOf(hostId), vpcNetwork.getId(), otherIp, bridgeName,
                            vpcNetwork.getUuid()));
                    s_logger.debug("Ask host " + i + " to create gre tunnel to "
                            + hostId);
                    Answer[] answers = _agentMgr.send(i, cmds);
                    handleCreateTunnelAnswer(answers);
                }
            } catch (GreTunnelException | OperationTimedoutException | AgentUnavailableException e) {
                // I really thing we should do a better handling of these exceptions
                s_logger.warn("Ovs Tunnel network created tunnel failed", e);
            }
        }
    }

    @Override
    public boolean preStateTransitionEvent(VirtualMachine.State oldState,
                                           VirtualMachine.Event event, VirtualMachine.State newState,
                                           VirtualMachine vo, boolean status, Object opaque) {
        return true;
    }

    @Override
    public boolean postStateTransitionEvent(StateMachine2.Transition<VirtualMachine.State, VirtualMachine.Event> transition, VirtualMachine vm, boolean status, Object opaque) {
      if (!status) {
        return false;
      }

      VirtualMachine.State oldState = transition.getCurrentState();
      VirtualMachine.State newState = transition.getToState();
      VirtualMachine.Event event = transition.getEvent();
      if (VirtualMachine.State.isVmStarted(oldState, event, newState)) {
        handleVmStateChange((VMInstanceVO)vm);
      } else if (VirtualMachine.State.isVmStopped(oldState, event, newState)) {
        handleVmStateChange((VMInstanceVO)vm);
      } else if (VirtualMachine.State.isVmMigrated(oldState, event, newState)) {
        handleVmStateChange((VMInstanceVO)vm);
      }

      return true;
    }

  private void handleVmStateChange(VMInstanceVO vm) {

        // get the VPC's impacted with the VM start
        List<Long> vpcIds = _ovsNetworkToplogyGuru.getVpcIdsVmIsPartOf(vm.getId());
        if (vpcIds == null || vpcIds.isEmpty()) {
            return;
        }

        for (Long vpcId: vpcIds) {
            VpcVO vpc = _vpcDao.findById(vpcId);
            // nothing to do if the VPC is not setup for distributed routing
            if (vpc == null || !vpc.usesDistributedRouter()) {
                return;
            }

            // get the list of hosts on which VPC spans (i.e hosts that need to be aware of VPC topology change update)
            List<Long> vpcSpannedHostIds = _ovsNetworkToplogyGuru.getVpcSpannedHosts(vpcId);
            String bridgeName=generateBridgeNameForVpc(vpcId);

            OvsVpcPhysicalTopologyConfigCommand topologyConfigCommand = prepareVpcTopologyUpdate(vpcId);
            topologyConfigCommand.setSequenceNumber(getNextTopologyUpdateSequenceNumber(vpcId));

            // send topology change update to VPC spanned hosts
            for (Long id: vpcSpannedHostIds) {
                if (!sendVpcTopologyChangeUpdate(topologyConfigCommand, id, bridgeName)) {
                    s_logger.debug("Failed to send VPC topology change update to host : " + id + ". Moving on " +
                            "with rest of the host update.");
                }
            }
        }
    }

    public boolean sendVpcTopologyChangeUpdate(OvsVpcPhysicalTopologyConfigCommand updateCmd, long hostId, String bridgeName) {
        try {
            s_logger.debug("Sending VPC topology change update to the host " + hostId);
            updateCmd.setHostId(hostId);
            updateCmd.setBridgeName(bridgeName);
            Answer ans = _agentMgr.send(hostId, updateCmd);
            if (ans.getResult()) {
                s_logger.debug("Successfully updated the host " + hostId + " with latest VPC topology." );
                return true;
            }  else {
                s_logger.debug("Failed to update the host " + hostId + " with latest VPC topology." );
                return false;
            }
        } catch (Exception e) {
            s_logger.debug("Failed to updated the host " + hostId + " with latest VPC topology.", e );
            return false;
        }
    }

    OvsVpcPhysicalTopologyConfigCommand prepareVpcTopologyUpdate(long vpcId) {
        VpcVO vpc = _vpcDao.findById(vpcId);
        assert (vpc != null): "invalid vpc id";

        List<? extends Network> vpcNetworks =  _vpcMgr.getVpcNetworks(vpcId);
        List<Long> hostIds = _ovsNetworkToplogyGuru.getVpcSpannedHosts(vpcId);
        List<Long> vmIds = _ovsNetworkToplogyGuru.getAllActiveVmsInVpc(vpcId);

        List<OvsVpcPhysicalTopologyConfigCommand.Host> hosts = new ArrayList<>();
        List<OvsVpcPhysicalTopologyConfigCommand.Tier> tiers = new ArrayList<>();
        List<OvsVpcPhysicalTopologyConfigCommand.Vm> vms = new ArrayList<>();

        for (Long hostId : hostIds) {
            HostVO hostDetails = _hostDao.findById(hostId);
            String remoteIp = null;
            for (Network network: vpcNetworks) {
                try {
                    remoteIp = getGreEndpointIP(hostDetails, network);
                } catch (Exception e) {
                    s_logger.info("[ignored]"
                            + "error getting GRE endpoint: " + e.getLocalizedMessage());
                }
            }
            OvsVpcPhysicalTopologyConfigCommand.Host host = new OvsVpcPhysicalTopologyConfigCommand.Host(hostId, remoteIp);
            hosts.add(host);
        }

        for (Network network: vpcNetworks) {
            String key = network.getBroadcastUri().getAuthority();
            long gre_key;
            if (key.contains(".")) {
                String[] parts = key.split("\\.");
                gre_key = Long.parseLong(parts[1]);
            } else {
                try {
                    gre_key = Long.parseLong(BroadcastDomainType.getValue(key));
                } catch (Exception e) {
                    return null;
                }
            }
            NicVO nic = _nicDao.findByIp4AddressAndNetworkId(network.getGateway(), network.getId());
            OvsVpcPhysicalTopologyConfigCommand.Tier tier = new OvsVpcPhysicalTopologyConfigCommand.Tier(gre_key,
                    network.getUuid(), network.getGateway(), nic.getMacAddress(), network.getCidr());
            tiers.add(tier);
        }

        for (long vmId: vmIds) {
            VirtualMachine vmInstance = _vmInstanceDao.findById(vmId);
            List<OvsVpcPhysicalTopologyConfigCommand.Nic>  vmNics = new ArrayList<OvsVpcPhysicalTopologyConfigCommand.Nic>();
            for (Nic vmNic :_nicDao.listByVmId(vmId)) {
                Network network = _networkDao.findById(vmNic.getNetworkId());
                if (network.getTrafficType() == TrafficType.Guest) {
                    OvsVpcPhysicalTopologyConfigCommand.Nic nic =  new OvsVpcPhysicalTopologyConfigCommand.Nic(
                            vmNic.getIPv4Address(), vmNic.getMacAddress(), network.getUuid());
                    vmNics.add(nic);
                }
            }
            OvsVpcPhysicalTopologyConfigCommand.Vm vm = new OvsVpcPhysicalTopologyConfigCommand.Vm(
                    vmInstance.getHostId(), vmNics.toArray(new OvsVpcPhysicalTopologyConfigCommand.Nic[vmNics.size()]));
            vms.add(vm);
        }

        return new OvsVpcPhysicalTopologyConfigCommand(
                hosts.toArray(new OvsVpcPhysicalTopologyConfigCommand.Host[hosts.size()]),
                tiers.toArray(new OvsVpcPhysicalTopologyConfigCommand.Tier[tiers.size()]),
                vms.toArray(new OvsVpcPhysicalTopologyConfigCommand.Vm[vms.size()]),
                vpc.getCidr());
    }

    // Subscriber to ACL replace events. On acl replace event, if the vpc for the tier is enabled for
    // distributed routing send the ACL update to all the hosts on which VPC spans
    public class NetworkAclEventsSubscriber implements MessageSubscriber {
        @Override
        public void onPublishMessage(String senderAddress, String subject, Object args) {
            try {
                NetworkVO network = (NetworkVO) args;
                String bridgeName=generateBridgeNameForVpc(network.getVpcId());
                if (network.getVpcId() != null && isVpcEnabledForDistributedRouter(network.getVpcId())) {
                    long vpcId = network.getVpcId();
                    OvsVpcRoutingPolicyConfigCommand cmd = prepareVpcRoutingPolicyUpdate(vpcId);
                    cmd.setSequenceNumber(getNextRoutingPolicyUpdateSequenceNumber(vpcId));

                    // get the list of hosts on which VPC spans (i.e hosts that need to be aware of VPC
                    // network ACL update)
                    List<Long> vpcSpannedHostIds = _ovsNetworkToplogyGuru.getVpcSpannedHosts(vpcId);
                    for (Long id: vpcSpannedHostIds) {
                        if (!sendVpcRoutingPolicyChangeUpdate(cmd, id, bridgeName)) {
                            s_logger.debug("Failed to send VPC routing policy change update to host : " + id +
                                    ". But moving on with sending the updates to the rest of the hosts.");
                        }
                    }
                }
            } catch (Exception e) {
                s_logger.debug("Failed to send VPC routing policy change updates all hosts in vpc", e);
            }
        }
    }

    private OvsVpcRoutingPolicyConfigCommand prepareVpcRoutingPolicyUpdate(long vpcId) {

        List<OvsVpcRoutingPolicyConfigCommand.Acl> acls = new ArrayList<>();
        List<OvsVpcRoutingPolicyConfigCommand.Tier> tiers = new ArrayList<>();

        VpcVO vpc = _vpcDao.findById(vpcId);
        List<? extends Network> vpcNetworks =  _vpcMgr.getVpcNetworks(vpcId);
        assert (vpc != null && (vpcNetworks != null && !vpcNetworks.isEmpty())): "invalid vpc id";

        for (Network network : vpcNetworks) {
            Long networkAclId = network.getNetworkACLId();
            if (networkAclId == null)
                continue;
            NetworkACLVO networkAcl = _networkACLDao.findById(networkAclId);

            List<OvsVpcRoutingPolicyConfigCommand.AclItem> aclItems = new ArrayList<>();
            List<NetworkACLItemVO> aclItemVos = _networkACLItemDao.listByACL(networkAclId);
            for (NetworkACLItemVO aclItem : aclItemVos) {
                String[] sourceCidrs = aclItem.getSourceCidrList().toArray(new String[aclItem.getSourceCidrList().size()]);

                aclItems.add(new OvsVpcRoutingPolicyConfigCommand.AclItem(
                        aclItem.getNumber(), aclItem.getUuid(), aclItem.getAction().name(),
                        aclItem.getTrafficType().name(),
                        ((aclItem.getSourcePortStart() != null) ?aclItem.getSourcePortStart().toString() :null),
                        ((aclItem.getSourcePortEnd() != null) ?aclItem.getSourcePortEnd().toString() :null),
                        aclItem.getProtocol(),
                        sourceCidrs));
            }

            OvsVpcRoutingPolicyConfigCommand.Acl acl = new OvsVpcRoutingPolicyConfigCommand.Acl(networkAcl.getUuid(),
                    aclItems.toArray(new OvsVpcRoutingPolicyConfigCommand.AclItem[aclItems.size()]));
            acls.add(acl);

            OvsVpcRoutingPolicyConfigCommand.Tier tier = new OvsVpcRoutingPolicyConfigCommand.Tier(network.getUuid(),
                    network.getCidr(), networkAcl.getUuid());
            tiers.add(tier);
        }

        OvsVpcRoutingPolicyConfigCommand cmd = new OvsVpcRoutingPolicyConfigCommand(vpc.getUuid(), vpc.getCidr(),
                acls.toArray(new OvsVpcRoutingPolicyConfigCommand.Acl[acls.size()]),
                tiers.toArray(new OvsVpcRoutingPolicyConfigCommand.Tier[tiers.size()]));
        return cmd;
    }

    private boolean sendVpcRoutingPolicyChangeUpdate(OvsVpcRoutingPolicyConfigCommand updateCmd, long hostId, String bridgeName) {
        try {
            s_logger.debug("Sending VPC routing policies change update to the host " + hostId);
            updateCmd.setHostId(hostId);
            updateCmd.setBridgeName(bridgeName);
            Answer ans = _agentMgr.send(hostId, updateCmd);
            if (ans.getResult()) {
                s_logger.debug("Successfully updated the host " + hostId + " with latest VPC routing policies." );
                return true;
            }  else {
                s_logger.debug("Failed to update the host " + hostId + " with latest routing policies." );
                return false;
            }
        } catch (Exception e) {
            s_logger.debug("Failed to updated the host " + hostId + " with latest routing policies due to" , e );
            return false;
        }
    }

    private long getNextTopologyUpdateSequenceNumber(final long vpcId) {

        try {
            return  Transaction.execute(new TransactionCallback<Long>() {
                @Override
                public Long doInTransaction(TransactionStatus status) {
                    VpcDistributedRouterSeqNoVO seqVo = _vpcDrSeqNoDao.findByVpcId(vpcId);
                    if (seqVo == null) {
                        seqVo = new VpcDistributedRouterSeqNoVO(vpcId);
                        _vpcDrSeqNoDao.persist(seqVo);
                    }
                    seqVo = _vpcDrSeqNoDao.lockRow(seqVo.getId(), true);
                    seqVo.incrTopologyUpdateSequenceNo();
                    _vpcDrSeqNoDao.update(seqVo.getId(), seqVo);
                    return seqVo.getTopologyUpdateSequenceNo();
                }
            });
        } finally {

        }
    }

    private long getNextRoutingPolicyUpdateSequenceNumber(final long vpcId) {

        try {
            return  Transaction.execute(new TransactionCallback<Long>() {
                @Override
                public Long doInTransaction(TransactionStatus status) {
                    VpcDistributedRouterSeqNoVO seqVo = _vpcDrSeqNoDao.findByVpcId(vpcId);
                    if (seqVo == null) {
                        seqVo = new VpcDistributedRouterSeqNoVO(vpcId);
                        _vpcDrSeqNoDao.persist(seqVo);
                    }
                    seqVo = _vpcDrSeqNoDao.lockRow(seqVo.getId(), true);
                    seqVo.incrPolicyUpdateSequenceNo();
                    _vpcDrSeqNoDao.update(seqVo.getId(), seqVo);
                    return seqVo.getPolicyUpdateSequenceNo();
                }
            });
        } finally {

        }
    }
}


text:
#import "RCTViewManager.h"

@interface AIRMapManager : RCTViewManager

@end

redpajama_set_name: RedPajamaGithub


text:
tsip_session_invite.prototype = Object.create(tsip_session.prototype);
tsip_event_invite.prototype = Object.create(tsip_event.prototype);

tsip_session_invite.prototype.o_stream_local = null;
tsip_session_invite.prototype.o_stream_remote = null;

/**
* SIP INVITE event types
*/
var tsip_event_invite_type_e =
{
	// ============================
	//	Sip Events
	//
	I_NEW_CALL: 0,

	// in-dialog requests/reponses
	I_REQUEST: 100,
	I_AO_REQUEST: 101,

	// 3GPP TS 24.629: Explicit Call Transfer (ECT)
	O_ECT_TRYING: 200,
	O_ECT_ACCEPTED: 201,
	O_ECT_COMPLETED: 202,
	O_ECT_FAILED: 203,
	O_ECT_NOTIFY: 204,
	I_ECT_REQUESTED: 205,
	I_ECT_NEW_CALL: 206,
	I_ECT_COMPLETED: 207,
	I_ECT_FAILED: 208,
	I_ECT_NOTIFY: 209,

    /* BFCP (rfc4582) */
    M_BFCP_INFO: 300,

	// ============================
	//	Media Events
	//

	M_EARLY_MEDIA: 400,
	M_UPDATING: 401, // Trying to update from Audio -> Video for example
	M_UPDATED: 402, // succeed to update
	M_STREAM_CONNECTING: 403,
	M_STREAM_CONNECTED: 404,
    M_STREAM_LOCAL_REQUESTED: 405,
    M_STREAM_LOCAL_ACCEPTED: 406,
    M_STREAM_LOCAL_REFUSED: 407,
    M_STREAM_LOCAL_ADDED: 408,
    M_STREAM_LOCAL_REMOVED: 409,
    M_STREAM_REMOTE_ADDED: 410,
    M_STREAM_REMOTE_REMOVED: 411,

	/* 3GPP TS 24.610: Communication Hold */
	M_LOCAL_HOLD_OK: 500,
	M_LOCAL_HOLD_NOK: 501,
	M_LOCAL_RESUME_OK: 502,
	M_LOCAL_RESUME_NOK: 503,
	M_REMOTE_HOLD: 504,
	M_REMOTE_RESUME:505

};

/**
* SIP INVITE session
* @ctor
* Signature: tsip_session_invite(o_stack, ...set())
* @tparam tsip_stack o_stack SIP stack to use to create the session
*
@code
// creates a session to call 'alice'
var o_session = new tsip_session_invite(o_stack,
    tsip_session.prototype.SetToStr("alice"),
    tsip_session.prototype.SetCaps("+sip.ice"),
    tsip_session.prototype.SetHeader("Purpose", "Calling 'alice'")
);
@endcode
*/
function tsip_session_invite(o_stack) {
    tsip_session.call(this, o_stack);
    this.__set(Array.prototype.slice.call(arguments, 1));
}

/**
* SIP INVITE event.

* Used to report INVITE events via @ref tsip_stack::on_event_invite and @ref tsip_stack::on_event_dialog
* @ctor
* @tparam tsip_session_invite o_session SIP session
* @tparam int i_code Event code
* @tparam String s_phrase Event description
* @tparam tsip_message o_sip_message SIP message
* @tparam tsip_event_invite_type_e e_invite_type INVITE event type
*/
function tsip_event_invite(o_session, i_code, s_phrase, o_sip_message, e_invite_type) {
    tsip_event.call(this, o_session, i_code, s_phrase, o_sip_message, tsip_event_type_e.INVITE);
    this.e_invite_type = e_invite_type;
}

tsip_session_invite.prototype.get_stream_local = function () {
    return this.o_stream_local;
}

tsip_session_invite.prototype.get_stream_remote = function () {
    return this.o_stream_remote;
}

/*
 Internal function
*/
tsip_session_invite.prototype.__set_stream_local = function (o_stream) {
    this.o_stream_local = o_stream;
}

/*
Internal function
*/
tsip_session_invite.prototype.__set_stream_remote = function (o_stream) {
    this.o_stream_remote = o_stream;
}

/**
* Makes and audio/video call.
 Sends SIP INVITE request.
 The session state will be reported through @ref tsip_stack::on_event_dialog and @ref tsip_stack::on_event_invite.
*
* Signature: call(e_media_type, ...set())
* @tparam tmedia_type_e e_media_type media type. For now, only tmedia_type_e.AUDIO and tmedia_type_e.AUDIO_VIDEO are supported.
* @treturn int zero if succeed and non-zero otherwise
* @sa @ref hold()
 @ref resume()
*
@code
o_session.call(tmedia_type_e.AUDIO_VIDEO,
    tsip_session.prototype.SetHeader("Purpose", "Calling someone")
);
@endcode
*/
tsip_session_invite.prototype.call = function(e_media_type){
    if (this.o_stack.e_state != tsip_transport_state_e.STARTED) {
        tsk_utils_log_error("Stack not started");
        return -2;
    }

    var i_ret = -1;
    var o_action = new tsip_action(tsip_action_type_e.INVITE);
    if(o_action){
        var b_new_dialog = false;
        o_action.media.e_type = e_media_type;
        var o_dialog = this.o_stack.o_layer_dialog.find_by_ss(this);
        if (!o_dialog) {
            b_new_dialog = true;
            o_dialog = this.o_stack.o_layer_dialog.dialog_new(tsip_dialog_type_e.INVITE, this);
        }
        if((i_ret = o_dialog.fsm_act(o_action.e_type, null, o_action)) == 0){
            if(b_new_dialog){ // otherwise we are trying to refresh the media type and the type will be updated if 200 OK
                this.media.e_type = e_media_type;
            }
        }
    }

	return i_ret;
}

/**
* Puts the call on hold.
 The hold/resume state will be reported through @ref tsip_stack::on_event_invite.
*
* Signature: hold(e_media_type, ...set())
* @tparam tmedia_type_e e_media_type media type to hold. Should be the same media type used to make the call.
* @treturn int zero if succeed and non-zero otherwise
* @sa @ref call()
 @ref resume()
*
@code
o_session.hold(tmedia_type_e.AUDIO_VIDEO,
    tsip_session.prototype.SetHeader("Purpose", "Holding the call")
);
@endcode
*/
tsip_session_invite.prototype.hold = function(e_media_type){
    if (this.o_stack.e_state != tsip_transport_state_e.STARTED) {
        tsk_utils_log_error("Stack not started");
        return -2;
    }

    var i_ret = -1;
    var o_action = new tsip_action(tsip_action_type_e.HOLD);
    if(o_action){
        o_action.media.e_type = e_media_type;
        i_ret = this.__action_handle(o_action);
    }

	return i_ret;
}

/**
* Resumes the call.
 The hold/resume state will be reported through @ref tsip_stack::on_event_invite.
*
* Signature: resume(e_media_type, ...set())
* @tparam tmedia_type_e e_media_type media type to resume. Should be the same media type used to make the call.
* @treturn int zero if succeed and non-zero otherwise
* @sa @ref call()
 @ref hold()
*
@code
o_session.resume(tmedia_type_e.AUDIO_VIDEO,
    tsip_session.prototype.SetHeader("Purpose", "Resuming the call")
);
@endcode
*/
tsip_session_invite.prototype.resume = function(e_media_type){
    if (this.o_stack.e_state != tsip_transport_state_e.STARTED) {
        tsk_utils_log_error("Stack not started");
        return -2;
    }

    var i_ret = -1;
    var o_action = new tsip_action(tsip_action_type_e.RESUME);
    if(o_action){
        o_action.media.e_type = e_media_type;
        i_ret = this.__action_handle(o_action);
    }

	return i_ret;
}

/**
* Sends SIP INFO message. The session must be connected or in early-media state.

* Signature: info(o_content, s_content_type, ...set())
* @tparam Object o_content Message content. Could be a String or ArrayBuffer
* @tparam String s_content_type Message content type
* @treturn int zero if succeed and non-zero otherwise
*
@code
o_session.info("Hello world!", "text/plain");
@endcode
*/
tsip_session_invite.prototype.info = function (o_content, s_content_type) {
    if (this.o_stack.e_state != tsip_transport_state_e.STARTED) {
        tsk_utils_log_error("Stack not started");
        return -2;
    }

    var i_ret = -1;
    var o_action = new tsip_action(tsip_action_type_e.INFO);
    if (o_action) {
        if (s_content_type) {
            o_action.add_headers(new tsip_header_Content_Type(s_content_type));
        }
        o_action.set_content(o_content);
        i_ret = this.__action_handle(o_action);
    }

    return i_ret;
}

/**
* Sends DTMF digit using SIP INFO. The session must be connected or in early-media state.

* Signature: dtmf(...set())
* @tparam char c_digit Digit to send
* @treturn int zero if succeed and non-zero otherwise
*
@code
// sends sharp digit
o_session.dtmf('#');
@endcode
*/
tsip_session_invite.prototype.dtmf = function (c_digit) {
    if (this.o_stack.e_state != tsip_transport_state_e.STARTED) {
        tsk_utils_log_error("Stack not started");
        return -2;
    }

    if (!c_digit) {
        tsk_utils_log_error("Invalid parameter");
        return -1;
    }
    var o_action = new tsip_action(tsip_action_type_e.DTMF_SEND);
    if (o_action) {
        o_action.add_headers(new tsip_header_Content_Type("application/dtmf-relay"));
        o_action.set_content(tsk_string_format("Signal={0}\r\nDuration={1}", c_digit, 120));
        return this.__action_handle(o_action);
    }
    return -3;
}

/**
* Transfers the call using SIP REFER. The session must be connected or in early-media state.

* Signature: dtmf(...set())
* @tparam String s_to Transfer destination uri or phone number
* @treturn int zero if succeed and non-zero otherwise
*
@code
o_session.transfer('alice');
// or
o_session.transfer('sip:alice@doubango.org');
@endcode
*/
tsip_session_invite.prototype.transfer = function (s_to) {
    if (!s_to) {
        tsk_utils_log_error('Invalid parameter');
        return -1;
    }
    if (this.o_stack.e_state != tsip_transport_state_e.STARTED) {
        tsk_utils_log_error("Stack not started");
        return -2;
    }
    var o_uri_to = tsip_uri_make_valid(s_to, this.o_stack.network.o_uri_realm.s_host);
    if (!o_uri_to) {
        tsk_utils_log_error("%s is not a valid SIP Uri", s_to);
        return -3;
    }

    var i_ret = -1;
    var o_action = new tsip_action(tsip_action_type_e.ECT);
    if (o_action) {
        o_action.ect.s_to = tsip_uri_tostring(o_uri_to, false, false);
        i_ret = this.__action_handle(o_action);
    }

    return i_ret;
}

/**
* Accepts incoming tgransfer request
* @treturn int zero if succeed and non-zero otherwise
*/
tsip_session_invite.prototype.transfer_accept = function () {
    return this.__action_any(tsip_action_type_e.ECT_ACCEPT);
}

/**
* Rejects incoming tgransfer request
* @treturn int zero if succeed and non-zero otherwise
*/
tsip_session_invite.prototype.transfer_reject = function () {
    return this.__action_any(tsip_action_type_e.ECT_REJECT);
}

/**
Starts sharing your entire desktop or an App using BFCP(rfc4582). Requires webrt4all plugin.
* @treturn int zero if succeed and non-zero otherwise
*/
tsip_session_invite.prototype.start_bfcp_share = function () {
    var e_new_media = this.media.e_type;
    switch (this.media.e_type) {
        case tmedia_type_e.AUDIO: e_new_media = tmedia_type_e.AUDIO_BFCPVIDEO; break;
        case tmedia_type_e.VIDEO: e_new_media = tmedia_type_e.VIDEO_BFCPVIDEO; break;
        default: e_new_media = tmedia_type_e.AUDIO_VIDEO_BFCPVIDEO; break;
    }
    return this.call(e_new_media);
}

/**
Stops sharing your entire desktop or an App using BFCP(rfc4582). Requires webrt4all plugin.
* @treturn int zero if succeed and non-zero otherwise
*/
tsip_session_invite.prototype.stop_bfcp_share = function () {
    var e_new_media = this.media.e_type;
    switch (this.media.e_type) {
        case tmedia_type_e.AUDIO_BFCPVIDEO: e_new_media = tmedia_type_e.AUDIO; break;
        case tmedia_type_e.VIDEO_BFCPVIDEO: e_new_media = tmedia_type_e.VIDEO; break;
        default: e_new_media = tmedia_type_e.AUDIO_VIDEO; break;
    }
    return this.call(e_new_media);
}

/** mutes/unmutes session
* @treturn int zero if succeed and non-zero otherwise
*/
tsip_session_invite.prototype.set_mute = function (s_media, b_mute) {
    var o_action = new tsip_action(tsip_action_type_e.MUTE);
    if (o_action) {
        o_action.mute.b_muted = b_mute;
        o_action.mute.s_media = s_media;
        return this.__action_handle(o_action);
    }
    return -3;
}


text:
package colors

import (
	"fmt"
	"regexp"
	"strings"
)

const (
	hexRegexString = "^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$"
	hexFormat      = "#%02x%02x%02x"
	hexShortFormat = "#%1x%1x%1x"
	hexToRGBFactor = 17
)

var (
	hexRegex = regexp.MustCompile(hexRegexString)
)

// HEXColor represents a HEX color
type HEXColor struct {
	hex string
}

// ParseHEX validates an parses the provided string into a HEXColor object
func ParseHEX(s string) (*HEXColor, error) {

	s = strings.ToLower(s)

	if !hexRegex.MatchString(s) {
		return nil, ErrBadColor
	}

	return &HEXColor{hex: s}, nil
}

// String returns the string representation on the HEXColor
func (c *HEXColor) String() string {
	return c.hex
}

// ToHEX converts the HEXColor to a HEXColor
// it's here to satisfy the Color interface
func (c *HEXColor) ToHEX() *HEXColor {
	return c
}

// ToRGB converts the HEXColor to and RGBColor
func (c *HEXColor) ToRGB() *RGBColor {

	var r, g, b uint8

	if len(c.hex) == 4 {
		fmt.Sscanf(c.hex, hexShortFormat, &r, &g, &b)
		r *= hexToRGBFactor
		g *= hexToRGBFactor
		b *= hexToRGBFactor
	} else {
		fmt.Sscanf(c.hex, hexFormat, &r, &g, &b)
	}

	return &RGBColor{R: r, G: g, B: b}
}

// ToRGBA converts the HEXColor to an RGBAColor
func (c *HEXColor) ToRGBA() *RGBAColor {

	rgb := c.ToRGB()

	return &RGBAColor{R: rgb.R, G: rgb.G, B: rgb.B, A: 1}
}

// IsLight returns whether the color is perceived to be a light color
func (c *HEXColor) IsLight() bool {
	return c.ToRGB().IsLight()
}

// IsDark returns whether the color is perceived to be a dark color
func (c *HEXColor) IsDark() bool {
	return !c.IsLight()
}

// RGBA implements color.Color interface
func (c *HEXColor) RGBA() (r, g, b, a uint32) {
	return c.ToRGBA().RGBA()
}

// Equal reports whether c is the same color as d
func (c *HEXColor) Equal(d Color) bool {
	return c.ToRGBA().String() == d.ToRGBA().String()
}


text:
import React from 'react';
import { Emoji, EmojiDataManager } from 'interweave-emoji';
import { render } from 'rut-dom';
import { PreviewBar, PreviewBarProps } from '../src/PreviewBar';
import { CAT_EMOJI, ContextWrapper } from './mocks';

describe('PreviewBar', () => {
	const props: PreviewBarProps = {
		emoji: CAT_EMOJI,
		hideEmoticon: false,
		hideShortcodes: false,
	};

	beforeEach(() => {
		props.emoji = EmojiDataManager.getInstance('en', '0.0.0').EMOJIS['1F642'];
	});

	it('renders a preview', () => {
		const { root } = render<PreviewBarProps>(<PreviewBar {...props} />, {
			wrapper: <ContextWrapper />,
		});

		expect(root.findOne('section')).toMatchSnapshot();
	});

	describe('with emoji', () => {
		it('can customize class name', () => {
			const { root } = render<PreviewBarProps>(<PreviewBar {...props} />, {
				wrapper: (
					<ContextWrapper
						classNames={{
							preview: 'test-preview',
							previewEmoji: 'test-preview-emoji',
							previewContent: 'test-preview-content',
							previewTitle: 'test-preview-title',
							previewSubtitle: 'test-preview-subtitle',
						}}
					/>
				),
			});
			const divs = root.find('div');

			expect(root.findOne('section')).toHaveProp('className', 'test-preview');
			expect(divs[0]).toHaveProp('className', 'test-preview-emoji');
			expect(divs[1]).toHaveProp('className', 'test-preview-content');
			expect(divs[2]).toHaveProp('className', 'test-preview-title');
			expect(divs[3]).toHaveProp('className', 'test-preview-subtitle');
		});

		it('renders an emoji', () => {
			const { root } = render<PreviewBarProps>(<PreviewBar {...props} />);

			expect(root.findOne(Emoji)).toHaveProps(
				expect.objectContaining({
					enlargeEmoji: true,
					hexcode: props.emoji!.hexcode,
				}),
			);
		});

		it('displays title', () => {
			const { root } = render<PreviewBarProps>(<PreviewBar {...props} />);

			expect(root).toContainNode('Slightly smiling face');
		});

		it('doesnt display title if no label or name', () => {
			const { root } = render<PreviewBarProps>(
				<PreviewBar
					{...props}
					emoji={{
						...props.emoji!,
						label: '',
					}}
				/>,
			);

			expect(root.find('div', { className: 'interweave-picker__preview-title' })).toHaveLength(0);
		});

		it('displays subtitle', () => {
			const { root } = render<PreviewBarProps>(<PreviewBar {...props} />);

			expect(root).toContainNode(':) :slightly_smiling_face:');
		});

		it('displays subtitle without emoticon', () => {
			const { root } = render<PreviewBarProps>(
				<PreviewBar
					{...props}
					emoji={{
						...props.emoji!,
						emoticon: '',
					}}
				/>,
			);

			expect(root).toContainNode(':slightly_smiling_face:');
		});

		it('displays subtitle without shortcodes', () => {
			const { root } = render<PreviewBarProps>(
				<PreviewBar
					{...props}
					emoji={{
						...props.emoji!,
						canonical_shortcodes: [],
					}}
				/>,
			);

			expect(root).toContainNode(':)');
		});

		it('hides emoticon in subtitle', () => {
			const { root } = render<PreviewBarProps>(<PreviewBar {...props} hideEmoticon />);

			expect(root).toContainNode(':slightly_smiling_face:');
		});

		it('hides shortcodes in subtitle', () => {
			const { root } = render<PreviewBarProps>(<PreviewBar {...props} hideShortcodes />);

			expect(root).toContainNode(':)');
		});

		it('doesnt display subtitle if no emoticon or shortcodes', () => {
			const { root } = render<PreviewBarProps>(
				<PreviewBar
					{...props}
					emoji={{
						...props.emoji!,
						canonical_shortcodes: [],
						emoticon: '',
					}}
				/>,
			);

			expect(root.find('div', { className: 'interweave-picker__preview-subtitle' })).toHaveLength(
				0,
			);
		});

		it('doesnt display subtitle if all are hidden', () => {
			const { root } = render<PreviewBarProps>(
				<PreviewBar {...props} hideEmoticon hideShortcodes />,
			);

			expect(root.find('div', { className: 'interweave-picker__preview-subtitle' })).toHaveLength(
				0,
			);
		});
	});

	describe('no emoji', () => {
		it('can customize class name', () => {
			const { root } = render<PreviewBarProps>(
				<PreviewBar {...props} emoji={null} noPreview="Preview" />,
				{
					wrapper: (
						<ContextWrapper
							classNames={{
								preview: 'test-preview',
								noPreview: 'test-preview-none',
							}}
						/>
					),
				},
			);

			expect(root.findOne('section')).toHaveProp('className', 'test-preview');
			expect(root.findOne('div')).toHaveProp('className', 'test-preview-none');
		});

		it('renders no preview message', () => {
			const none = 'No preview';
			const { root } = render<PreviewBarProps>(<PreviewBar {...props} emoji={null} />, {
				wrapper: (
					<ContextWrapper
						messages={{
							noPreview: none,
						}}
					/>
				),
			});

			expect(root).toContainNode(none);
		});

		it('renders no preview element', () => {
			const none = <b>No preview</b>;
			const { root } = render<PreviewBarProps>(
				<PreviewBar {...props} emoji={null} noPreview={none} />,
			);

			expect(root).toContainNode(none);
		});

		it('renders nothing if no preview message or preview element', () => {
			const { root } = render<PreviewBarProps>(
				<PreviewBar {...props} emoji={null} noPreview={null} />,
				{
					wrapper: (
						<ContextWrapper
							messages={{
								noPreview: '',
							}}
						/>
					),
				},
			);

			expect(root.findOne('section')).toMatchSnapshot();
		});
	});
});


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W25854_extracted</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans17.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Skarston

    <p class="styleSans18.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">1-12

    <p class="styleSans18.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Unit Gas

    <p class="styleSans14.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Compressor

    <p class="styleSans312.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">\ISWW
Cu lcgvmd

mm, .' MM "v. WW J.' hm
V
u\
1
{Mn- [mum-h
V
"MA [lav \l-bb'm

    <p class="styleSans50.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Gas Gath er" . r , "  .. ONEOK I _  .
Processed at the Stateline Plant in Williams County mu m;  :hew ONEOK gamean hoes .'nr :mxch 51am was contractual rflpar !,

j Slamil

    <p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">


text:
package com.getcapacitor.plugin.notification;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Class used to abstract storage for notification data
 */
public class NotificationStorage {

  // Key for private preferences
  private static final String NOTIFICATION_STORE_ID = "NOTIFICATION_STORE";

  // Key used to save action types
  private static final String ACTION_TYPES_ID = "ACTION_TYPE_STORE";

  private static final String ID_KEY = "notificationIds";

  private Context context;

  public NotificationStorage(Context context) {
    this.context = context;
  }

  /**
   * Persist the id of currently scheduled notification
   */
  public void appendNotificationIds(List<LocalNotification> localNotifications) {
    SharedPreferences storage = getStorage(NOTIFICATION_STORE_ID);
    SharedPreferences.Editor editor = storage.edit();
    long creationTime = new Date().getTime();
    for (LocalNotification request : localNotifications) {
      String key = request.getId().toString();
      editor.putLong(key, creationTime);
    }
    editor.apply();
  }

  public List<String> getSavedNotificationIds() {
    SharedPreferences storage = getStorage(NOTIFICATION_STORE_ID);
    Map<String, ?> all = storage.getAll();
    if (all != null) {
      return new ArrayList<>(all.keySet());
    }
    return new ArrayList<>();
  }

  /**
   * Remove the stored notifications
   */
  public void deleteNotification(String id) {
    SharedPreferences.Editor editor = getStorage(NOTIFICATION_STORE_ID).edit();
    editor.remove(id);
    editor.apply();
  }

  /**
   * Shared private preferences for the application.
   */
  private SharedPreferences getStorage(String key) {
    return context.getSharedPreferences(key, Context.MODE_PRIVATE);
  }

  /**
   * Writes new action types (actions that being displayed in notification) to storage.
   * Write will override previous data.
   *
   * @param typesMap - map with groupId and actionArray assigned to group
   */
  public void writeActionGroup(Map<String, NotificationAction[]> typesMap) {
    Set<String> typesIds = typesMap.keySet();
    for (String id : typesIds) {
      SharedPreferences.Editor editor = getStorage(ACTION_TYPES_ID + id).edit();
      editor.clear();
      NotificationAction[] notificationActions = typesMap.get(id);
      editor.putInt("count", notificationActions.length);
      for (int i = 0; i < notificationActions.length; i++) {
        editor.putString("id" + i, notificationActions[i].getId());
        editor.putString("title" + i, notificationActions[i].getTitle());
        editor.putBoolean("input" + i, notificationActions[i].isInput());
      }
      editor.apply();
    }
  }

  /**
   * Retrieve array of notification actions per ActionTypeId
   *
   * @param forId - id of the group
   */
  public NotificationAction[] getActionGroup(String forId) {
    SharedPreferences storage = getStorage(ACTION_TYPES_ID + forId);
    int count = storage.getInt("count", 0);
    NotificationAction[] actions = new NotificationAction[count];
    for (int i = 0; i < count; i++) {
      String id = storage.getString("id" + i, "");
      String title = storage.getString("title" + i, "");
      Boolean input = storage.getBoolean("input" + i, false);
      actions[i] = new NotificationAction(id, title, input);
    }
    return actions;
  }

}


text:
require File.join(File.dirname(__FILE__), '..', '..', 'spec_helper.rb')

given "a menu_element exists" do
  MenuElement.all.destroy!
  request(resource(:menu_elements), :method => "POST",
    :params => { :menu_element => { :id => nil }})
end

describe "resource(:menu_elements)" do
  describe "GET" do

    before(:each) do
      @response = request(resource(:menu_elements))
    end

    it "responds successfully" do
      @response.should be_successful
    end

    it "contains a list of menu_elements" do
      pending
      @response.should have_xpath("//ul")
    end

  end

  describe "GET", :given => "a menu_element exists" do
    before(:each) do
      @response = request(resource(:menu_elements))
    end

    it "has a list of menu_elements" do
      pending
      @response.should have_xpath("//ul/li")
    end
  end

  describe "a successful POST" do
    before(:each) do
      MenuElement.all.destroy!
      @response = request(resource(:menu_elements), :method => "POST",
        :params => { :menu_element => { :id => nil }})
    end

    it "redirects to resource(:menu_elements)" do
      @response.should redirect_to(resource(MenuElement.first), :message => {:notice => "menu_element was successfully created"})
    end

  end
end

describe "resource(@menu_element)" do
  describe "a successful DELETE", :given => "a menu_element exists" do
     before(:each) do
       @response = request(resource(MenuElement.first), :method => "DELETE")
     end

     it "should redirect to the index action" do
       @response.should redirect_to(resource(:menu_elements))
     end

   end
end

describe "resource(:menu_elements, :new)" do
  before(:each) do
    @response = request(resource(:menu_elements, :new))
  end

  it "responds successfully" do
    @response.should be_successful
  end
end

describe "resource(@menu_element, :edit)", :given => "a menu_element exists" do
  before(:each) do
    @response = request(resource(MenuElement.first, :edit))
  end

  it "responds successfully" do
    @response.should be_successful
  end
end

describe "resource(@menu_element)", :given => "a menu_element exists" do

  describe "GET" do
    before(:each) do
      @response = request(resource(MenuElement.first))
    end

    it "responds successfully" do
      @response.should be_successful
    end
  end

  describe "PUT" do
    before(:each) do
      @menu_element = MenuElement.first
      @response = request(resource(@menu_element), :method => "PUT",
        :params => { :menu_element => {:id => @menu_element.id} })
    end

    it "redirect to the article show action" do
      @response.should redirect_to(resource(@menu_element))
    end
  end

end


text:
package test.drinkwater.examples.drinktracker.benchmark;

import drinkwater.ApplicationBuilder;
import drinkwater.core.DrinkWaterApplication;
import examples.drinkwater.drinktracker.asbean.ApplicationAsBeanObject;
import examples.drinkwater.drinktracker.asbeanclass.ApplicationAsBeanClass;
import examples.drinkwater.drinktracker.asrest.ApplicationAsRest;
import examples.drinkwater.drinktracker.model.*;
import org.junit.Assert;
import org.junit.Test;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.assertTrue;

/**
 * Created by A406775 on 28/12/2016.
 */
public class SimpleBenchMark {

    private int LOOP_COUNT = 1;

    @Test
    public void performBenchMark() throws Exception {

        long timeAsRest = 0;
        long timeAsBeanObject = 0;
        long timeAsBeanClass = 0;
        long timeWithoutDW = 0;

//        //without DrinkWater
        timeWithoutDW = benchMarkWithoutDW();
//        //rest
        timeAsRest = benchMarkThisConfig(new ApplicationAsRest());
//        //beanobject
        timeAsBeanObject = benchMarkThisConfig(new ApplicationAsBeanObject());
//        //as beanClass
        timeAsBeanClass = benchMarkThisConfig(new ApplicationAsBeanClass());

        printReport(timeWithoutDW, timeAsBeanObject, timeAsBeanClass, timeAsRest);

        //just to be green
        assertTrue(true);
    }

    private long benchMarkWithoutDW() throws Exception {
        //create service using classes
        AccountService accountService = new AccountService();
        DrinkTrackerService numberService = new DrinkTrackerService();
        numberService.setWaterVolumeFormatter(new DefaultWaterVolumeFormatter());
        numberService.setWaterVolumeRepository(new WaterVolumeFileRepository("c:/temp"));
        numberService.setAccountService(accountService);

        return dowork(accountService, numberService);
    }

    private long benchMarkThisConfig(ApplicationBuilder builder) throws Exception {

        DrinkWaterApplication app = DrinkWaterApplication.create();
        try {

            app.addServiceBuilder(builder);
            app.start();

            //get ref to the services
            IAccountService accountDWService = app.getService(IAccountService.class);
            IDrinkTrackerService numberDWService = app.getService(IDrinkTrackerService.class);

            //start bench
            return dowork(accountDWService, numberDWService);
        } finally {
            app.stop();
        }

    }

    private void printReport(long timeWithoutDW, long timeAsBeanObject, long timeAsBeanClass, long timeAsRest) {
        long diff_with_bean_object = timeAsBeanObject - timeWithoutDW;
        long diff_with_bean_class = timeAsBeanClass - timeWithoutDW;
        long diff_with_rest = timeAsRest - timeWithoutDW;

        System.out.println("BENCHMARK WITH loop count : " + LOOP_COUNT);
        System.out.println("---------------------------------------------------");
        System.out.println("");
        System.out.println("test with DIRECT_OBJECT took            :  " + TimeUnit.NANOSECONDS.toMillis(timeWithoutDW) + " millis (" + TimeUnit.NANOSECONDS.toSeconds(timeWithoutDW) + " sec)");
        System.out.println("test with BEANOBJECT took               :  " + TimeUnit.NANOSECONDS.toMillis(timeAsBeanObject) + " millis (" + TimeUnit.NANOSECONDS.toSeconds(timeAsBeanObject) + " sec)");
        System.out.println("test with BEANCLASS took                :  " + TimeUnit.NANOSECONDS.toMillis(timeAsBeanClass) + " millis (" + TimeUnit.NANOSECONDS.toSeconds(timeAsBeanClass) + " sec)");
        System.out.println("test with REST took                     :  " + TimeUnit.NANOSECONDS.toMillis(timeAsRest) + " millis (" + TimeUnit.NANOSECONDS.toSeconds(timeAsRest) + " sec)");
        System.out.println("");
        System.out.println("test with BEANOBJECT  was slower  by    :  " + TimeUnit.NANOSECONDS.toMillis(diff_with_bean_object) + " millis (" + TimeUnit.NANOSECONDS.toSeconds(diff_with_bean_object) + " sec)");
        System.out.println("test with BEANCLASS  was slower  by     :  " + TimeUnit.NANOSECONDS.toMillis(diff_with_bean_class) + " millis (" + TimeUnit.NANOSECONDS.toSeconds(diff_with_bean_class) + " sec)");
        System.out.println("test with RESTCLASS was slower   by     :  " + TimeUnit.NANOSECONDS.toMillis(diff_with_rest) + " millis (" + TimeUnit.NANOSECONDS.toSeconds(diff_with_rest) + " sec)");
        System.out.println("");
        System.out.println("---------------------------------------------------");
    }

    private long dowork(IAccountService accountService, IDrinkTrackerService numberService) throws Exception {
        Account acc = accountService.createAccount("cedric", "secret");

        //start counter here
        long startTime = System.nanoTime();
        for (int i = 0; i < LOOP_COUNT; i++) {
            acc = accountService.login("cedric", "secret");
            numberService.saveVolume(acc, 10);
            numberService.saveVolume(acc, 20);
            numberService.saveVolume(acc, 30);
            numberService.saveVolume(acc, 40);
            numberService.saveVolume(acc, 50);
            numberService.saveVolume(acc, 60);
            List<String> numbers = numberService.getVolumes(acc);

            //perfrom some assertions
            Assert.assertEquals(6, numbers.size());
            //delete file and logoff
            numberService.clearVolumes(acc);
            accountService.logoff(acc);

            assertTrue(true);
        }

        accountService.clearAccounts();

        long ellapsedTime = System.nanoTime() - startTime;

        return ellapsedTime;
    }
}


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'ZipCode'
        db.create_table('development_zipcode', (
            ('id',       self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('zipcode',  self.gf('django.db.models.fields.CharField')(max_length=5)),
            ('name',     self.gf('django.db.models.fields.CharField')(max_length=100)),
            ('state',    self.gf('django.db.models.fields.CharField')(max_length=2)),
            ('geometry', self.gf('django.contrib.gis.db.models.fields.MultiPolygonField')()), # where is SRID?
        ))
        db.send_create_signal('development', ['ZipCode'])

    def backwards(self, orm):
        # Deleting model 'ZipCode'
        db.delete_table('development_zipcode')

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        'auth.permission': {
            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'development.communitytype': {
            'Meta': {'object_name': 'CommunityType'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'development.municipality': {
            'Meta': {'ordering': "['name']", 'object_name': 'Municipality'},
            'communitytype': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['development.CommunityType']", 'null': 'True', 'blank': 'True'}),
            'geometry': ('django.contrib.gis.db.models.fields.MultiPolygonField', [], {}),
            'muni_id': ('django.db.models.fields.IntegerField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'})
        },
        'development.project': {
            'Meta': {'ordering': "['dd_id']", 'object_name': 'Project'},
            'affordable_comment': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'as_of_right': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}),
            'ch40': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['development.ZoningTool']", 'null': 'True', 'blank': 'True'}),
            'clustosrd': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}),
            'commsf': ('django.db.models.fields.FloatField', [], {'null': 'True'}),
            'complyr': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'created_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'project_created_by'", 'null': 'True', 'to': "orm['auth.User']"}),
            'dd_id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'ddname': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'dev_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
            'draft': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'edinstpct': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'emploss': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'gqpop': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            'hotelrms': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'indmfpct': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'last_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'last_modified_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'project_last_modified_by'", 'null': 'True', 'to': "orm['auth.User']"}),
            'lgmultifam': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            'location': ('django.contrib.gis.db.models.fields.PointField', [], {'null': 'True', 'blank': 'True'}),
            'mapcintrnl': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'mfdisc': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'mxduse': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}),
            'ofcmdpct': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'otheremprat2': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'othpct': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'ovr55': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}),
            'parking_spaces': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            'pctaffall': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'phased': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'prjacrs': ('django.db.models.fields.FloatField', [], {'null': 'True'}),
            'projecttype': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['development.ProjectType']", 'null': 'True'}),
            'projecttype_detail': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'rdv': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}),
            'removed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'retpct': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'rndpct': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'rptdemp': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'singfamhu': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            'stalled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'status': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['development.ProjectStatus']"}),
            'taz': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['development.Taz']", 'null': 'True', 'blank': 'True'}),
            'total_cost': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            'total_cost_allocated_pct': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'totemp': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'tothu': ('django.db.models.fields.FloatField', [], {'null': 'True'}),
            'twnhsmmult': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            'url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
            'url_add': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
            'walkscore': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            'whspct': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'xcoord': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'ycoord': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'})
        },
        'development.projectstatus': {
            'Meta': {'object_name': 'ProjectStatus'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '20'})
        },
        'development.projecttype': {
            'Meta': {'ordering': "['order']", 'object_name': 'ProjectType'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'order': ('django.db.models.fields.IntegerField', [], {'default': '0'})
        },
        'development.taz': {
            'Meta': {'ordering': "['taz_id']", 'object_name': 'Taz'},
            'geometry': ('django.contrib.gis.db.models.fields.MultiPolygonField', [], {}),
            'municipality': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['development.Municipality']"}),
            'taz_id': ('django.db.models.fields.IntegerField', [], {'primary_key': 'True'})
        },
        'development.zipcode': {
            'Meta': {'ordering': "['zipcode']", 'object_name': 'ZipCode'},
            'geometry': ('django.contrib.gis.db.models.fields.MultiPolygonField', [], {}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'state': ('django.db.models.fields.CharField', [], {'max_length': '2'}),
            'zipcode': ('django.db.models.fields.CharField', [], {'max_length': '5'})
        },
        'development.zoningtool': {
            'Meta': {'object_name': 'ZoningTool'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '3'})
        }
    }

    complete_apps = ['development']


text:
layout: post
title: Hello world
author: Panu Guyson
---

Hello world, welcome to my new blog.

This blog is written with markdown language with [jekyll](https://jekyllrb.com/) and hosted on [github](https://github.com/).
Thanks [AkshayAgarwal007](https://github.com/AkshayAgarwal007) for beautify theme [Jekyll-Mono](https://github.com/AkshayAgarwal007/Jekyll-Mono).


text:
cryptonite
==========

[![Join the chat at https://gitter.im/vincenthz/cryptonite](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/vincenthz/cryptonite?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Build Status](https://travis-ci.org/haskell-crypto/cryptonite.png?branch=master)](https://travis-ci.org/haskell-crypto/cryptonite)
[![BSD](http://b.repl.ca/v1/license-BSD-blue.png)](http://en.wikipedia.org/wiki/BSD_licenses)
[![Haskell](http://b.repl.ca/v1/language-haskell-lightgrey.png)](http://haskell.org)

Cryptonite is a haskell repository of cryptographic primitives. Each crypto
algorithm has specificities that are hard to wrap in common APIs and types,
so instead of trying to provide a common ground for algorithms, this package
provides a non-consistent low-level API.

If you have no idea what you're doing, please do not use this directly.
Instead, rely on higher level protocols or implementations.

Documentation: [cryptonite on hackage](http://hackage.haskell.org/package/cryptonite)

Stability
---------

Cryptonite APIs are stable, and we only strive to add, not change or remove.
Note that because the API exposed is wide and also expose internals things (for
power users and flexibility), certains APIs can be revised in extreme cases
where we can't just add.

Versioning
----------

Next version of `0.x` is `0.(x+1)`. There's no exceptions, or API related meaning
behind the numbers.

Each versions of stackage (going back 3 stable LTS) has a cryptonite version
that we maintain with security fixes when necessary and are versioned with the
following `0.x.y` scheme.

Coding Style
------------

The coding style of this project mostly follows:
[haskell-style](https://github.com/tibbe/haskell-style-guide/blob/master/haskell-style.md)

Support
-------

cryptonite supports the following platforms:

* Windows >= 8
* OSX >= 10.8
* Linux
* BSDs

On the following architectures:

* x86-64
* i386

On the following haskell versions:

* GHC 7.8.x
* GHC 7.10.x
* GHC 8.0.x
* GHC 8.2.x

Further platforms and architectures probably work too, but since the
maintainer(s) don't have regular access to them, we can't commit to
further support.

Known Building Issues
---------------------

On OSX <= 10.7, the system compiler doesn't understand the '-maes' option, and
with the lack of autodetection feature builtin in .cabal file, it is left on
the user to disable the aesni. See the [Disabling AESNI] section

Disabling AESNI
---------------

It may be useful to disable AESNI for building, testing or runtime purposes.
This is achieved with the *support_aesni* flag.

As part of configure of cryptonite:

```
  cabal configure --flag='-support_aesni'
```

or as part of an installation:

```
  cabal install --constraint="cryptonite -support_aesni"
```

For help with cabal flags, see: [stackoverflow : is there a way to define flags for cabal](http://stackoverflow.com/questions/23523869/is-there-any-way-to-define-flags-for-cabal-dependencies)

Links
-----

* [ChaCha](http://cr.yp.to/chacha.html)
* [ChaCha-test-vectors](https://github.com/secworks/chacha_testvectors.git)
* [Poly1305](http://cr.yp.to/mac.html)
* [Poly1305-test-vectors](http://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-06#page-12)
* [Salsa](http://cr.yp.to/snuffle.html)
* [Salsa128-test-vectors](https://github.com/alexwebr/salsa20/blob/master/test_vectors.128)
* [Salsa256-test-vectors](https://github.com/alexwebr/salsa20/blob/master/test_vectors.256)
* [XSalsa](https://cr.yp.to/snuffle/xsalsa-20081128.pdf)
* [PBKDF2](http://tools.ietf.org/html/rfc2898)
* [PBKDF2-test-vectors](http://www.ietf.org/rfc/rfc6070.txt)
* [Scrypt](http://www.tarsnap.com/scrypt.html)
* [Curve25519](http://cr.yp.to/ecdh.html)
* [Ed25519](http://ed25519.cr.yp.to/papers.html)
* [Ed448-Goldilocks](http://ed448goldilocks.sourceforge.net/)
* [EdDSA-test-vectors](http://www.ietf.org/rfc/rfc8032.txt)
* [AFIS](http://clemens.endorphin.org/cryptography)


text:
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
module Network.IRC.ByteString.Parser
   (
     -- |IRC message types
     ServerName, IRCMsg(..), UserInfo(..)
     -- |Conversion functions
   , toIRCMsg, fromIRCMsg
     -- |Attoparsec parser
   , ircLine
   ) where
import Data.Attoparsec.Char8 as Char8
import qualified Data.Attoparsec.ByteString as Word8
import Data.ByteString.Char8 as BS
  (cons, append, intercalate, ByteString, concat)
import Data.Maybe (fromMaybe)
import Data.Char (isNumber, isAlpha)
import Control.Applicative
import Prelude hiding (takeWhile)

import Network.IRC.ByteString.Config
import Network.IRC.ByteString.Utils

--Types--
type ServerName = ByteString

data IRCMsg = IRCMsg { msgPrefix  :: Maybe (Either UserInfo ServerName)
                     , msgCmd     :: ByteString
                     , msgParams  :: [ByteString]
                     , msgTrail   :: Maybe ByteString
                     }
            deriving (Show, Eq, Read)

data UserInfo = UserInfo { userNick  :: ByteString
                         , userName  :: Maybe ByteString
                         , userHost  :: Maybe ByteString
                         }
              deriving (Eq, Show, Read)

fromIRCMsg :: IRCMsg -> ByteString
fromIRCMsg msg = BS.concat $ [prefix', command', params', trail', "\r\n"]
  where prefix' = case msgPrefix msg of
          Nothing -> ""
          Just (Right serv) -> ':' `cons` serv `append` " "
          Just (Left info)  -> ':' `cons` userNick info
                               `append` maybeUser
                               `append` maybeHost
                               `append` " "
            where
              maybeUser  = maybe ""  ('!' `cons`) (userName info)
              maybeHost  = maybe "" ('@' `cons`) (userHost info)

        command' = msgCmd msg

        paramList = msgParams msg
        params'
          | Prelude.null paramList = ""
          | otherwise = ' ' `cons` intercalate " " (msgParams msg)

        trail' = case msgTrail msg of
            Nothing -> ""
            Just t -> " :" `append` t

toIRCMsg :: IRCParserConfig -> ByteString -> Result IRCMsg
toIRCMsg = parse . ircLine

-- |zero or more spaces as defined by 'isSpace'
ircSpaces c = skipWhile (isIRCSpace c) <?> "optional space"

-- |one or more spaces as defined by 'isSpace'
ircSpaces1 c = satisfy (isIRCSpace c)
               >> skipWhile (isIRCSpace c)
               <?> "required space"

ircLine conf = IRCMsg <$> optional (prefix conf) <*> command <*> params conf <*> trail conf <* optional (string "\r\n")
          <?> "IRC line"

prefix conf = char ':'
              *> eitherP (userInfo <* end) (serverName <* end)
              <?> "prefix"
  where
    end = ircSpaces1 conf <|> endOfInput
    nick = nickParser conf <?> "nick"
    user = userParser conf <?> "user"
    host = hostParser conf <?> "host"
    serverName = host <?> "server name"
    userInfo = UserInfo <$> nick
                        <*> optional (char '!' >> user)
                        <*> optional (char '@' >> host)
                        <?> "user info"

command = (alpha <|> numeric) <?> "command name"
  where
    alpha = takeWhile1 isAlpha
    numeric = n <:> n <:> n <:> pure ""
        where n = satisfy isNumber

params conf = fromMaybe [] <$> optional
              (ircSpaces1 conf >> paramParser conf `sepBy` ircSpaces1 conf)
              <?> "params list"

trail conf = ircSpaces conf
             >> optional (char ':' >> Word8.takeWhile (not . isEndOfLine))
             <?> "message body"