Example usage for java.math BigInteger equals

List of usage examples for java.math BigInteger equals

Introduction

In this page you can find the example usage for java.math BigInteger equals.

Prototype

public boolean equals(Object x) 

Source Link

Document

Compares this BigInteger with the specified Object for equality.

Usage

From source file:org.opendaylight.netvirt.dhcpservice.DhcpExternalTunnelManager.java

public void handleTunnelStateUp(IpAddress tunnelIp, BigInteger interfaceDpn,
        List<ListenableFuture<Void>> futures) {
    LOG.trace("In handleTunnelStateUp tunnelIp {}, interfaceDpn {}", tunnelIp, interfaceDpn);
    synchronized (getTunnelIpDpnKey(tunnelIp, interfaceDpn)) {
        Set<Pair<IpAddress, String>> tunnelIpElanPair = designatedDpnsToTunnelIpElanNameCache
                .get(DhcpMConstants.INVALID_DPID);
        List<BigInteger> dpns = DhcpServiceUtils.getListOfDpns(broker);
        if (tunnelIpElanPair == null || tunnelIpElanPair.isEmpty()) {
            LOG.trace("There are no undesignated DPNs");
            return;
        }/*from  www. j a v a 2 s. co m*/
        WriteTransaction tx = broker.newWriteOnlyTransaction();
        for (Pair<IpAddress, String> pair : tunnelIpElanPair) {
            if (tunnelIp.equals(pair.getLeft())) {
                BigInteger newDesignatedDpn = designateDpnId(tunnelIp, pair.getRight(), dpns);
                if (newDesignatedDpn != null && !newDesignatedDpn.equals(DhcpMConstants.INVALID_DPID)) {
                    Set<String> vmMacAddress = tunnelIpElanNameToVmMacCache.get(pair);
                    if (vmMacAddress != null && !vmMacAddress.isEmpty()) {
                        LOG.trace("Updating DHCP flow for macAddress {} with newDpn {}", vmMacAddress,
                                newDesignatedDpn);
                        installDhcpFlowsForVms(newDesignatedDpn, vmMacAddress, tx);
                    }
                }
            }
        }
        futures.add(tx.submit());
    }
}

From source file:org.opendaylight.netvirt.vpnmanager.VpnUtil.java

static void setupSubnetMacIntoVpnInstance(DataBroker dataBroker, IMdsalApiManager mdsalManager, String vpnName,
        String subnetVpnName, String srcMacAddress, BigInteger dpnId, WriteTransaction writeTx,
        int addOrRemove) {
    long vpnId = getVpnId(dataBroker, vpnName);
    long subnetVpnId = VpnConstants.INVALID_ID;
    if (subnetVpnName != null) {
        subnetVpnId = getVpnId(dataBroker, subnetVpnName);
    }/*from w  ww.  ja  va2s.c om*/

    if (dpnId.equals(BigInteger.ZERO)) {
        /* Apply the MAC on all DPNs in a VPN */
        List<BigInteger> dpIds = getDpnsOnVpn(dataBroker, vpnName);
        if (dpIds == null || dpIds.isEmpty()) {
            return;
        }
        for (BigInteger dpId : dpIds) {
            addGwMacIntoTx(mdsalManager, srcMacAddress, writeTx, addOrRemove, vpnId, dpId, subnetVpnId);
        }
    } else {
        addGwMacIntoTx(mdsalManager, srcMacAddress, writeTx, addOrRemove, vpnId, dpnId, subnetVpnId);
    }
}

From source file:org.limewire.mojito.util.DHTSizeEstimator.java

/**
 * Computes and returns the approximate DHT size based 
 * on the given List of Contacts.//  w  w w .  j  ava 2s . c  om
 */
public synchronized BigInteger computeSize(Collection<? extends Contact> nodes) {

    // Works only with more than two Nodes
    if (nodes.size() < MIN_NODE_COUNT) {
        // There's always us!
        return BigInteger.ONE.max(BigInteger.valueOf(nodes.size()));
    }

    // Get the Iterator. We assume the Contacts are sorted by
    // their xor distance!
    Iterator<? extends Contact> contacts = nodes.iterator();

    // See Azureus DHTControlImpl.estimateDHTSize()
    // Di = nearestId xor NodeIDi
    // Dc = sum(i * Di) / sum(i * i)
    // Size = 2**160 / Dc

    BigInteger sum1 = BigInteger.ZERO;
    BigInteger sum2 = BigInteger.ZERO;

    // The algorithm works relative to the ID space.
    KUID nearestId = contacts.next().getNodeID();

    // We start 1 because the nearest Node is the 0th item!
    for (int i = 1; contacts.hasNext(); i++) {
        Contact node = contacts.next();

        BigInteger distance = nearestId.xor(node.getNodeID()).toBigInteger();
        BigInteger j = BigInteger.valueOf(i);

        sum1 = sum1.add(j.multiply(distance));
        sum2 = sum2.add(j.pow(2));
    }

    BigInteger estimatedSize = BigInteger.ZERO;
    if (!sum1.equals(BigInteger.ZERO)) {
        estimatedSize = KUID.MAXIMUM.toBigInteger().multiply(sum2).divide(sum1);
    }

    // And there is always us!
    estimatedSize = BigInteger.ONE.max(estimatedSize);

    // Get the average of the local estimations
    BigInteger localSize = BigInteger.ZERO;
    localSizeHistory.add(estimatedSize);

    // Adjust the size of the List. The Setting is SIMPP-able
    // and may change!
    int maxLocalHistorySize = ContextSettings.MAX_LOCAL_HISTORY_SIZE.getValue();
    while (localSizeHistory.size() > maxLocalHistorySize && !localSizeHistory.isEmpty()) {
        localSizeHistory.remove(0);
    }

    if (!localSizeHistory.isEmpty()) {
        BigInteger localSizeSum = BigInteger.ZERO;
        for (BigInteger size : localSizeHistory) {
            localSizeSum = localSizeSum.add(size);
        }

        localSize = localSizeSum.divide(BigInteger.valueOf(localSizeHistory.size()));
    }

    // Get the combined average
    // S = (localEstimation + sum(remoteEstimation[i]))/count
    BigInteger combinedSize = localSize;
    if (ContextSettings.COUNT_REMOTE_SIZE.getValue()) {
        // Prune all duplicates and sort the values
        Set<BigInteger> remoteSizeSet = new TreeSet<BigInteger>(remoteSizeHistory);

        if (remoteSizeSet.size() >= 3) {
            BigInteger[] remote = remoteSizeSet.toArray(new BigInteger[0]);

            // Skip the smallest and largest values
            int count = 1;
            int skip = ContextSettings.SKIP_REMOTE_ESTIMATES.getValue();
            for (int i = skip; (skip >= 0) && (i < (remote.length - skip)); i++) {
                combinedSize = combinedSize.add(remote[i]);
                count++;
            }
            combinedSize = combinedSize.divide(BigInteger.valueOf(count));

            // Make sure we didn't exceed the MAXIMUM number as
            // we made an addition with the local estimation which
            // might be already 2**160 bit!
            combinedSize = combinedSize.min(MAXIMUM);
        }
    }

    // There is always us!
    return BigInteger.ONE.max(combinedSize);
}

From source file:Ternary.java

public Ternary(BigInteger toConvert) {
    this();//  ww w.j  a v a  2s  . c o  m
    int position = 0;
    BigInteger remaining = toConvert;
    BigInteger rounded, left;
    while (!remaining.equals(BigInteger.ZERO)) {
        rounded = ((new BigDecimal(remaining)).divide(bdThree, 0, BigDecimal.ROUND_HALF_UP)).toBigInteger();
        left = remaining.subtract(rounded.multiply(biThree));
        if (left.equals(BigInteger.ONE))
            setTrit(position++, Trit.POSITIVE);
        else if (left.equals(BigInteger.ZERO))
            setTrit(position++, Trit.NEUTRAL);
        else
            setTrit(position++, Trit.NEGATIVE);
        remaining = rounded;
    }
}

From source file:org.opendaylight.vpnservice.dhcpservice.DhcpExternalTunnelManager.java

public void handleDesignatedDpnDown(BigInteger dpnId, List<BigInteger> listOfDpns) {
    logger.trace("In handleDesignatedDpnDown dpnId {}, listOfDpns {}", dpnId, listOfDpns);
    try {/* ww  w. ja  v  a2 s .c om*/
        List<Pair<IpAddress, String>> listOfTunnelIpElanNamePairs = designatedDpnsToTunnelIpElanNameCache
                .get(dpnId);
        if (!dpnId.equals(DHCPMConstants.INVALID_DPID)) {
            List<String> listOfVms = getAllVmMacs();
            for (String vmMacAddress : listOfVms) {
                unInstallDhcpEntries(dpnId, vmMacAddress);
            }
        }
        if (listOfTunnelIpElanNamePairs == null || listOfTunnelIpElanNamePairs.isEmpty()) {
            logger.trace("No tunnelIpElanName to handle for dpn {}. Returning", dpnId);
            return;
        }
        for (Pair<IpAddress, String> pair : listOfTunnelIpElanNamePairs) {
            updateCacheAndInstallNewFlows(dpnId, listOfDpns, pair);
        }
    } catch (Exception e) {
        logger.error("Error in handleDesignatedDpnDown {}", e);
    }
}

From source file:org.eclipse.om2m.core.controller.Controller.java

/**
 * Check Access Right from Acp Self privileges for ACP modifications
 * @param acp to check//from   ww w.ja v a  2s.co  m
 * @param originator to validate
 * @param operation
 */
public void checkSelfACP(AccessControlPolicyEntity acp, String originator, BigInteger operation)
        throws AccessDeniedException {
    // Check Resource accessRight existence not found
    boolean originatorFound = false;
    boolean operationAllowed = false;

    for (AccessControlRuleEntity rule : acp.getSelfPrivileges()) {
        originatorFound = false;
        operationAllowed = false;
        for (AccessControlOriginatorEntity originatorEntity : rule.getAccessControlOriginators()) {
            if (originator.matches(originatorEntity.getOriginatorID().replace("*", ".*"))) {
                originatorFound = true;
                break;
            }
        }
        if (originatorFound) {
            if (operation.equals(Operation.CREATE)) {
                if (rule.isCreate()) {
                    operationAllowed = true;
                }
            } else if (operation.equals(Operation.RETRIEVE)) {
                if (rule.isRetrieve()) {
                    operationAllowed = true;
                }
            } else if (operation.equals(Operation.UPDATE)) {
                if (rule.isUpdate()) {
                    operationAllowed = true;
                }
            } else if (operation.equals(Operation.DELETE)) {
                if (rule.isDelete()) {
                    operationAllowed = true;
                }
            }
        }
        if (originatorFound && operationAllowed) {
            break;
        }
    }
    if (!originatorFound) {
        throw new AccessDeniedException();
    }
    if (!operationAllowed) {
        throw new AccessDeniedException();
    }
}

From source file:org.opendaylight.netvirt.dhcpservice.DhcpExternalTunnelManager.java

public void handleDesignatedDpnDown(BigInteger dpnId, List<BigInteger> listOfDpns) {
    LOG.trace("In handleDesignatedDpnDown dpnId {}, listOfDpns {}", dpnId, listOfDpns);
    try {/*from ww w.j  a v a  2s .  com*/
        Set<Pair<IpAddress, String>> setOfTunnelIpElanNamePairs = designatedDpnsToTunnelIpElanNameCache
                .get(dpnId);
        WriteTransaction tx = broker.newWriteOnlyTransaction();
        if (!dpnId.equals(DhcpMConstants.INVALID_DPID)) {
            List<String> listOfVms = getAllVmMacs();
            for (String vmMacAddress : listOfVms) {
                unInstallDhcpEntries(dpnId, vmMacAddress, tx);
            }
        }
        if (setOfTunnelIpElanNamePairs == null || setOfTunnelIpElanNamePairs.isEmpty()) {
            LOG.trace("No tunnelIpElanName to handle for dpn {}. Returning", dpnId);
            return;
        }
        for (Pair<IpAddress, String> pair : setOfTunnelIpElanNamePairs) {
            updateCacheAndInstallNewFlows(dpnId, listOfDpns, pair, tx);
        }
        DhcpServiceUtils.submitTransaction(tx);
    } catch (ExecutionException e) {
        LOG.error("Error in handleDesignatedDpnDown {}", e);
    }
}

From source file:org.opendaylight.vpnservice.dhcpservice.DhcpInterfaceEventListener.java

@Override
protected void add(InstanceIdentifier<Interface> identifier, Interface add) {
    String interfaceName = add.getName();
    List<String> ofportIds = add.getLowerLayerIf();
    if (ofportIds == null || ofportIds.isEmpty()) {
        return;/*from   w w w  . ja va2 s .c  o m*/
    }
    NodeConnectorId nodeConnectorId = new NodeConnectorId(ofportIds.get(0));
    BigInteger dpId = BigInteger.valueOf(MDSALUtil.getDpnIdFromPortName(nodeConnectorId));
    logger.trace("Received add DCN for interface {}, dpid {}", interfaceName, dpId);
    org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface iface = DhcpServiceUtils
            .getInterfaceFromConfigDS(add.getName(), dataBroker);
    if (iface != null) {
        IfTunnel tunnelInterface = iface.getAugmentation(IfTunnel.class);
        if (tunnelInterface != null && !tunnelInterface.isInternal()) {
            IpAddress tunnelIp = tunnelInterface.getTunnelDestination();
            List<BigInteger> dpns = DhcpServiceUtils.getListOfDpns(dataBroker);
            if (dpns.contains(dpId)) {
                dhcpExternalTunnelManager.handleTunnelStateUp(tunnelIp, dpId);
            }
            return;
        }
    }
    if (!dpId.equals(DHCPMConstants.INVALID_DPID)) {
        installDhcpEntries(interfaceName, dpId);
        dhcpManager.updateInterfaceCache(interfaceName,
                new ImmutablePair<BigInteger, String>(dpId, add.getPhysAddress().getValue()));
    }
}

From source file:be.fedict.eid.dss.model.bean.TrustValidationServiceBean.java

public void validate(TimeStampToken timeStampToken, List<OCSPResp> ocspResponses, List<X509CRL> crls)
        throws CertificateEncodingException, TrustDomainNotFoundException, RevocationDataNotFoundException,
        ValidationFailedException, NoSuchAlgorithmException, NoSuchProviderException, CMSException,
        CertStoreException, IOException {
    LOG.debug("performing historical TSA validation...");
    String tsaTrustDomain = this.configuration.getValue(ConfigProperty.TSA_TRUST_DOMAIN, String.class);
    LOG.debug("TSA trust domain: " + tsaTrustDomain);

    Date validationDate = timeStampToken.getTimeStampInfo().getGenTime();
    LOG.debug("TSA validation date is TST time: " + validationDate);
    LOG.debug("# TSA ocsp responses: " + ocspResponses.size());
    LOG.debug("# TSA CRLs: " + crls.size());

    /*/*from   w  ww.j  av  a  2 s .c om*/
     *Building TSA chain. (Code from eID-applet)
     * 
     */

    SignerId signerId = timeStampToken.getSID();
    BigInteger signerCertSerialNumber = signerId.getSerialNumber();
    //X500Principal signerCertIssuer = signerId.getIssuer();

    X500Principal signerCertIssuer = new X500Principal(signerId.getIssuer().getEncoded());

    LOG.debug("signer cert serial number: " + signerCertSerialNumber);
    LOG.debug("signer cert issuer: " + signerCertIssuer);

    // TSP signer certificates retrieval
    CertStore certStore = timeStampToken.getCertificatesAndCRLs("Collection",
            BouncyCastleProvider.PROVIDER_NAME);
    Collection<? extends Certificate> certificates = certStore.getCertificates(null);
    X509Certificate signerCert = null;
    Map<String, X509Certificate> certificateMap = new HashMap<String, X509Certificate>();
    for (Certificate certificate : certificates) {
        X509Certificate x509Certificate = (X509Certificate) certificate;
        if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal())
                && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) {
            signerCert = x509Certificate;
        }
        String ski = Hex.encodeHexString(getSubjectKeyId(x509Certificate));
        certificateMap.put(ski, x509Certificate);
        LOG.debug("embedded certificate: " + x509Certificate.getSubjectX500Principal() + "; SKI=" + ski);
    }

    // TSP signer cert path building
    if (null == signerCert) {
        throw new RuntimeException("TSP response token has no signer certificate");
    }
    List<X509Certificate> tspCertificateChain = new LinkedList<X509Certificate>();

    X509Certificate tsaIssuer = loadCertificate(
            "be/fedict/eid/dss/CA POLITICA SELLADO DE TIEMPO - COSTA RICA.crt");
    X509Certificate rootCA = loadCertificate("be/fedict/eid/dss/CA RAIZ NACIONAL COSTA RICA.cer");
    LOG.debug("adding to certificate chain: " + signerCert.getSubjectX500Principal());
    tspCertificateChain.add(signerCert);
    LOG.debug("adding to certificate chain: " + tsaIssuer.getSubjectX500Principal());
    tspCertificateChain.add(tsaIssuer);
    LOG.debug("adding to certificate chain: " + rootCA.getSubjectX500Principal());
    tspCertificateChain.add(rootCA);

    /*
     * Perform PKI validation via eID Trust Service.
     */
    getXkms2Client().validate(tsaTrustDomain, tspCertificateChain, validationDate, ocspResponses, crls);
}

From source file:hashengineering.digitalcoin.wallet.ui.SendCoinsFragment.java

private void handleGo() {
    state = State.PREPARATION;/*  ww w  .  ja  v a  2  s . c o  m*/
    updateView();

    // create spend
    final BigInteger amount = amountCalculatorLink.getAmount();
    final SendRequest sendRequest = SendRequest.to(validatedAddress.address, amount);
    sendRequest.changeAddress = WalletUtils.pickOldestKey(wallet).toAddress(Constants.NETWORK_PARAMETERS);
    sendRequest.emptyWallet = amount.equals(wallet.getBalance(BalanceType.AVAILABLE));

    backgroundHandler.post(new Runnable() {
        @Override
        public void run() {
            final Transaction transaction = wallet.sendCoinsOffline(sendRequest); // can take long

            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (transaction != null) {
                        sentTransaction = transaction;

                        state = State.SENDING;
                        updateView();

                        sentTransaction.getConfidence().addEventListener(sentTransactionConfidenceListener);

                        if (bluetoothAdapter != null && bluetoothAdapter.isEnabled() && bluetoothMac != null
                                && bluetoothEnableView.isChecked()) {
                            backgroundHandler.post(
                                    new SendBluetoothRunnable(bluetoothAdapter, bluetoothMac, transaction) {
                                        @Override
                                        protected void onResult(final boolean ack) {
                                            bluetoothAck = ack;

                                            if (state == State.SENDING)
                                                state = State.SENT;

                                            updateView();
                                        }
                                    });
                        }

                        activity.getBlockchainService().broadcastTransaction(sentTransaction);

                        final Intent result = new Intent();
                        BitcoinIntegration.transactionHashToResult(result, sentTransaction.getHashAsString());
                        activity.setResult(Activity.RESULT_OK, result);
                    } else {
                        state = State.FAILED;
                        updateView();

                        activity.longToast(R.string.send_coins_error_msg);
                    }
                }
            });
        }
    });
}