Example usage for java.math BigInteger compareTo

List of usage examples for java.math BigInteger compareTo

Introduction

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

Prototype

public int compareTo(BigInteger val) 

Source Link

Document

Compares this BigInteger with the specified BigInteger.

Usage

From source file:org.sparkbit.jsonrpc.SparkBitJSONRPCServiceImpl.java

private synchronized String sendbitcoinusing_impl(String walletID, String txid, Long vout, String address,
        Double amount, String message) throws com.bitmechanic.barrister.RpcException {
    Wallet w = getWalletForWalletName(walletID);
    if (w == null) {
        JSONRPCError.WALLET_NOT_FOUND.raiseRpcException();
    }//from   ww w. j av  a  2s. c o  m
    if (amount <= 0.0) {
        JSONRPCError.SEND_BITCOIN_AMOUNT_TOO_LOW.raiseRpcException();
    }

    BigInteger bitcoinAmountSatoshis = Utils.toNanoCoins(amount.toString());

    // Is the BTC amount more than what is in the wallet?
    BigInteger totalSpend = bitcoinAmountSatoshis.add(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
    BigInteger availableBalance = w.getBalance(Wallet.BalanceType.AVAILABLE);
    if (totalSpend.compareTo(availableBalance) > 0) {
        JSONRPCError.SEND_BITCOIN_INSUFFICIENT_MONEY.raiseRpcException();
    }

    // Does the BTC amount respect the migration fees of any assets?
    boolean walletHasAnyAssets = CSMiscUtils.walletHasAnyAssets(w);
    if (walletHasAnyAssets) {
        boolean migrationSafe = CSMiscUtils.canSafelySpendWhileRespectingMigrationFee(this.controller, w,
                bitcoinAmountSatoshis);
        if (!migrationSafe) {
            BigInteger migrationFee = CSMiscUtils.calcMigrationFeeSatoshis(controller, w);
            JSONRPCError.SEND_INSUFFICIENT_MONEY_MIGRATION.raiseRpcException(
                    "Need to keep at least " + Utils.bitcoinValueToFriendlyString(migrationFee) + " BTC.");
        }
    }

    // Check send with txid and vout
    Sha256Hash sendWithTxidHash = null;
    boolean canSpendSendWithTxOut = false;
    if (txid != null) {
        try {
            sendWithTxidHash = new Sha256Hash(txid);
        } catch (IllegalArgumentException e) {
            // Not a valid tx hash string
            JSONRPCError.INVALID_TXID_HASH.raiseRpcException();
        }
        canSpendSendWithTxOut = isTxOutSpendable(w, sendWithTxidHash, vout.intValue());
    }

    CoinSparkPaymentRef paymentRef = null;

    String bitcoinAddress = address;
    if (address.startsWith("s")) {
        bitcoinAddress = CSMiscUtils.getBitcoinAddressFromCoinSparkAddress(address);
        if (bitcoinAddress == null) {
            JSONRPCError.COINSPARK_ADDRESS_INVALID.raiseRpcException();
        } else {
            CoinSparkAddress csa = new CoinSparkAddress();
            csa.decode(address);
            int flags = csa.getAddressFlags();
            if ((flags & CoinSparkAddress.COINSPARK_ADDRESS_FLAG_PAYMENT_REFS) > 0) {
                paymentRef = csa.getPaymentRef();
                //          log.debug(">>>> CoinSpark address has payment refs flag set: " + paymentRef.toString());
            }

            if (message != null && !CSMiscUtils.canSendTextMessageToCoinSparkAddress(csa)) {
                JSONRPCError.COINSPARK_ADDRESS_MISSING_TEXT_MESSAGE_FLAG.raiseRpcException();
            }
        }
    } else {
        // Cannot send message to a bitcoin address, must be a coinspark address
        if (message != null) {
            JSONRPCError.SEND_MESSAGE_MUST_BE_COINSPARK_ADDRESS.raiseRpcException();
        }
    }

    boolean isValid = CSMiscUtils.validateBitcoinAddress(bitcoinAddress, controller);
    if (!isValid) {
        JSONRPCError.BITCOIN_ADDRESS_INVALID.raiseRpcException();
    }

    String filename = getFullPathForWalletName(walletID);
    final WalletData wd = this.controller.getModel().getPerWalletModelDataByWalletFilename(filename);
    if (wd.isBusy()) {
        JSONRPCError.WALLEY_IS_BUSY.raiseRpcException();
    } else {
        wd.setBusy(true);
        wd.setBusyTaskKey("jsonrpc.busy.sendbitcoin");
        this.controller.fireWalletBusyChange(true);
    }

    Transaction sendTransaction = null;
    boolean sendValidated = false;
    boolean sendSuccessful = false;
    String sendTxHash = null;
    try {
        String sendAmount = amount.toString();
        // Create a SendRequest.
        Address sendAddressObject;

        sendAddressObject = new Address(controller.getModel().getNetworkParameters(), bitcoinAddress);
        Wallet.SendRequest sendRequest = Wallet.SendRequest.to(sendAddressObject,
                Utils.toNanoCoins(sendAmount));
        //                SendRequest sendRequest = SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount), 6, new BigInteger("10000"),1);
        sendRequest.ensureMinRequiredFee = true;
        sendRequest.fee = BigInteger.ZERO;
        sendRequest.feePerKb = BitcoinModel.SEND_FEE_PER_KB_DEFAULT;

        // Send with txout vout
        if (canSpendSendWithTxOut) {
            boolean addedInput = sendRequest.addInput(w,
                    new CSTransactionOutput(sendWithTxidHash, vout.intValue()));
            if (!addedInput) {
                // Failed to add input, so throw exception
                JSONRPCError.SEND_WITH_TXID_VOUT_FAILED.raiseRpcException();
            }
        }

        // Send with payment ref - if it exists and is not 0 which SparkBit treats semantically as null
        if (paymentRef != null && paymentRef.getRef() != 0) {
            sendRequest.setPaymentRef(paymentRef);
        }

        // Set up message if one exists
        boolean isEmptyMessage = false;
        if (message == null || message.isEmpty() || message.trim().length() == 0) {
            isEmptyMessage = true;
        }
        if (!isEmptyMessage) {
            CoinSparkMessagePart[] parts = { CSMiscUtils.createPlainTextCoinSparkMessagePart(message) };
            String[] serverURLs = CSMiscUtils.getMessageDeliveryServersArray(this.controller);
            sendRequest.setMessage(parts, serverURLs);
            //         log.debug(">>>> Messaging servers = " + ArrayUtils.toString(serverURLs));
            //         log.debug(">>>> parts[0] = " + parts[0]);
            //         log.debug(">>>> parts[0].fileName = " + parts[0].fileName);
            //         log.debug(">>>> parts[0].mimeType = " + parts[0].mimeType);
            //         log.debug(">>>> parts[0].content = " + new String(parts[0].content, "UTF-8"))
        }

        // Note - Request is populated with the AES key in the SendBitcoinNowAction after the user has entered it on the SendBitcoinConfirm form.
        // Complete it (which works out the fee) but do not sign it yet.
        log.info("Just about to complete the tx (and calculate the fee)...");

        w.completeTx(sendRequest, false);
        sendValidated = true;
        log.info("The fee after completing the transaction was " + sendRequest.fee);
        // Let's do it for real now.

        sendTransaction = this.controller.getMultiBitService().sendCoins(wd, sendRequest, null);
        if (sendTransaction == null) {
            // a null transaction returned indicates there was not
            // enough money (in spite of our validation)
            JSONRPCError.SEND_BITCOIN_INSUFFICIENT_MONEY.raiseRpcException();
        } else {
            sendSuccessful = true;
            sendTxHash = sendTransaction.getHashAsString();
            log.info("Sent transaction was:\n" + sendTransaction.toString());
        }

        if (sendSuccessful) {
            // There is enough money.

            /* If sending assets or BTC to a coinspark address, record transaction id --> coinspark address, into hashmap so we can use when displaying transactions */
            if (address.startsWith("s")) {
                SparkBitMapDB.INSTANCE.putSendCoinSparkAddressForTxid(sendTxHash, address);
            }
        } else {
            // There is not enough money
        }
        //      } catch (WrongNetworkException e1) {
        //      } catch (AddressFormatException e1) {
        //      } catch (KeyCrypterException e1) {
    } catch (InsufficientMoneyException e) {
        JSONRPCError.SEND_BITCOIN_INSUFFICIENT_MONEY.raiseRpcException();
    } catch (CSExceptions.CannotEncode e) {
        JSONRPCError.SEND_MESSAGE_CANNOT_ENCODE.raiseRpcException(e.getMessage());
    } catch (Exception e) {
        JSONRPCError.throwAsRpcException("Could not send bitcoin due to error", e);
    } finally {
        // Save the wallet.
        try {
            this.controller.getFileHandler().savePerWalletModelData(wd, false);
        } catch (WalletSaveException e) {
            //        log.error(e.getMessage(), e);
        }

        if (sendSuccessful) {
            // This returns immediately if rpcsendassettimeout is 0.
            JSONRPCController.INSTANCE.waitForTxSelectable(sendTransaction);
            //      JSONRPCController.INSTANCE.waitForTxBroadcast(sendTxHash);
        }

        // Declare that wallet is no longer busy with the task.
        wd.setBusyTaskKey(null);
        wd.setBusy(false);
        this.controller.fireWalletBusyChange(false);
    }

    if (sendSuccessful) {
        controller.fireRecreateAllViews(false);
    }
    return sendTxHash;
}

From source file:org.sparkbit.jsonrpc.SparkBitJSONRPCServiceImpl.java

private synchronized String sendassetusing_impl(String walletID, String txid, Long vout, String address,
        String assetRef, Double quantity, Boolean senderPays, String message, Double btcAmount)
        throws com.bitmechanic.barrister.RpcException {
    String sendTxHash = null;//w  ww . ja v  a  2s  . c o m
    boolean sendValidated = false;
    boolean sendSuccessful = false;

    Wallet w = getWalletForWalletName(walletID);
    if (w == null) {
        JSONRPCError.WALLET_NOT_FOUND.raiseRpcException();
    }

    // Check send with txid and vout
    Sha256Hash sendWithTxidHash = null;
    boolean canSpendSendWithTxOut = false;
    if (txid != null) {
        try {
            sendWithTxidHash = new Sha256Hash(txid);
        } catch (IllegalArgumentException e) {
            // Not a valid tx hash string
            JSONRPCError.INVALID_TXID_HASH.raiseRpcException();
        }
        canSpendSendWithTxOut = isTxOutSpendable(w, sendWithTxidHash, vout.intValue());
    }

    if (quantity <= 0.0) {
        JSONRPCError.SEND_ASSET_AMOUNT_TOO_LOW.raiseRpcException();
    }

    // BTC send amount, if null, use default amount of 10,000 satoshis.
    String sendAmount;
    if (btcAmount == null) {
        sendAmount = Utils.bitcoinValueToPlainString(BitcoinModel.COINSPARK_SEND_MINIMUM_AMOUNT);
    } else {
        double d = btcAmount.doubleValue();
        if (d <= 0.0) {
            JSONRPCError.SEND_BITCOIN_AMOUNT_TOO_LOW.raiseRpcException();
        }
        sendAmount = btcAmount.toString();
    }
    BigInteger bitcoinAmountSatoshis = Utils.toNanoCoins(sendAmount);

    // Is the BTC amount more than what is in the wallet?
    BigInteger totalSpend = bitcoinAmountSatoshis.add(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
    BigInteger availableBalance = w.getBalance(Wallet.BalanceType.AVAILABLE);
    if (totalSpend.compareTo(availableBalance) > 0) {
        JSONRPCError.SEND_BITCOIN_INSUFFICIENT_MONEY.raiseRpcException();
    }

    // Does the BTC amount respect the migration fees of any assets?
    boolean migrationSafe = CSMiscUtils.canSafelySpendWhileRespectingMigrationFee(this.controller, w,
            bitcoinAmountSatoshis);
    if (!migrationSafe) {
        BigInteger migrationFee = CSMiscUtils.calcMigrationFeeSatoshis(controller, w);
        JSONRPCError.SEND_INSUFFICIENT_MONEY_MIGRATION.raiseRpcException(
                "Need to keep at least " + Utils.bitcoinValueToFriendlyString(migrationFee) + " BTC.");
    }

    CoinSparkPaymentRef paymentRef = null;
    String bitcoinAddress = address;
    if (!address.startsWith("s")) {
        JSONRPCError.ADDRESS_NOT_COINSPARK_ADDRESS.raiseRpcException();
    } else {
        bitcoinAddress = CSMiscUtils.getBitcoinAddressFromCoinSparkAddress(address);
        if (bitcoinAddress == null) {
            JSONRPCError.COINSPARK_ADDRESS_INVALID.raiseRpcException();
        }

        CoinSparkAddress csa = CSMiscUtils.decodeCoinSparkAddress(address);
        if (!CSMiscUtils.canSendAssetsToCoinSparkAddress(csa)) {
            JSONRPCError.COINSPARK_ADDRESS_MISSING_ASSET_FLAG.raiseRpcException();
        }

        if (message != null && !CSMiscUtils.canSendTextMessageToCoinSparkAddress(csa)) {
            JSONRPCError.COINSPARK_ADDRESS_MISSING_TEXT_MESSAGE_FLAG.raiseRpcException();
        }

        // payment ref?
        int flags = csa.getAddressFlags();
        if ((flags & CoinSparkAddress.COINSPARK_ADDRESS_FLAG_PAYMENT_REFS) > 0) {
            paymentRef = csa.getPaymentRef();
            //      log.debug(">>>> CoinSpark address has payment refs flag set: " + paymentRef.toString());
        }
    }
    boolean isValid = CSMiscUtils.validateBitcoinAddress(bitcoinAddress, controller);
    if (!isValid) {
        JSONRPCError.BITCOIN_ADDRESS_INVALID.raiseRpcException();
    }

    String filename = getFullPathForWalletName(walletID);
    final WalletData wd = this.controller.getModel().getPerWalletModelDataByWalletFilename(filename);
    if (wd.isBusy()) {
        JSONRPCError.WALLEY_IS_BUSY.raiseRpcException();
    } else {
        wd.setBusy(true);
        wd.setBusyTaskKey("jsonrpc.busy.sendasset");
        this.controller.fireWalletBusyChange(true);
    }

    Transaction sendTransaction = null;

    try {
        // -- boilerplate ends here....

        CSAsset asset = getAssetForAssetRefString(w, assetRef);
        if (asset == null) {
            if (isAssetRefValid(assetRef)) {
                JSONRPCError.ASSETREF_NOT_FOUND.raiseRpcException();
            } else {
                JSONRPCError.ASSETREF_INVALID.raiseRpcException();
            }
        }

        if (asset.getAssetState() != CSAsset.CSAssetState.VALID) {
            if (!CSMiscUtils.canSendInvalidAsset(controller)) {
                JSONRPCError.ASSET_STATE_INVALID.raiseRpcException();
            }
        }

        // Check number of confirms
        int lastHeight = w.getLastBlockSeenHeight();
        CoinSparkAssetRef assetReference = asset.getAssetReference();
        if (assetReference != null) {
            final int blockIndex = (int) assetReference.getBlockNum();
            final int numConfirmations = lastHeight - blockIndex + 1; // 0 means no confirmation, 1 is yes for sa
            int threshold = NUMBER_OF_CONFIRMATIONS_TO_SEND_ASSET_THRESHOLD;
            // FIXME: REMOVE/COMMENT OUT BEFORE RELEASE?
            String sendAssetWithJustOneConfirmation = controller.getModel()
                    .getUserPreference("sendAssetWithJustOneConfirmation");
            if (Boolean.TRUE.toString().equals(sendAssetWithJustOneConfirmation)) {
                threshold = 1;
            }
            //System.out.println(">>>> " + CSMiscUtils.getHumanReadableAssetRef(asset) + " num confirmations " + numConfirmations + ", threshold = " + threshold);
            if (numConfirmations < threshold) {
                JSONRPCError.ASSET_NOT_CONFIRMED.raiseRpcException();
            }
        }

        String displayQtyString = new BigDecimal(quantity).toPlainString();
        BigInteger assetAmountRawUnits = CSMiscUtils.getRawUnitsFromDisplayString(asset, displayQtyString);
        int assetID = asset.getAssetID();
        BigInteger spendableAmount = w.CS.getAssetBalance(assetID).spendable;

        log.info("Want to send: " + assetAmountRawUnits + " , AssetID=" + assetID + ", total="
                + w.CS.getAssetBalance(assetID).total + ", spendable="
                + w.CS.getAssetBalance(assetID).spendable);

        //       String sendAmount = Utils.bitcoinValueToPlainString(BitcoinModel.COINSPARK_SEND_MINIMUM_AMOUNT);       
        CoinSparkGenesis genesis = asset.getGenesis();

        long desiredRawUnits = assetAmountRawUnits.longValue();
        short chargeBasisPoints = genesis.getChargeBasisPoints();
        long rawFlatChargeAmount = genesis.getChargeFlat();
        boolean chargeExists = (rawFlatChargeAmount > 0 || chargeBasisPoints > 0);
        if (chargeExists) {
            if (senderPays) {
                long x = genesis.calcGross(desiredRawUnits);
                assetAmountRawUnits = new BigInteger(String.valueOf(x));
            } else {
                // We don't have to do anything if recipient pays, just send gross amount.
                // calcNet() returns what the recipient will receive, but it's not what we send. 
            }
        }

        if (assetAmountRawUnits.compareTo(spendableAmount) > 0) {
            JSONRPCError.ASSET_INSUFFICIENT_BALANCE.raiseRpcException();
        }

        // Create a SendRequest.
        Address sendAddressObject;
        String sendAddress = bitcoinAddress;
        sendAddressObject = new Address(controller.getModel().getNetworkParameters(), sendAddress);
        //SendRequest sendRequest = SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount));

        //public static SendRequest to(Address destination,BigInteger value,int assetID, BigInteger assetValue,int split) {
        //BigInteger assetAmountRawUnits = new BigInteger(assetAmount);
        //      BigInteger bitcoinAmountSatoshis = Utils.toNanoCoins(sendAmount);

        Wallet.SendRequest sendRequest = Wallet.SendRequest.to(sendAddressObject, bitcoinAmountSatoshis,
                assetID, assetAmountRawUnits, 1);
        sendRequest.ensureMinRequiredFee = true;
        sendRequest.fee = BigInteger.ZERO;
        sendRequest.feePerKb = BitcoinModel.SEND_FEE_PER_KB_DEFAULT;

        // Note - Request is populated with the AES key in the SendBitcoinNowAction after the user has entered it on the SendBitcoinConfirm form.

        // Send with txout vout
        if (canSpendSendWithTxOut) {
            boolean addedInput = sendRequest.addInput(w,
                    new CSTransactionOutput(sendWithTxidHash, vout.intValue()));
            if (!addedInput) {
                // Failed to add input, so throw exception
                JSONRPCError.SEND_WITH_TXID_VOUT_FAILED.raiseRpcException();
            }
        }

        // Send with payment ref - if it exists and is not 0 which SparkBit treats semantically as null
        if (paymentRef != null && paymentRef.getRef() != 0) {
            sendRequest.setPaymentRef(paymentRef);
        }

        // Set up message if one exists
        boolean isEmptyMessage = false;
        if (message == null || message.trim().isEmpty()) {
            isEmptyMessage = true;
        }
        if (!isEmptyMessage) {
            CoinSparkMessagePart[] parts = { CSMiscUtils.createPlainTextCoinSparkMessagePart(message) };
            String[] serverURLs = CSMiscUtils.getMessageDeliveryServersArray(this.controller);
            sendRequest.setMessage(parts, serverURLs);
        }

        // Complete it (which works out the fee) but do not sign it yet.
        log.info("Just about to complete the tx (and calculate the fee)...");

        // there is enough money, so let's do it for real now
        w.completeTx(sendRequest, false);
        sendValidated = true;
        log.info("The fee after completing the transaction was " + sendRequest.fee);
        // Let's do it for real now.

        sendTransaction = this.controller.getMultiBitService().sendCoins(wd, sendRequest, null);
        if (sendTransaction == null) {
            // a null transaction returned indicates there was not
            // enough money (in spite of our validation)
            JSONRPCError.ASSET_INSUFFICIENT_BALANCE.raiseRpcException();
        } else {
            sendSuccessful = true;
            sendTxHash = sendTransaction.getHashAsString();
        }

        if (sendSuccessful) {
            // There is enough money.

            /* If sending assets or BTC to a coinspark address, record transaction id --> coinspark address, into hashmap so we can use when displaying transactions */
            if (address.startsWith("s")) {
                SparkBitMapDB.INSTANCE.putSendCoinSparkAddressForTxid(sendTxHash, address);
            }
        } else {
            // There is not enough money
        }

        //--- bolilerplate begins...
    } catch (InsufficientMoneyException ime) {
        JSONRPCError.ASSET_INSUFFICIENT_BALANCE.raiseRpcException();
    } catch (com.bitmechanic.barrister.RpcException e) {
        throw (e);
    } catch (CSExceptions.CannotEncode e) {
        JSONRPCError.SEND_MESSAGE_CANNOT_ENCODE.raiseRpcException(e.getMessage());
    } catch (Exception e) {
        JSONRPCError.throwAsRpcException("Could not send asset due to error: ", e);
    } finally {
        // Save the wallet.
        try {
            this.controller.getFileHandler().savePerWalletModelData(wd, false);
        } catch (WalletSaveException e) {
            //        log.error(e.getMessage(), e);
        }

        if (sendSuccessful) {
            // This returns immediately if rpcsendassettimeout is 0.
            JSONRPCController.INSTANCE.waitForTxSelectable(sendTransaction);
            //      JSONRPCController.INSTANCE.waitForTxBroadcast(sendTxHash);
        }

        // Declare that wallet is no longer busy with the task.
        wd.setBusyTaskKey(null);
        wd.setBusy(false);
        this.controller.fireWalletBusyChange(false);
    }

    if (sendSuccessful) {
        controller.fireRecreateAllViews(false);
    }
    return sendTxHash;
}

From source file:com.netscape.cms.servlet.csadmin.ConfigurationUtils.java

public static X509Certificate getX509CertFromToken(byte[] cert)
        throws IOException, CertificateException, NotInitializedException {

    X509CertImpl impl = new X509CertImpl(cert);
    String issuer_impl = impl.getIssuerDN().toString();
    BigInteger serial_impl = impl.getSerialNumber();
    CryptoManager cm = CryptoManager.getInstance();
    X509Certificate[] permcerts = cm.getPermCerts();
    for (int i = 0; i < permcerts.length; i++) {
        String issuer_p = permcerts[i].getIssuerDN().toString();
        BigInteger serial_p = permcerts[i].getSerialNumber();
        if (issuer_p.equals(issuer_impl) && serial_p.compareTo(serial_impl) == 0) {
            return permcerts[i];
        }//w  ww.j  ava  2 s  .  c  o m
    }
    return null;
}

From source file:com.flexive.core.storage.genericSQL.GenericTreeStorageSpreaded.java

protected long _reorganizeSpace(Connection con, SequencerEngine seq, FxTreeMode sourceMode, FxTreeMode destMode,
        long nodeId, boolean includeNodeId, BigInteger overrideSpacing, BigInteger overrideLeft,
        FxTreeNodeInfo insertParent, int insertPosition, BigInteger insertSpace, BigInteger insertBoundaries[],
        int depthDelta, Long destinationNode, boolean createMode, boolean createKeepIds,
        boolean disableSpaceOptimization) throws FxTreeException {
    long firstCreatedNodeId = -1;
    FxTreeNodeInfoSpreaded nodeInfo;//from w  w  w  .  j av  a2  s  .c o m
    try {
        nodeInfo = (FxTreeNodeInfoSpreaded) getTreeNodeInfo(con, sourceMode, nodeId);
    } catch (Exception e) {
        return -1;
    }

    if (!nodeInfo.isSpaceOptimizable() && !disableSpaceOptimization) {
        // The Root node and cant be optimize any more ... so all we can do is fail :-/
        // This should never really happen
        if (nodeId == ROOT_NODE) {
            return -1;
        }
        //System.out.println("### UP we go, depthDelta=" + depthDelta);
        return _reorganizeSpace(con, seq, sourceMode, destMode, nodeInfo.getParentId(), includeNodeId,
                overrideSpacing, overrideLeft, insertParent, insertPosition, insertSpace, insertBoundaries,
                depthDelta, destinationNode, createMode, createKeepIds, false);
    }

    BigInteger spacing = nodeInfo.getDefaultSpacing();
    if (overrideSpacing != null && (overrideSpacing.compareTo(spacing) < 0 || overrideLeft != null)) {
        // override spacing unless it is greater OR overrideLeft is specified (in that case we
        // have to use the spacing for valid tree ranges)  
        spacing = overrideSpacing;
    } else {
        if (spacing.compareTo(GO_UP) < 0 && !createMode && !disableSpaceOptimization) {
            return _reorganizeSpace(con, seq, sourceMode, destMode, nodeInfo.getParentId(), includeNodeId,
                    overrideSpacing, overrideLeft, insertParent, insertPosition, insertSpace, insertBoundaries,
                    depthDelta, destinationNode, createMode, createKeepIds, false);
        }
    }

    if (insertBoundaries != null && insertPosition == -1) {
        insertPosition = 0; // insertPosition cannot be negative
    }

    Statement stmt = null;
    PreparedStatement ps = null;
    ResultSet rs;
    BigInteger left = overrideLeft == null ? nodeInfo.getLeft() : overrideLeft;
    BigInteger right = null;
    String includeNode = includeNodeId ? "=" : "";
    long counter = 0;
    long newId = -1;
    try {
        final long start = System.currentTimeMillis();
        String createProps = createMode ? ",PARENT,REF,NAME,TEMPLATE" : "";
        String sql = " SELECT ID," + StorageManager.getIfFunction( // compute total child count only when the node has children
                "CHILDCOUNT = 0", "0",
                "(SELECT COUNT(*) FROM " + getTable(sourceMode) + " WHERE LFT > NODE.LFT AND RGT < NODE.RGT)") +
        // 3           4             5   6
                ", CHILDCOUNT, LFT AS LFTORD,RGT,DEPTH" + createProps
                + " FROM (SELECT ID,CHILDCOUNT,LFT,RGT,DEPTH" + createProps + " FROM " + getTable(sourceMode)
                + " WHERE " + "LFT>" + includeNode + nodeInfo.getLeft() + " AND LFT<" + includeNode
                + nodeInfo.getRight() + ") NODE " + "ORDER BY LFTORD ASC";
        stmt = con.createStatement();
        rs = stmt.executeQuery(sql);
        if (createMode) {
            //                                                                 1  2      3     4     5   6        7   8
            ps = con.prepareStatement(
                    "INSERT INTO " + getTable(destMode) + " (ID,PARENT,DEPTH,DIRTY,REF,TEMPLATE,LFT,RGT," +
                    //9           10    11
                            "CHILDCOUNT,NAME,MODIFIED_AT) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?)");
        } else {
            ps = con.prepareStatement("UPDATE " + getTable(sourceMode) + " SET LFT=?,RGT=?,DEPTH=? WHERE ID=?");
        }
        long id;
        int total_childs;
        int direct_childs;
        BigInteger nextLeft;
        int lastDepth = nodeInfo.getDepth() + (includeNodeId ? 0 : 1);
        int depth;
        BigInteger _rgt;
        BigInteger _lft;
        Long ref = null;
        String data = null;
        String name = "";

        Stack<Long> currentParent = null;
        if (createMode) {
            currentParent = new Stack<Long>();
            currentParent.push(destinationNode);
        }

        //System.out.println("Spacing:"+SPACING);
        while (rs.next()) {
            //System.out.println("------------------");
            id = rs.getLong(1);
            total_childs = rs.getInt(2);
            direct_childs = rs.getInt(3);
            _lft = getNodeBounds(rs, 4);
            _rgt = getNodeBounds(rs, 5);
            depth = rs.getInt(6);
            if (createMode) {
                // Reading these properties is slow, only do it when needed
                ref = rs.getLong(8);
                if (rs.wasNull())
                    ref = null;
                name = rs.getString(9);
                data = rs.getString(10);
                if (rs.wasNull())
                    data = null;
            }
            left = left.add(spacing).add(BigInteger.ONE);

            // Handle depth differences
            if (lastDepth - depth > 0) {
                BigInteger depthDifference = spacing.add(BigInteger.ONE);
                left = left.add(depthDifference.multiply(BigInteger.valueOf(lastDepth - depth)));
            }
            if (createMode) {
                if (lastDepth < depth) {
                    currentParent.push(newId);
                } else if (lastDepth > depth) {
                    for (int p = 0; p < (lastDepth - depth); p++)
                        currentParent.pop();
                }
            }

            right = left.add(spacing).add(BigInteger.ONE);

            // add child space if needed
            if (total_childs > 0) {
                BigInteger childSpace = spacing.multiply(BigInteger.valueOf(total_childs * 2));
                childSpace = childSpace.add(BigInteger.valueOf((total_childs * 2) - 1));
                right = right.add(childSpace);
                nextLeft = left;
            } else {
                nextLeft = right;
            }

            if (insertBoundaries != null) {
                // insert gap at requested position
                // If we're past the gap, keep adding the insert space to left/right because the added
                // space is never "injected" into the loop, i.e. without adding it the left/right boundaries of
                // nodes after the gap would be too far to the left.
                if (_lft.compareTo(insertBoundaries[0]) > 0) {
                    left = left.add(insertSpace);
                }
                if (_rgt.compareTo(insertBoundaries[0]) > 0) {
                    right = right.add(insertSpace);
                }
            }

            // sanity checks
            if (left.compareTo(right) >= 0) {
                throw new FxTreeException(LOG, "ex.tree.reorganize.failed", counter, left, right,
                        "left greater than right");
            }
            if (insertParent != null && right.compareTo((BigInteger) insertParent.getRight()) > 0) {
                throw new FxTreeException(LOG, "ex.tree.reorganize.failed", counter, left, right,
                        "wrote past parent node bounds");
            }

            // Update the node
            if (createMode) {
                newId = createKeepIds ? id : seq.getId(destMode.getSequencer());
                if (firstCreatedNodeId == -1)
                    firstCreatedNodeId = newId;

                // Create the main entry
                ps.setLong(1, newId);
                ps.setLong(2, currentParent.peek());
                ps.setLong(3, depth + depthDelta);
                ps.setBoolean(4, destMode != FxTreeMode.Live); //only flag non-live tree's dirty
                if (ref == null) {
                    ps.setNull(5, java.sql.Types.NUMERIC);
                } else {
                    ps.setLong(5, ref);
                }
                if (data == null) {
                    ps.setNull(6, java.sql.Types.VARCHAR);
                } else {
                    ps.setString(6, data);
                }
                //                    System.out.println("=> id:"+newId+" left:"+left+" right:"+right);
                setNodeBounds(ps, 7, left);
                setNodeBounds(ps, 8, right);
                ps.setInt(9, direct_childs);
                ps.setString(10, name);
                ps.setLong(11, System.currentTimeMillis());
                ps.addBatch();
            } else {
                setNodeBounds(ps, 1, left);
                setNodeBounds(ps, 2, right);
                ps.setInt(3, depth + depthDelta);
                ps.setLong(4, id);
                ps.addBatch();
                //                    ps.executeBatch();
                //                    ps.clearBatch();
            }

            // Prepare variables for the next node
            left = nextLeft;
            lastDepth = depth;
            counter++;

            // Execute batch every 10000 items to avoid out of memory
            if (counter % 10000 == 0) {
                ps.executeBatch();
                ps.clearBatch();
            }
        }
        rs.close();
        stmt.close();
        stmt = null;
        ps.executeBatch();

        if (LOG.isDebugEnabled()) {
            final long time = System.currentTimeMillis() - start;

            LOG.debug("Tree reorganization of " + counter + " items completed in " + time + " ms (spaceLen="
                    + spacing + ")");
        }
        return firstCreatedNodeId;
    } catch (FxApplicationException e) {
        throw e instanceof FxTreeException ? (FxTreeException) e : new FxTreeException(e);
    } catch (SQLException e) {
        String next = "";
        if (e.getNextException() != null)
            next = " next:" + e.getNextException().getMessage();
        if (StorageManager.isDuplicateKeyViolation(e))
            throw new FxTreeException(LOG, e, "ex.tree.reorganize.duplicateKey");
        throw new FxTreeException(LOG, e, "ex.tree.reorganize.failed", counter, left, right,
                e.getMessage() + next);
    } catch (Exception e) {
        throw new FxTreeException(e);
    } finally {
        try {
            if (stmt != null)
                stmt.close();
        } catch (Throwable t) {
            /*ignore*/}
        try {
            if (ps != null)
                ps.close();
        } catch (Throwable t) {
            /*ignore*/}
    }
}

From source file:org.sparkbit.jsonrpc.SparkBitJSONRPCServiceImpl.java

/**
 * Returns an array of unspent transaction outputs, detailing the Bitcoin and
 * asset balances tied to that UTXO./*from  ww w  . j  av a2 s  .  c om*/
 * 
 * Behavior is modeled from bitcoin: https://bitcoin.org/en/developer-reference#listunspent
 * minconf "Default is 1; use 0 to count unconfirmed transactions."
 * maxconf "Default is 9,999,999; use 0 to count unconfirmed transactions."
 * As minconf and maxconf are not optional, the default values above are ignored.
 * 
 * @param walletname
 * @param minconf
 * @param maxconf
 * @param addresses       List of CoinSpark or Bitcoin addresses
 * @return
 * @throws com.bitmechanic.barrister.RpcException 
 */
@Override
public JSONRPCUnspentTransactionOutput[] listunspent(String walletname, Long minconf, Long maxconf,
        String[] addresses) throws com.bitmechanic.barrister.RpcException {
    log.info("LIST UNSPENT TRANSACTION OUTPUTS");
    log.info("wallet name  = " + walletname);
    log.info("min number of confirmations = " + minconf);
    log.info("max number of confirmations = " + maxconf);
    log.info("addresses = " + Arrays.toString(addresses));

    Wallet w = getWalletForWalletName(walletname);
    if (w == null) {
        JSONRPCError.WALLET_NOT_FOUND.raiseRpcException();
    }

    if (minconf < 0 || maxconf < 0) {
        JSONRPCError.CONFIRMATIONS_TOO_LOW.raiseRpcException();
    }

    NetworkParameters networkParams = this.controller.getModel().getNetworkParameters();
    int mostCommonChainHeight = this.controller.getMultiBitService().getPeerGroup().getMostCommonChainHeight();

    boolean skipAddresses = addresses.length == 0;

    // Parse the list of addresses
    // If CoinSpark, convert to BTC.
    Set<String> setOfAddresses = new HashSet<String>();
    for (String address : addresses) {
        address = address.trim();
        if (address.length() == 0) {
            continue; // ignore empty string
        }
        String btcAddress = null;
        String csAddress = null;
        if (address.startsWith("s")) {
            csAddress = address;
            btcAddress = CSMiscUtils.getBitcoinAddressFromCoinSparkAddress(address);
            if (btcAddress == null) {
                // Invalid CoinSpark address, so throw exception
                JSONRPCError.COINSPARK_ADDRESS_INVALID.raiseRpcException(csAddress);
            }
        } else {
            btcAddress = address;
        }
        boolean b = CSMiscUtils.validateBitcoinAddress(btcAddress, this.controller);
        if (b) {
            setOfAddresses.add(btcAddress);
            // convenience to add coinspark address for lookup
            //      if (csAddress != null) setOfAddresses.add(csAddress);
        } else {
            if (csAddress != null) {
                // Invalid Bitcoin address from decoded CoinSpark address so throw exception.
                JSONRPCError.COINSPARK_ADDRESS_INVALID
                        .raiseRpcException(csAddress + " --> decoded btc address " + btcAddress);
            } else {
                // Invalid Bitcoin address
                JSONRPCError.BITCOIN_ADDRESS_INVALID.raiseRpcException(btcAddress);
            }
        }
    }

    // If the set of addresses is empty, list of addresses probably whitespace etc.
    // Let's treat as skipping addresses.
    if (setOfAddresses.size() == 0) {
        skipAddresses = true;
    }

    ArrayList<JSONRPCUnspentTransactionOutput> resultList = new ArrayList<>();

    Map<CSTransactionOutput, Map<Integer, CSBalance>> map = w.CS.getAllAssetTxOuts();
    //   Set<CSTransactionOutput> keys = map.keySet();
    Iterator it = map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry entry = (Map.Entry) it.next();
        CSTransactionOutput cstxout = (CSTransactionOutput) entry.getKey();

        // Only process if txout belongs to our wallet and is unspent
        Transaction tx = cstxout.getParentTransaction();
        TransactionOutput txout = tx.getOutput(cstxout.getIndex());
        if (!txout.isAvailableForSpending() || !txout.isMine(w)) {
            continue;
        }

        // If confidence is not building, don't list it as it is pending, dead or unknown.
        TransactionConfidence.ConfidenceType confidenceType = tx.getConfidence().getConfidenceType();
        if (confidenceType == TransactionConfidence.ConfidenceType.UNKNOWN
                || confidenceType == TransactionConfidence.ConfidenceType.DEAD) {
            continue;
        }

        int numConfirmations = 0; // If confidence is PENDING, this will be zero
        if (confidenceType == TransactionConfidence.ConfidenceType.BUILDING) {
            // getAppearedAtChainHeight() will throw illegalstate exception if confidence is not building
            int txAppearedAtChainHeight = tx.getConfidence().getAppearedAtChainHeight();
            numConfirmations = mostCommonChainHeight - txAppearedAtChainHeight + 1; // if same, then it means 1 confirmation
        }

        // Only process if number of confirmations is within range.
        if (minconf == 0 || maxconf == 0) {
            // Unconfirmed transactions are okay, so do nothing.
        } else if (numConfirmations < minconf || numConfirmations > maxconf) {
            // Skip if outside of range
            continue;
        }

        // Only process if the BTC address for this tx is in the list of addresses
        String btcAddress = txout.getScriptPubKey().getToAddress(networkParams).toString();
        if (!skipAddresses && !setOfAddresses.contains(btcAddress)) {
            continue;
        }

        // Get the bitcoin and asset balances on this utxo
        Map<Integer, CSBalance> balances = (Map<Integer, CSBalance>) entry.getValue();

        boolean hasAssets = false;
        ArrayList<JSONRPCBalance> balancesList = new ArrayList<>();

        for (Map.Entry<Integer, CSBalance> balanceEntry : balances.entrySet()) {
            Integer assetID = balanceEntry.getKey();
            CSBalance balance = balanceEntry.getValue();
            BigInteger qty = balance.getQty();

            boolean isSelectable = DefaultCoinSelector.isSelectable(tx);

            //      log.info(">>>> assetID = " + assetID + " , qty = " + qty);

            // Handle Bitcoin specially
            if (assetID == 0) {
                JSONRPCBalance bal = null;
                //          if (isSelectable) {
                //         bal = createBitcoinBalance(w, qty, null);
                //          } else {
                bal = createBitcoinBalance(w, qty, null);
                //          }
                balancesList.add(bal);
                continue;
            }

            // Other assets
            hasAssets = true;

            if (qty.compareTo(BigInteger.ZERO) > 0) {
                JSONRPCBalance bal = null;
                bal = createAssetBalance(w, assetID, qty, null);
                //          if (isSelectable) {
                //         bal = createAssetBalance(w, assetID, qty, qty);
                //          } else {
                //         bal = createAssetBalance(w, assetID, qty, BigInteger.ZERO);
                //          }
                balancesList.add(bal);
            }
        }
        JSONRPCBalance[] balancesArray = balancesList.toArray(new JSONRPCBalance[0]);

        String scriptPubKeyHexString = Utils.bytesToHexString(txout.getScriptBytes());

        // Build the object to return
        JSONRPCUnspentTransactionOutput utxo = new JSONRPCUnspentTransactionOutput();
        utxo.setTxid(tx.getHashAsString());
        utxo.setVout((long) cstxout.getIndex());
        utxo.setScriptPubKey(scriptPubKeyHexString);
        utxo.setAmounts(balancesArray); //new JSONRPCBalance[0]);
        utxo.setConfirmations((long) numConfirmations);

        utxo.setBitcoin_address(btcAddress);

        if (hasAssets) {
            String sparkAddress = null;
            // First let's see if we have stored the recipient in our map and use it instead
            // of generating a new one from bitcoin address
            try {
                String spk = SparkBitMapDB.INSTANCE.getSendCoinSparkAddressForTxid(tx.getHashAsString());
                String btc = CSMiscUtils.getBitcoinAddressFromCoinSparkAddress(spk);
                if (btc.equals(btcAddress)) {
                    sparkAddress = spk;
                }
            } catch (Exception e) {
            }
            if (sparkAddress == null) {
                sparkAddress = CSMiscUtils.convertBitcoinAddressToCoinSparkAddress(btcAddress);
            }
            utxo.setCoinspark_address(sparkAddress);
        }

        utxo.setAmounts(balancesArray);

        resultList.add(utxo);
    }

    JSONRPCUnspentTransactionOutput[] resultArray = resultList.toArray(new JSONRPCUnspentTransactionOutput[0]);
    return resultArray;
}

From source file:de.tudarmstadt.ukp.dkpro.lexsemresource.graph.EntityGraphJGraphT.java

/**
 * Computes the shortest path from node to all other nodes. Paths to nodes that have already
 * been the source of the shortest path computation are omitted (the path was already added to
 * the path sum). Updates the sum of shortest path lengths and the diameter of the graph. As the
 * JGraphT BreadthFirstIterator does not provide information about the distance to the start
 * node in each step, we will use our own BFS implementation.
 *
 * @param pStartNode/*from  w w  w  .j  av a2 s .  c om*/
 *            The start node of the search.
 * @param pShortestPathLengthSum
 *            The sum of the shortest path lengths.
 * @param pMaxPathLength
 *            The maximum path length found so far.
 * @param pWasSource
 *            A set of nodes which have been the start node of the computation process. For such
 *            nodes all path lengths have been already computed.
 * @return An array of double values. The first value is the shortestPathLengthSum The second
 *         value is the maxPathLength They are returned as an array for performance reasons. I
 *         do not want to create an object, as this function is called *very* often.
 */
private BigInteger[] computeShortestPathLengths(Entity pStartNode, BigInteger pBigShortestPathLengthSum,
        BigInteger pBigMaxPathLength, Set<Entity> pWasSource) {

    int pStartNodeMaxPathLength = 0;

    // a set of nodes that have already been expanded -> algorithm should expand nodes
    // monotonically and not go back
    Set<Entity> alreadyExpanded = new HashSet<Entity>();

    // a queue holding the newly discovered nodes and their distance to the start node
    List<Entity[]> queue = new ArrayList<Entity[]>();

    // initialize queue with start node
    Entity[] innerList = new Entity[2];
    innerList[0] = pStartNode; // the node
    innerList[1] = new Entity("0"); // the distance to the start node
    queue.add(innerList);

    // while the queue is not empty
    while (!queue.isEmpty()) {
        // remove first element from queue
        Entity[] queueElement = queue.get(0);
        Entity currentNode = queueElement[0];
        Entity distance = queueElement[1];
        queue.remove(0);

        // if the node was not already expanded
        if (!alreadyExpanded.contains(currentNode)) {

            // the node gets expanded now
            alreadyExpanded.add(currentNode);

            // if the node was a source node in a previous run, we already have added this path
            if (!pWasSource.contains(currentNode)) {
                // add the distance of this node to shortestPathLengthSum
                // check if maxPathLength must be updated
                int tmpDistance = new Integer(distance.getFirstLexeme());
                pBigShortestPathLengthSum = pBigShortestPathLengthSum.add(BigInteger.valueOf(tmpDistance));

                if (pBigMaxPathLength.compareTo(BigInteger.valueOf(tmpDistance)) == -1) {
                    pBigMaxPathLength = BigInteger.valueOf(tmpDistance);

                    // logger.info("*TEST TRUE:* pBigShortestPathLengthSum = " +
                    // pBigShortestPathLengthSum);
                }
                //
            }
            // even if the node was a source node in a previous run there can be a path to other
            // nodes over this node, so go on

            // get the neighbors of the queue element
            Set<Entity> neighbors = getNeighbors(currentNode);

            // iterate over all neighbors
            for (Entity neighbor : neighbors) {
                // if the node was not already expanded
                if (!alreadyExpanded.contains(neighbor)) {
                    // add the node to the queue, increase node distance by one
                    Entity[] tmpList = new Entity[2];
                    tmpList[0] = neighbor;
                    Integer tmpDistance = new Integer(distance.getFirstLexeme()) + 1;
                    tmpList[1] = new Entity(tmpDistance.toString());
                    queue.add(tmpList);
                }
            }
        }
        pStartNodeMaxPathLength = new Integer(distance.getFirstLexeme());
    }
    eccentricityMap.put(pStartNode, pStartNodeMaxPathLength);

    BigInteger returnArray[] = { pBigShortestPathLengthSum, pBigMaxPathLength };
    return returnArray;
}

From source file:org.alfresco.opencmis.CMISConnector.java

/**
 * Sets a property value.//from w  w w.  j av a 2s  . com
 */
public void setProperty(NodeRef nodeRef, TypeDefinitionWrapper type, String propertyId, Serializable value) {
    if (propertyId == null) {
        throw new CmisInvalidArgumentException("Cannot process not null property!");
    }

    PropertyDefinitionWrapper propDef = type.getPropertyById(propertyId);
    if (propDef == null) {
        throw new CmisInvalidArgumentException("Property " + propertyId + " is unknown!");
    }

    Updatability updatability = propDef.getPropertyDefinition().getUpdatability();
    if ((updatability == Updatability.READONLY) || (updatability == Updatability.WHENCHECKEDOUT
            && !checkOutCheckInService.isWorkingCopy(nodeRef))) {
        throw new CmisInvalidArgumentException("Property " + propertyId + " is read-only!");
    }

    if (propDef.getPropertyId().equals(PropertyIds.SECONDARY_OBJECT_TYPE_IDS)) {
        throw new IllegalArgumentException(
                "Cannot process " + PropertyIds.SECONDARY_OBJECT_TYPE_IDS + " in setProperty");
    } else {
        QName propertyQName = propDef.getPropertyAccessor().getMappedProperty();
        if (propertyQName == null) {
            throw new CmisConstraintException("Unable to set property " + propertyId + "!");
        }

        if (propertyId.equals(PropertyIds.NAME)) {
            if (!(value instanceof String)) {
                throw new CmisInvalidArgumentException("Object name must be a string!");
            }

            try {
                fileFolderService.rename(nodeRef, value.toString());
            } catch (FileExistsException e) {
                throw new CmisContentAlreadyExistsException("An object with this name already exists!", e);
            } catch (FileNotFoundException e) {
                throw new CmisInvalidArgumentException("Object with id " + nodeRef.getId() + " not found!");
            }
        } else {
            // overflow check
            if (propDef.getPropertyDefinition().getPropertyType() == PropertyType.INTEGER
                    && value instanceof BigInteger) {
                org.alfresco.service.cmr.dictionary.PropertyDefinition def = dictionaryService
                        .getProperty(propertyQName);
                QName dataDef = def.getDataType().getName();
                BigInteger bigValue = (BigInteger) value;

                if ((bigValue.compareTo(maxInt) > 0 || bigValue.compareTo(minInt) < 0)
                        && dataDef.equals(DataTypeDefinition.INT)) {
                    throw new CmisConstraintException(
                            "Value is out of range for property " + propertyQName.getLocalName());
                }

                if ((bigValue.compareTo(maxLong) > 0 || bigValue.compareTo(minLong) < 0)
                        && dataDef.equals(DataTypeDefinition.LONG)) {
                    throw new CmisConstraintException(
                            "Value is out of range for property " + propertyQName.getLocalName());
                }
            }

            nodeService.setProperty(nodeRef, propertyQName, value);
        }
    }
}

From source file:com.netscape.ca.CertificateAuthority.java

private synchronized void readAuthority(LDAPEntry entry) {
    String nsUniqueId = entry.getAttribute("nsUniqueId").getStringValueArray()[0];
    if (deletedNsUniqueIds.contains(nsUniqueId)) {
        logger.warn("readAuthority: ignoring entry with nsUniqueId '" + nsUniqueId + "' due to deletion");
        return;/*from  www . j  ava  2s.  c om*/
    }

    LDAPAttribute aidAttr = entry.getAttribute("authorityID");
    LDAPAttribute nickAttr = entry.getAttribute("authorityKeyNickname");
    LDAPAttribute keyHostsAttr = entry.getAttribute("authorityKeyHost");
    LDAPAttribute dnAttr = entry.getAttribute("authorityDN");
    LDAPAttribute parentAIDAttr = entry.getAttribute("authorityParentID");
    LDAPAttribute parentDNAttr = entry.getAttribute("authorityParentDN");
    LDAPAttribute serialAttr = entry.getAttribute("authoritySerial");

    if (aidAttr == null || nickAttr == null || dnAttr == null) {
        logger.warn("Malformed authority object; required attribute(s) missing: " + entry.getDN());
        return;
    }

    AuthorityID aid = new AuthorityID((String) aidAttr.getStringValues().nextElement());

    X500Name dn = null;
    try {
        dn = new X500Name((String) dnAttr.getStringValues().nextElement());
    } catch (IOException e) {
        logger.warn("Malformed authority object; invalid authorityDN: " + entry.getDN() + ": " + e.getMessage(),
                e);
    }

    String desc = null;
    LDAPAttribute descAttr = entry.getAttribute("description");
    if (descAttr != null)
        desc = (String) descAttr.getStringValues().nextElement();

    /* Determine if it is the host authority's entry, by
     * comparing DNs.  DNs must be serialised in case different
     * encodings are used for AVA values, e.g. PrintableString
     * from LDAP vs UTF8String in certificate.
     */
    if (dn.toString().equals(mName.toString())) {
        logger.debug("Found host authority");
        foundHostAuthority = true;
        this.authorityID = aid;
        this.authorityDescription = desc;
        caMap.put(aid, this);
        return;
    }

    BigInteger newEntryUSN = null;
    LDAPAttribute entryUSNAttr = entry.getAttribute("entryUSN");
    if (entryUSNAttr == null) {
        logger.debug("readAuthority: no entryUSN");
        if (!entryUSNPluginEnabled()) {
            logger.warn("readAuthority: dirsrv USN plugin is not enabled; skipping entry");
            log(ILogger.LL_FAILURE,
                    "Lightweight authority entry has no" + " entryUSN attribute and USN plugin not enabled;"
                            + " skipping.  Enable dirsrv USN plugin.");
            return;
        } else {
            logger.debug("readAuthority: dirsrv USN plugin is enabled; continuing");
            // entryUSN plugin is enabled, but no entryUSN attribute. We
            // can proceed because future modifications will result in the
            // entryUSN attribute being added.
        }
    } else {
        newEntryUSN = new BigInteger(entryUSNAttr.getStringValueArray()[0]);
        logger.debug("readAuthority: new entryUSN = " + newEntryUSN);
    }

    BigInteger knownEntryUSN = entryUSNs.get(aid);
    if (newEntryUSN != null && knownEntryUSN != null) {
        logger.debug("readAuthority: known entryUSN = " + knownEntryUSN);
        if (newEntryUSN.compareTo(knownEntryUSN) <= 0) {
            logger.debug("readAuthority: data is current");
            return;
        }
    }

    @SuppressWarnings("unused")
    X500Name parentDN = null;
    if (parentDNAttr != null) {
        try {
            parentDN = new X500Name((String) parentDNAttr.getStringValues().nextElement());
        } catch (IOException e) {
            logger.warn("Malformed authority object; invalid authorityParentDN: " + entry.getDN() + ": "
                    + e.getMessage(), e);
            return;
        }
    }

    String keyNick = (String) nickAttr.getStringValues().nextElement();

    Collection<String> keyHosts;
    if (keyHostsAttr == null) {
        keyHosts = Collections.emptyList();
    } else {
        @SuppressWarnings("unchecked")
        Enumeration<String> keyHostsEnum = keyHostsAttr.getStringValues();
        keyHosts = Collections.list(keyHostsEnum);
    }

    AuthorityID parentAID = null;
    if (parentAIDAttr != null)
        parentAID = new AuthorityID((String) parentAIDAttr.getStringValues().nextElement());

    BigInteger serial = null;
    if (serialAttr != null)
        serial = new BigInteger(serialAttr.getStringValueArray()[0]);

    boolean enabled = true;
    LDAPAttribute enabledAttr = entry.getAttribute("authorityEnabled");
    if (enabledAttr != null) {
        String enabledString = (String) enabledAttr.getStringValues().nextElement();
        enabled = enabledString.equalsIgnoreCase("TRUE");
    }

    try {
        CertificateAuthority ca = new CertificateAuthority(hostCA, dn, aid, parentAID, serial, keyNick,
                keyHosts, desc, enabled);
        caMap.put(aid, ca);
        entryUSNs.put(aid, newEntryUSN);
        nsUniqueIds.put(aid, nsUniqueId);
    } catch (EBaseException e) {
        logger.warn("Error initialising lightweight CA: " + e.getMessage(), e);
    }
}

From source file:org.alfresco.opencmis.CMISConnector.java

private void setAspectProperties(NodeRef nodeRef, boolean isNameChanging,
        CmisExtensionElement aspectExtension) {
    if (aspectExtension.getChildren() == null) {
        return;//from  ww  w.j  av  a 2s . c  o  m
    }

    List<String> aspectsToAdd = new ArrayList<String>();
    List<String> aspectsToRemove = new ArrayList<String>();
    Map<QName, List<Serializable>> aspectProperties = new HashMap<QName, List<Serializable>>();

    for (CmisExtensionElement extension : aspectExtension.getChildren()) {
        if (!ALFRESCO_EXTENSION_NAMESPACE.equals(extension.getNamespace())) {
            continue;
        }

        if (ASPECTS_TO_ADD.equals(extension.getName()) && (extension.getValue() != null)) {
            aspectsToAdd.add(extension.getValue());
        } else if (ASPECTS_TO_REMOVE.equals(extension.getName()) && (extension.getValue() != null)) {
            aspectsToRemove.add(extension.getValue());
        } else if (PROPERTIES.equals(extension.getName()) && (extension.getChildren() != null)) {
            for (CmisExtensionElement property : extension.getChildren()) {
                if (!property.getName().startsWith("property")) {
                    continue;
                }

                String propertyId = (property.getAttributes() == null ? null
                        : property.getAttributes().get("propertyDefinitionId"));
                if ((propertyId == null) || (property.getChildren() == null)) {
                    continue;
                }

                PropertyType propertyType = PropertyType.STRING;
                DatatypeFactory df = null;
                if (property.getName().equals("propertyBoolean")) {
                    propertyType = PropertyType.BOOLEAN;
                } else if (property.getName().equals("propertyInteger")) {
                    propertyType = PropertyType.INTEGER;
                } else if (property.getName().equals("propertyDateTime")) {
                    propertyType = PropertyType.DATETIME;
                    try {
                        df = DatatypeFactory.newInstance();
                    } catch (DatatypeConfigurationException e) {
                        throw new CmisRuntimeException("Aspect conversation exception: " + e.getMessage(), e);
                    }
                } else if (property.getName().equals("propertyDecimal")) {
                    propertyType = PropertyType.DECIMAL;
                }

                ArrayList<Serializable> values = new ArrayList<Serializable>();
                if (property.getChildren() != null) {
                    //                        try
                    //                        {
                    for (CmisExtensionElement valueElement : property.getChildren()) {
                        if ("value".equals(valueElement.getName())) {
                            switch (propertyType) {
                            case BOOLEAN:
                                try {
                                    values.add(Boolean.parseBoolean(valueElement.getValue()));
                                } catch (Exception e) {
                                    throw new CmisInvalidArgumentException(
                                            "Invalid property aspect value: " + propertyId, e);
                                }
                                break;
                            case DATETIME:
                                try {
                                    values.add(df.newXMLGregorianCalendar(valueElement.getValue())
                                            .toGregorianCalendar());
                                } catch (Exception e) {
                                    throw new CmisInvalidArgumentException(
                                            "Invalid property aspect value: " + propertyId, e);
                                }
                                break;
                            case INTEGER:
                                BigInteger value = null;
                                try {
                                    value = new BigInteger(valueElement.getValue());
                                } catch (Exception e) {
                                    throw new CmisInvalidArgumentException(
                                            "Invalid property aspect value: " + propertyId, e);
                                }

                                // overflow check
                                PropertyDefinitionWrapper propDef = getOpenCMISDictionaryService()
                                        .findProperty(propertyId);
                                if (propDef == null) {
                                    throw new CmisInvalidArgumentException(
                                            "Property " + propertyId + " is unknown!");
                                }

                                QName propertyQName = propDef.getPropertyAccessor().getMappedProperty();
                                if (propertyQName == null) {
                                    throw new CmisConstraintException(
                                            "Unable to set property " + propertyId + "!");
                                }

                                org.alfresco.service.cmr.dictionary.PropertyDefinition def = dictionaryService
                                        .getProperty(propertyQName);
                                QName dataDef = def.getDataType().getName();

                                if (dataDef.equals(DataTypeDefinition.INT)
                                        && (value.compareTo(maxInt) > 0 || value.compareTo(minInt) < 0)) {
                                    throw new CmisConstraintException(
                                            "Value is out of range for property " + propertyId);
                                }

                                if (dataDef.equals(DataTypeDefinition.LONG)
                                        && (value.compareTo(maxLong) > 0 || value.compareTo(minLong) < 0)) {
                                    throw new CmisConstraintException(
                                            "Value is out of range for property " + propertyId);
                                }

                                values.add(value);
                                break;
                            case DECIMAL:
                                try {
                                    values.add(new BigDecimal(valueElement.getValue()));
                                } catch (Exception e) {
                                    throw new CmisInvalidArgumentException(
                                            "Invalid property aspect value: " + propertyId, e);
                                }
                                break;
                            default:
                                values.add(valueElement.getValue());
                            }
                        }
                    }
                }

                aspectProperties.put(QName.createQName(propertyId, namespaceService), values);
            }
        }
    }

    // remove and add aspects
    String aspectType = null;
    try {
        for (String aspect : aspectsToRemove) {
            aspectType = aspect;

            TypeDefinitionWrapper type = getType(aspect);
            if (type == null) {
                throw new CmisInvalidArgumentException("Invalid aspect: " + aspectType);
            }

            QName typeName = type.getAlfrescoName();
            // if aspect is hidden aspect, remove only if hidden node is not client controlled
            if (typeName.equals(ContentModel.ASPECT_HIDDEN)) {
                if (hiddenAspect.isClientControlled(nodeRef)
                        || aspectProperties.containsKey(ContentModel.PROP_CLIENT_CONTROLLED)) {
                    // manipulate hidden aspect only if client controlled
                    nodeService.removeAspect(nodeRef, typeName);
                }

                //                   if(!isNameChanging && !hiddenAspect.isClientControlled(nodeRef) && !aspectProperties.containsKey(ContentModel.PROP_CLIENT_CONTROLLED))
                //                   {
                //                       nodeService.removeAspect(nodeRef, typeName);   
                //                   }
            } else {
                nodeService.removeAspect(nodeRef, typeName);
            }
        }

        for (String aspect : aspectsToAdd) {
            aspectType = aspect;

            TypeDefinitionWrapper type = getType(aspect);
            if (type == null) {
                throw new CmisInvalidArgumentException("Invalid aspect: " + aspectType);
            }

            QName typeName = type.getAlfrescoName();
            // if aspect is hidden aspect, remove only if hidden node is not client controlled
            if (typeName.equals(ContentModel.ASPECT_HIDDEN)) {
                if (hiddenAspect.isClientControlled(nodeRef)
                        || aspectProperties.containsKey(ContentModel.PROP_CLIENT_CONTROLLED)) {
                    // manipulate hidden aspect only if client controlled
                    nodeService.addAspect(nodeRef, type.getAlfrescoName(),
                            Collections.<QName, Serializable>emptyMap());
                }

                //                   if(!isNameChanging && !hiddenAspect.isClientControlled(nodeRef) && !aspectProperties.containsKey(ContentModel.PROP_CLIENT_CONTROLLED))
                //                   {
                //                      nodeService.addAspect(nodeRef, type.getAlfrescoName(),
                //                               Collections.<QName, Serializable> emptyMap());   
                //                   }
            } else {
                nodeService.addAspect(nodeRef, type.getAlfrescoName(),
                        Collections.<QName, Serializable>emptyMap());
            }
        }
    } catch (InvalidAspectException e) {
        throw new CmisInvalidArgumentException("Invalid aspect: " + aspectType);
    } catch (InvalidNodeRefException e) {
        throw new CmisInvalidArgumentException("Invalid node: " + nodeRef);
    }

    // set property
    for (Map.Entry<QName, List<Serializable>> property : aspectProperties.entrySet()) {
        QName propertyQName = property.getKey();

        if (property.getValue().isEmpty()) {
            if (HiddenAspect.HIDDEN_PROPERTIES.contains(property.getKey())) {
                if (hiddenAspect.isClientControlled(nodeRef)
                        || aspectProperties.containsKey(ContentModel.PROP_CLIENT_CONTROLLED)) {
                    // manipulate hidden aspect property only if client controlled
                    nodeService.removeProperty(nodeRef, propertyQName);
                }
            } else {
                nodeService.removeProperty(nodeRef, property.getKey());
            }
        } else {
            if (HiddenAspect.HIDDEN_PROPERTIES.contains(property.getKey())) {
                if (hiddenAspect.isClientControlled(nodeRef)
                        || aspectProperties.containsKey(ContentModel.PROP_CLIENT_CONTROLLED)) {
                    // manipulate hidden aspect property only if client controlled
                    nodeService.setProperty(nodeRef, property.getKey(),
                            property.getValue().size() == 1 ? property.getValue().get(0)
                                    : (Serializable) property.getValue());
                }
            } else {
                Serializable value = (Serializable) property.getValue();
                nodeService.setProperty(nodeRef, property.getKey(),
                        property.getValue().size() == 1 ? property.getValue().get(0) : value);
            }
        }
    }
}

From source file:com.google.bitcoin.core.Wallet.java

/**
 * <p>Returns a future that will complete when the balance of the given type has becom equal or larger to the given
 * value. If the wallet already has a large enough balance the future is returned in a pre-completed state. Note
 * that this method is not blocking, if you want to actually wait immediately, you have to call .get() on
 * the result.</p>//from  w w w.ja v  a2  s  .c om
 *
 * <p>Also note that by the time the future completes, the wallet may have changed yet again if something else
 * is going on in parallel, so you should treat the returned balance as advisory and be prepared for sending
 * money to fail! Finally please be aware that any listeners on the future will run either on the calling thread
 * if it completes immediately, or eventually on a background thread if the balance is not yet at the right
 * level. If you do something that means you know the balance should be sufficient to trigger the future,
 * you can use {@link com.google.bitcoin.utils.Threading#waitForUserCode()} to block until the future had a
 * chance to be updated.</p>
 */
public ListenableFuture<BigInteger> getBalanceFuture(final BigInteger value, final BalanceType type) {
    lock.lock();
    try {
        final SettableFuture<BigInteger> future = SettableFuture.create();
        final BigInteger current = getBalance(type);
        if (current.compareTo(value) >= 0) {
            // Already have enough.
            future.set(current);
        } else {
            // Will be checked later in checkBalanceFutures. We don't just add an event listener for ourselves
            // here so that running getBalanceFuture().get() in the user code thread works - generally we must
            // avoid giving the user back futures that require the user code thread to be free.
            BalanceFutureRequest req = new BalanceFutureRequest();
            req.future = future;
            req.value = value;
            req.type = type;
            balanceFutureRequests.add(req);
        }
        return future;
    } finally {
        lock.unlock();
    }
}