Example usage for java.math BigInteger subtract

List of usage examples for java.math BigInteger subtract

Introduction

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

Prototype

public BigInteger subtract(BigInteger val) 

Source Link

Document

Returns a BigInteger whose value is (this - val) .

Usage

From source file:org.apache.flink.graph.library.clustering.directed.TriadicCensus.java

@Override
public Result getResult() {
    BigInteger one = BigInteger.ONE;
    BigInteger two = BigInteger.valueOf(2);
    BigInteger three = BigInteger.valueOf(3);
    BigInteger six = BigInteger.valueOf(6);

    BigInteger vertexCount = BigInteger.valueOf((Long) vertexDegreesHelper.getAccumulator(env, "vc"));
    BigInteger unidirectionalEdgeCount = BigInteger
            .valueOf((Long) vertexDegreesHelper.getAccumulator(env, "uec") / 2);
    BigInteger bidirectionalEdgeCount = BigInteger
            .valueOf((Long) vertexDegreesHelper.getAccumulator(env, "bec") / 2);
    BigInteger triplet021dCount = BigInteger.valueOf((Long) vertexDegreesHelper.getAccumulator(env, "021d"));
    BigInteger triplet021uCount = BigInteger.valueOf((Long) vertexDegreesHelper.getAccumulator(env, "021u"));
    BigInteger triplet021cCount = BigInteger.valueOf((Long) vertexDegreesHelper.getAccumulator(env, "021c"));
    BigInteger triplet111dCount = BigInteger.valueOf((Long) vertexDegreesHelper.getAccumulator(env, "111d"));
    BigInteger triplet111uCount = BigInteger.valueOf((Long) vertexDegreesHelper.getAccumulator(env, "111u"));
    BigInteger triplet201Count = BigInteger.valueOf((Long) vertexDegreesHelper.getAccumulator(env, "201"));

    // triads with three connecting edges = closed triplet = triangle
    BigInteger triangle030tCount = BigInteger.valueOf((Long) triangleListingHelper.getAccumulator(env, "030t"));
    BigInteger triangle030cCount = BigInteger.valueOf((Long) triangleListingHelper.getAccumulator(env, "030c"));
    BigInteger triangle120dCount = BigInteger.valueOf((Long) triangleListingHelper.getAccumulator(env, "120d"));
    BigInteger triangle120uCount = BigInteger.valueOf((Long) triangleListingHelper.getAccumulator(env, "120u"));
    BigInteger triangle120cCount = BigInteger.valueOf((Long) triangleListingHelper.getAccumulator(env, "120c"));
    BigInteger triangle210Count = BigInteger.valueOf((Long) triangleListingHelper.getAccumulator(env, "210"));
    BigInteger triangle300Count = BigInteger.valueOf((Long) triangleListingHelper.getAccumulator(env, "300"));

    // triads with two connecting edges = open triplet;
    // each triangle deducts the count of three triplets
    triplet201Count = triplet201Count.subtract(triangle300Count.multiply(three));

    triplet201Count = triplet201Count.subtract(triangle210Count);
    triplet111dCount = triplet111dCount.subtract(triangle210Count);
    triplet111uCount = triplet111uCount.subtract(triangle210Count);

    triplet111dCount = triplet111dCount.subtract(triangle120cCount);
    triplet111uCount = triplet111uCount.subtract(triangle120cCount);
    triplet021cCount = triplet021cCount.subtract(triangle120cCount);

    triplet111uCount = triplet111uCount.subtract(triangle120uCount.multiply(two));
    triplet021uCount = triplet021uCount.subtract(triangle120uCount);

    triplet111dCount = triplet111dCount.subtract(triangle120dCount.multiply(two));
    triplet021dCount = triplet021dCount.subtract(triangle120dCount);

    triplet021cCount = triplet021cCount.subtract(triangle030cCount.multiply(three));

    triplet021cCount = triplet021cCount.subtract(triangle030tCount);
    triplet021uCount = triplet021uCount.subtract(triangle030tCount);
    triplet021dCount = triplet021dCount.subtract(triangle030tCount);

    // triads with one connecting edge; each edge pairs with `vertex count - 2` vertices;
    // each triangle deducts from three and each open triplet from two edges
    BigInteger edge102 = bidirectionalEdgeCount.multiply(vertexCount.subtract(two)).subtract(triplet111dCount)
            .subtract(triplet111uCount).subtract(triplet201Count.multiply(two)).subtract(triangle120dCount)
            .subtract(triangle120uCount).subtract(triangle120cCount).subtract(triangle210Count.multiply(two))
            .subtract(triangle300Count.multiply(three));

    BigInteger edge012 = unidirectionalEdgeCount.multiply(vertexCount.subtract(two))
            .subtract(triplet021dCount.multiply(two)).subtract(triplet021uCount.multiply(two))
            .subtract(triplet021cCount.multiply(two)).subtract(triplet111dCount).subtract(triplet111uCount)
            .subtract(triangle030tCount.multiply(three)).subtract(triangle030cCount.multiply(three))
            .subtract(triangle120dCount.multiply(two)).subtract(triangle120uCount.multiply(two))
            .subtract(triangle120cCount.multiply(two)).subtract(triangle210Count);

    // triads with zero connecting edges;
    // (vertex count choose 3) minus earlier counts
    BigInteger triad003 = vertexCount.multiply(vertexCount.subtract(one)).multiply(vertexCount.subtract(two))
            .divide(six).subtract(edge012).subtract(edge102).subtract(triplet021dCount)
            .subtract(triplet021uCount).subtract(triplet021cCount).subtract(triplet111dCount)
            .subtract(triplet111uCount).subtract(triangle030tCount).subtract(triangle030cCount)
            .subtract(triplet201Count).subtract(triangle120dCount).subtract(triangle120uCount)
            .subtract(triangle120cCount).subtract(triangle210Count).subtract(triangle300Count);

    return new Result(triad003, edge012, edge102, triplet021dCount, triplet021uCount, triplet021cCount,
            triplet111dCount, triplet111uCount, triangle030tCount, triangle030cCount, triplet201Count,
            triangle120dCount, triangle120uCount, triangle120cCount, triangle210Count, triangle300Count);
}

From source file:org.jmangos.realm.network.packet.auth.client.CMD_AUTH_LOGON_CHALLENGE.java

@Override
protected void readImpl() throws BufferUnderflowException, RuntimeException {

    readC();//from w w w  .  j  a va  2 s  .  c o m
    if (readC() == WoWAuthResponse.WOW_SUCCESS.getMessageId()) {
        final SecureRandom random = new SecureRandom();
        MessageDigest sha = null;
        try {
            sha = MessageDigest.getInstance("SHA-1");
        } catch (final NoSuchAlgorithmException e) {
            e.printStackTrace();
            return;
        }
        final BigInteger k = new BigInteger("3");
        final byte[] Bb = readB(32);
        final BigInteger g = new BigInteger(readB(readC()));
        final byte[] Nb = readB(readC());
        final byte[] saltb = readB(32);
        /* byte[] unk3 = */readB(16);
        readC();
        ArrayUtils.reverse(Bb);
        final BigInteger B = new BigInteger(1, Bb);
        ArrayUtils.reverse(Bb);
        ArrayUtils.reverse(Nb);
        final BigInteger N = new BigInteger(1, Nb);
        ArrayUtils.reverse(Nb);
        final BigInteger a = new BigInteger(1, random.generateSeed(19));

        final byte[] passhash = sha.digest(this.config.AUTH_LOGIN.toUpperCase().concat(":")
                .concat(this.config.AUTH_PASSWORD.toUpperCase()).getBytes(Charset.forName("UTF-8")));
        sha.update(saltb);
        sha.update(passhash);

        final byte[] xhash = sha.digest();
        ArrayUtils.reverse(xhash);
        final BigInteger x = new BigInteger(1, xhash);
        logger.debug("x:" + x.toString(16).toUpperCase());
        final BigInteger v = g.modPow(x, N);
        logger.debug("v:" + v.toString(16).toUpperCase());
        final BigInteger A = g.modPow(a, N);
        logger.debug("A:" + A.toString(16).toUpperCase());
        logger.debug("B:" + B.toString(16).toUpperCase());
        this.ahash = A.toByteArray();
        ArrayUtils.reverse(this.ahash);
        sha.update(this.ahash);
        sha.update(Bb);
        final byte[] hashu = sha.digest();
        ArrayUtils.reverse(hashu);
        final BigInteger u = new BigInteger(1, hashu);
        logger.debug("u:" + u.toString(16).toUpperCase());
        final BigInteger S = (B.subtract(k.multiply(g.modPow(x, N)))).modPow(a.add(u.multiply(x)), N);

        final byte[] full_S = S.toByteArray();
        ArrayUtils.reverse(full_S);
        logger.debug("t:" + StringUtils.toHexString(full_S));
        final byte[] s1_hash = new byte[16];
        final byte[] s2_hash = new byte[16];
        for (int i = 0; i < 16; i++) {
            s1_hash[i] = full_S[i * 2];
            s2_hash[i] = full_S[(i * 2) + 1];
        }
        final byte[] t1 = sha.digest(s1_hash);
        final byte[] t2 = sha.digest(s2_hash);
        final byte[] vK = new byte[40];
        for (int i = 0; i < 20; i++) {
            vK[i * 2] = t1[i];
            vK[(i * 2) + 1] = t2[i];
        }

        byte[] hash = new byte[20];
        logger.debug("N:" + N.toString(16).toUpperCase());
        hash = sha.digest(Nb);

        logger.debug("hash:" + new BigInteger(1, hash).toString(16).toUpperCase());

        byte[] gH = new byte[20];
        sha.update(g.toByteArray());
        gH = sha.digest();
        for (int i = 0; i < 20; ++i) {
            hash[i] ^= gH[i];
        }

        byte[] t4 = new byte[20];
        t4 = sha.digest(this.config.AUTH_LOGIN.toUpperCase().getBytes(Charset.forName("UTF-8")));

        sha.update(hash);
        logger.debug("hash:" + StringUtils.toHexString(hash));
        sha.update(t4);
        logger.debug("t4:" + StringUtils.toHexString(t4));
        sha.update(saltb);
        logger.debug("saltb:" + StringUtils.toHexString(saltb));
        sha.update(this.ahash);
        logger.debug("ahash:" + StringUtils.toHexString(this.ahash));
        sha.update(Bb);
        logger.debug("Bb:" + StringUtils.toHexString(Bb));
        sha.update(vK);
        logger.debug("vK:" + StringUtils.toHexString(vK));
        this.m1 = sha.digest();

        sha.update(this.ahash);
        sha.update(this.m1);
        sha.update(vK);
        logger.debug("m1 value" + StringUtils.toHexString(this.m1));
        @SuppressWarnings("unused")
        final byte[] m2 = sha.digest();

        final ChannelPipeline pipeline = getClient().getChannel().getPipeline();
        ((RealmToAuthChannelHandler) pipeline.getLast()).setSeed(vK);

    } else {
        getChannel().getPipeline().remove("handler");
        getChannel().getPipeline().remove("eventlog");
        getChannel().getPipeline().remove("executor");
        getChannel().close();
        getChannel().getFactory().releaseExternalResources();
    }
}

From source file:com.kncwallet.wallet.ui.SendCoinsFragment.java

private void validateAmounts(final boolean popups) {
    isValidAmounts = false;/*from ww w  .  jav a 2 s .c o m*/

    final BigInteger amount = amountCalculatorLink.getAmount();

    if (amount == null) {
        // empty amount
        if (popups)
            popupMessage(amountCalculatorLink.activeView(),
                    getString(R.string.send_coins_fragment_amount_empty));
    } else if (amount.signum() > 0) {
        final BigInteger estimated = wallet.getBalance(BalanceType.ESTIMATED);
        final BigInteger available = wallet.getBalance(BalanceType.AVAILABLE);
        final BigInteger pending = estimated.subtract(available);
        // TODO subscribe to wallet changes

        final BigInteger availableAfterAmount = available.subtract(amount);
        final boolean enoughFundsForAmount = availableAfterAmount.signum() >= 0;

        if (enoughFundsForAmount) {
            // everything fine
            isValidAmounts = true;
        } else {
            // not enough funds for amount
            //if (popups)
            //   popupAvailable(amountCalculatorLink.activeView(), available, pending);
        }
    } else {
        // invalid amount
        //if (popups)
        //   popupMessage(amountCalculatorLink.activeView(), getString(R.string.send_coins_fragment_amount_error));
    }

    updateView();
}

From source file:org.estatio.api.Api.java

private LeaseTerm putLeaseTerm(final String leaseReference, final String unitReference,
        final BigInteger itemSequence, final String itemType, final LocalDate itemStartDate,
        final LocalDate startDate, final LocalDate endDate, final BigInteger sequence, final String statusStr) {
    final Lease lease = fetchLease(leaseReference);
    final Unit unit;
    if (unitReference != null) {
        unit = units.findUnitByReference(unitReference);
        if (unitReference != null && unit == null) {
            throw new ApplicationException(String.format("Unit with reference %s not found.", unitReference));
        }/* w  w  w.j  a  va2 s .  co  m*/
    }
    final LeaseItemType leaseItemType = fetchLeaseItemType(itemType);
    final LeaseItem item = lease.findItem(leaseItemType, itemStartDate, itemSequence);
    if (item == null) {
        throw new ApplicationException(
                String.format("LeaseItem with reference %1$s, %2$s, %3$s, %4$s not found.", leaseReference,
                        leaseItemType.toString(), itemStartDate.toString(), itemSequence.toString()));
    }
    LeaseTerm term = item.findTermWithSequence(sequence);
    if (term == null) {
        if (sequence.equals(BigInteger.ONE)) {
            term = item.newTerm(startDate, endDate);
        } else {
            final LeaseTerm previousTerm = item.findTermWithSequence(sequence.subtract(BigInteger.ONE));
            term = previousTerm.createNext(startDate, endDate);
        }
        term.setSequence(sequence);
    }
    term.setStatus(org.estatio.dom.lease.LeaseTermStatus.valueOf(statusStr));
    return term;
}

From source file:piuk.MyRemoteWallet.java

public Pair<Transaction, Long> makeTransaction(KeyBag keyWallet, List<MyTransactionOutPoint> unspent,
        String toAddress, String changeAddress, BigInteger amount, BigInteger baseFee,
        boolean consumeAllOutputs) throws Exception {

    long priority = 0;

    if (unspent == null || unspent.size() == 0)
        throw new InsufficientFundsException("No free outputs to spend.");

    if (amount == null || amount.compareTo(BigInteger.ZERO) <= 0)
        throw new Exception("You must provide an amount");

    //Construct a new transaction
    Transaction tx = new Transaction(params);

    final Script toOutputScript = ScriptBuilder.createOutputScript(new Address(MainNetParams.get(), toAddress));

    final TransactionOutput output = new TransactionOutput(params, null, Coin.valueOf(amount.longValue()),
            toOutputScript.getProgram());

    tx.addOutput(output);//from  ww  w  .java2 s.c  om

    //Now select the appropriate inputs
    BigInteger valueSelected = BigInteger.ZERO;
    BigInteger valueNeeded = amount.add(baseFee);
    BigInteger minFreeOutputSize = BigInteger.valueOf(1000000);

    for (MyTransactionOutPoint outPoint : unspent) {

        Script scriptPubKey = outPoint.getConnectedOutput().getScriptPubKey();

        if (scriptPubKey == null) {
            throw new Exception("scriptPubKey is null");
        }

        final ECKey key = keyWallet.findKeyFromPubHash(scriptPubKey.getPubKeyHash());

        if (key == null) {
            throw new Exception("Unable to find ECKey for scriptPubKey " + scriptPubKey);
        }

        MyTransactionInput input = new MyTransactionInput(params, null, new byte[0], outPoint);

        tx.addInput(input);

        input.setScriptSig(scriptPubKey.createEmptyInputScript(key, null));

        valueSelected = valueSelected.add(BigInteger.valueOf(outPoint.getValue().longValue()));

        priority += outPoint.getValue().longValue() * outPoint.confirmations;

        if (!consumeAllOutputs) {
            if (valueSelected.compareTo(valueNeeded) == 0
                    || valueSelected.compareTo(valueNeeded.add(minFreeOutputSize)) >= 0)
                break;
        }
    }

    //Check the amount we have selected is greater than the amount we need
    if (valueSelected.compareTo(valueNeeded) < 0) {
        throw new InsufficientFundsException("Insufficient Funds");
    }

    long estimatedSize = tx.bitcoinSerialize().length + (138 * tx.getInputs().size());

    BigInteger fee = BigInteger.valueOf((int) Math.ceil(estimatedSize / 1000d)).multiply(baseFee);

    BigInteger change = valueSelected.subtract(amount).subtract(fee);

    if (change.compareTo(BigInteger.ZERO) < 0) {
        throw new Exception("Insufficient Value for Fee. Fix this lazy.");
    } else if (change.compareTo(BigInteger.ZERO) > 0) {
        //Now add the change if there is any
        final Script change_script = ScriptBuilder
                .createOutputScript(new Address(MainNetParams.get(), changeAddress));

        TransactionOutput change_output = new TransactionOutput(params, null, Coin.valueOf(change.longValue()),
                change_script.getProgram());

        tx.addOutput(change_output);
    }

    estimatedSize = tx.bitcoinSerialize().length + (138 * tx.getInputs().size());

    priority /= estimatedSize;

    return new Pair<Transaction, Long>(tx, priority);
}

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

private ArrayList<JSONRPCTransactionAmount> getAssetTransactionAmounts(Wallet wallet, Transaction tx,
        boolean excludeBTCFee, boolean absoluteBTCFee) {
    if (wallet == null || tx == null)
        return null;

    Map<Integer, BigInteger> receiveMap = wallet.CS.getAssetsSentToMe(tx);
    Map<Integer, BigInteger> sendMap = wallet.CS.getAssetsSentFromMe(tx);

    //   System.out.println(">>>> tx = " + tx.getHashAsString());
    //   System.out.println(">>>>     receive map = " +  receiveMap);
    //   System.out.println(">>>>     send map = " +  sendMap);

    //Map<String, String> nameAmountMap = new TreeMap<>();
    ArrayList<JSONRPCTransactionAmount> resultList = new ArrayList<>();

    boolean isSentByMe = tx.sent(wallet);
    Map<Integer, BigInteger> loopMap = (isSentByMe) ? sendMap : receiveMap;

    //   Integer assetID = null;
    BigInteger netAmount = null;

    //   for (Map.Entry<Integer, BigInteger> entry : loopMap.entrySet()) {
    for (Integer assetID : loopMap.keySet()) {
        //       assetID = entry.getKey();
        if (assetID == null || assetID == 0)
            continue; // skip bitcoin

        BigInteger receivedAmount = receiveMap.get(assetID); // should be number of raw units
        BigInteger sentAmount = sendMap.get(assetID);
        boolean isReceivedAmountMissing = (receivedAmount == null);
        boolean isSentAmountMissing = (sentAmount == null);

        netAmount = BigInteger.ZERO;
        if (!isReceivedAmountMissing)
            netAmount = netAmount.add(receivedAmount);
        if (!isSentAmountMissing)
            netAmount = netAmount.subtract(sentAmount);

        if (isSentByMe && !isSentAmountMissing && sentAmount.equals(BigInteger.ZERO)) {
            // Catch a case where for a send transaction, the send amount for an asset is 0,
            // but the receive cmount is not 0.  Also the asset was not valid.
            continue;
        }/*from   www .j a v  a 2  s . c  o m*/

        CSAsset asset = wallet.CS.getAsset(assetID);
        if (asset == null) {
            // something went wrong, we have asset id but no asset, probably deleted.
            // For now, we carry on, and we display what we know.
        }

        if (netAmount.equals(BigInteger.ZERO) && isSentByMe) {
            // If net asset is 0 and this is our send transaction,
            // we don't need to show anything, as this probably due to implicit transfer.
            // So continue the loop.
            continue;
        }

        if (netAmount.equals(BigInteger.ZERO) && !isSentByMe) {
            // Receiving an asset, where the value is 0 because its not confirmed yet,
            // or not known because asset files not uploaded so we dont know display format.
            // Anyway, we don't do anything here as we do want to display this incoming
            // transaction the best we can.
        }

        //       System.out.println(">>>>     isSentAmountMissing = " + isSentAmountMissing);
        //       System.out.println(">>>>     asset reference = " + asset.getAssetReference());
        //       System.out.println(">>>>     asset name = " + asset.getName());

        String name = null;
        CoinSparkGenesis genesis = null;
        boolean isUnknown = false;
        if (asset != null) {
            genesis = asset.getGenesis();
            name = asset.getNameShort(); // could return null?
        }
        if (name == null) {
            isUnknown = true;
            if (genesis != null) {
                name = "Asset from " + genesis.getDomainName();
            } else {
                // No genesis block found yet
                name = "Other Asset";
            }
        }

        String s1 = null;
        if (asset == null || isUnknown == true || (netAmount.equals(BigInteger.ZERO) && !isSentByMe)) {
            // We don't have formatting details since asset is unknown or deleted
            // If there is a quantity, we don't display it since we don't have display format info
            // Of if incoming asset transfer, unconfirmed, it will be zero, so show ... instead
            s1 = "...";
        } else {
            BigDecimal displayUnits = CSMiscUtils.getDisplayUnitsForRawUnits(asset, netAmount);
            s1 = CSMiscUtils.getFormattedDisplayString(asset, displayUnits);
        }

        //
        // Create JSONRPCTransactionAmount and add it to list
        // 
        String fullName = "";
        String assetRef = "";
        if (asset != null) {
            fullName = asset.getName();
            if (fullName == null)
                fullName = name; // use short name
            assetRef = CSMiscUtils.getHumanReadableAssetRef(asset);
        }
        BigDecimal displayQty = CSMiscUtils.getDisplayUnitsForRawUnits(asset, netAmount);
        JSONRPCTransactionAmount amount = new JSONRPCTransactionAmount();
        amount.setAsset_ref(assetRef);
        amount.setDisplay(s1);
        amount.setName(fullName);
        amount.setName_short(name);
        amount.setQty(displayQty.doubleValue());
        amount.setRaw(netAmount.longValue());
        resultList.add(amount);
    }

    BigInteger satoshiAmount = receiveMap.get(0);
    satoshiAmount = satoshiAmount.subtract(sendMap.get(0));

    // We will show the fee separately so no need to include here.
    if (excludeBTCFee && isSentByMe) {
        BigInteger feeSatoshis = tx.calculateFee(wallet); // returns positive
        if (absoluteBTCFee) {
            satoshiAmount = satoshiAmount.abs().subtract(feeSatoshis);
        } else {
            satoshiAmount = satoshiAmount.add(feeSatoshis);
        }
    }

    String btcAmount = Utils.bitcoinValueToFriendlyString(satoshiAmount) + " BTC";
    BigDecimal satoshiAmountBTC = new BigDecimal(satoshiAmount).divide(new BigDecimal(Utils.COIN));
    JSONRPCTransactionAmount amount = new JSONRPCTransactionAmount();
    amount.setAsset_ref("bitcoin");
    amount.setDisplay(btcAmount);
    amount.setName("Bitcoin");
    amount.setName_short("Bitcoin");
    amount.setQty(satoshiAmountBTC.doubleValue());
    amount.setRaw(satoshiAmount.longValue());
    resultList.add(amount);

    return resultList;
}

From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java

protected Response invoke(UrlBuilder url, String method, String contentType, Map<String, String> headers,
        Output writer, BindingSession session, BigInteger offset, BigInteger length) {
    try {//from  www  .j ava 2s . c  o  m
        // log before connect
        //Log.d("URL", url.toString());
        if (LOG.isDebugEnabled()) {
            LOG.debug(method + " " + url);
        }

        // connect
        HttpURLConnection conn = getHttpURLConnection(new URL(url.toString()));
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(writer != null);
        conn.setAllowUserInteraction(false);
        conn.setUseCaches(false);
        conn.setRequestProperty(HTTP.USER_AGENT, ClientVersion.OPENCMIS_CLIENT);

        // timeouts
        int connectTimeout = session.get(SessionParameter.CONNECT_TIMEOUT, -1);
        if (connectTimeout >= 0) {
            conn.setConnectTimeout(connectTimeout);
        }

        int readTimeout = session.get(SessionParameter.READ_TIMEOUT, -1);
        if (readTimeout >= 0) {
            conn.setReadTimeout(readTimeout);
        }

        // set content type
        if (contentType != null) {
            conn.setRequestProperty(HTTP.CONTENT_TYPE, contentType);
        }
        // set other headers
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                conn.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // authenticate
        AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session);
        if (authProvider != null) {
            Map<String, List<String>> httpHeaders = authProvider.getHTTPHeaders(url.toString());
            if (httpHeaders != null) {
                for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) {
                    if (header.getValue() != null) {
                        for (String value : header.getValue()) {
                            conn.addRequestProperty(header.getKey(), value);
                        }
                    }
                }
            }

            if (conn instanceof HttpsURLConnection) {
                SSLSocketFactory sf = authProvider.getSSLSocketFactory();
                if (sf != null) {
                    ((HttpsURLConnection) conn).setSSLSocketFactory(sf);
                }

                HostnameVerifier hv = authProvider.getHostnameVerifier();
                if (hv != null) {
                    ((HttpsURLConnection) conn).setHostnameVerifier(hv);
                }
            }
        }

        // range
        if ((offset != null) || (length != null)) {
            StringBuilder sb = new StringBuilder("bytes=");

            if ((offset == null) || (offset.signum() == -1)) {
                offset = BigInteger.ZERO;
            }

            sb.append(offset.toString());
            sb.append("-");

            if ((length != null) && (length.signum() == 1)) {
                sb.append(offset.add(length.subtract(BigInteger.ONE)).toString());
            }

            conn.setRequestProperty("Range", sb.toString());
        }

        // compression
        Object compression = session.get(AlfrescoSession.HTTP_ACCEPT_ENCODING);
        if (compression == null) {
            conn.setRequestProperty("Accept-Encoding", "");
        } else {
            Boolean compressionValue;
            try {
                compressionValue = Boolean.parseBoolean(compression.toString());
                if (compressionValue) {
                    conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
                } else {
                    conn.setRequestProperty("Accept-Encoding", "");
                }
            } catch (Exception e) {
                conn.setRequestProperty("Accept-Encoding", compression.toString());
            }
        }

        // locale
        if (session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) instanceof String
                && session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) != null) {
            conn.setRequestProperty("Accept-Language",
                    session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE).toString());
        }

        // send data
        if (writer != null) {
            Object chunkTransfert = session.get(AlfrescoSession.HTTP_CHUNK_TRANSFERT);
            if (chunkTransfert != null && Boolean.parseBoolean(chunkTransfert.toString())) {
                conn.setRequestProperty(HTTP.TRANSFER_ENCODING, "chunked");
                conn.setChunkedStreamingMode(0);
            }

            conn.setConnectTimeout(900000);

            OutputStream connOut = null;

            Object clientCompression = session.get(SessionParameter.CLIENT_COMPRESSION);
            if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                conn.setRequestProperty(HTTP.CONTENT_ENCODING, "gzip");
                connOut = new GZIPOutputStream(conn.getOutputStream(), 4096);
            } else {
                connOut = conn.getOutputStream();
            }

            OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE);
            writer.write(out);
            out.flush();
        }

        // connect
        conn.connect();

        // get stream, if present
        int respCode = conn.getResponseCode();
        InputStream inputStream = null;
        if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED)
                || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION)
                || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) {
            inputStream = conn.getInputStream();
        }

        // log after connect
        if (LOG.isTraceEnabled()) {
            LOG.trace(method + " " + url + " > Headers: " + conn.getHeaderFields());
        }

        // forward response HTTP headers
        if (authProvider != null) {
            authProvider.putResponseHeaders(url.toString(), respCode, conn.getHeaderFields());
        }

        // get the response
        return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream,
                conn.getErrorStream());
    } catch (Exception e) {
        throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e);
    }
}

From source file:piuk.blockchain.android.MyRemoteWallet.java

public Pair<Transaction, Long> makeTransaction(boolean isSimpleSend, List<MyTransactionOutPoint> unspent,
        HashMap<String, BigInteger> receivingAddresses, BigInteger fee, final String changeAddress)
        throws Exception {

    long priority = 0;

    if (unspent == null || unspent.size() == 0)
        throw new InsufficientFundsException("No free outputs to spend.");

    if (fee == null)
        fee = BigInteger.ZERO;/*from w w w  .  j  ava  2s.  c  o  m*/

    //Construct a new transaction
    Transaction tx = new Transaction(getParams());

    BigInteger outputValueSum = BigInteger.ZERO;

    for (Iterator<Entry<String, BigInteger>> iterator = receivingAddresses.entrySet().iterator(); iterator
            .hasNext();) {
        Map.Entry<String, BigInteger> mapEntry = iterator.next();
        String toAddress = mapEntry.getKey();
        BigInteger amount = mapEntry.getValue();

        if (amount == null || amount.compareTo(BigInteger.ZERO) <= 0)
            throw new Exception("You must provide an amount");

        outputValueSum = outputValueSum.add(amount);
        //Add the output
        BitcoinScript toOutputScript = BitcoinScript.createSimpleOutBitoinScript(new BitcoinAddress(toAddress));
        //         Log.d("MyRemoteWallet", "MyRemoteWallet makeTransaction toAddress: " + toAddress + "amount: " + amount);

        TransactionOutput output = new TransactionOutput(getParams(), null, amount,
                toOutputScript.getProgram());

        tx.addOutput(output);
    }

    //Now select the appropriate inputs
    BigInteger valueSelected = BigInteger.ZERO;
    BigInteger valueNeeded = outputValueSum.add(fee);
    BigInteger minFreeOutputSize = BigInteger.valueOf(1000000);

    MyTransactionOutPoint changeOutPoint = null;

    for (MyTransactionOutPoint outPoint : unspent) {

        BitcoinScript script = new BitcoinScript(outPoint.getScriptBytes());

        if (script.getOutType() == BitcoinScript.ScriptOutTypeStrange)
            continue;

        BitcoinScript inputScript = new BitcoinScript(outPoint.getConnectedPubKeyScript());
        String address = inputScript.getAddress().toString();

        //if isSimpleSend don't use address as input if is output 
        if (isSimpleSend && receivingAddresses.get(address) != null)
            continue;

        MyTransactionInput input = new MyTransactionInput(getParams(), null, new byte[0], outPoint);

        input.outpoint = outPoint;
        //         Log.d("MyRemoteWallet", "MyRemoteWallet makeTransaction fromAddress: " + address + "amount: " + outPoint.value);

        tx.addInput(input);

        valueSelected = valueSelected.add(outPoint.value);

        priority += outPoint.value.longValue() * outPoint.confirmations;

        if (changeAddress == null)
            changeOutPoint = outPoint;

        if (valueSelected.compareTo(valueNeeded) == 0
                || valueSelected.compareTo(valueNeeded.add(minFreeOutputSize)) >= 0)
            break;
    }

    //Check the amount we have selected is greater than the amount we need
    if (valueSelected.compareTo(valueNeeded) < 0) {
        throw new InsufficientFundsException("Insufficient Funds");
    }

    BigInteger change = valueSelected.subtract(outputValueSum).subtract(fee);

    //Now add the change if there is any
    if (change.compareTo(BigInteger.ZERO) > 0) {
        BitcoinScript change_script;
        if (changeAddress != null) {
            change_script = BitcoinScript.createSimpleOutBitoinScript(new BitcoinAddress(changeAddress));
            //            Log.d("MyRemoteWallet", "MyRemoteWallet makeTransaction changeAddress != null: " + changeAddress + "change: " + change);
        } else if (changeOutPoint != null) {
            BitcoinScript inputScript = new BitcoinScript(changeOutPoint.getConnectedPubKeyScript());
            //             Log.d("MyRemoteWallet", "MyRemoteWallet makeTransaction changeAddress == null: " + inputScript.getAddress() + "change: " + change);

            //Return change to the first address
            change_script = BitcoinScript.createSimpleOutBitoinScript(inputScript.getAddress());
        } else {
            throw new Exception("Invalid transaction attempt");
        }
        TransactionOutput change_output = new TransactionOutput(getParams(), null, change,
                change_script.getProgram());

        tx.addOutput(change_output);
    }

    long estimatedSize = tx.bitcoinSerialize().length + (114 * tx.getInputs().size());

    priority /= estimatedSize;

    return new Pair<Transaction, Long>(tx, priority);
}

From source file:piuk.blockchain.android.MyRemoteWallet.java

public Pair<Transaction, Long> makeTransactionCustom(final HashMap<String, BigInteger> sendingAddresses,
        List<MyTransactionOutPoint> unspent, HashMap<String, BigInteger> receivingAddresses, BigInteger fee,
        final String changeAddress) throws Exception {

    long priority = 0;

    if (unspent == null || unspent.size() == 0)
        throw new InsufficientFundsException("No free outputs to spend.");

    if (fee == null)
        fee = BigInteger.ZERO;//from w  w w  .  j  av  a 2s .  com

    //Construct a new transaction
    Transaction tx = new Transaction(getParams());

    BigInteger outputValueSum = BigInteger.ZERO;

    for (Iterator<Entry<String, BigInteger>> iterator = receivingAddresses.entrySet().iterator(); iterator
            .hasNext();) {
        Map.Entry<String, BigInteger> mapEntry = iterator.next();
        String toAddress = mapEntry.getKey();
        BigInteger amount = mapEntry.getValue();

        if (amount == null || amount.compareTo(BigInteger.ZERO) <= 0)
            throw new Exception("You must provide an amount");

        outputValueSum = outputValueSum.add(amount);
        //Add the output
        BitcoinScript toOutputScript = BitcoinScript.createSimpleOutBitoinScript(new BitcoinAddress(toAddress));
        //         Log.d("MyRemoteWallet", "MyRemoteWallet makeTransactionCustom toAddress: " + toAddress + "amount: " + amount);

        TransactionOutput output = new TransactionOutput(getParams(), null, amount,
                toOutputScript.getProgram());
        tx.addOutput(output);
    }

    //Now select the appropriate inputs
    BigInteger valueSelected = BigInteger.ZERO;
    BigInteger valueNeeded = outputValueSum.add(fee);

    Map<String, BigInteger> addressTotalUnspentValues = new HashMap<String, BigInteger>();

    for (MyTransactionOutPoint outPoint : unspent) {

        BitcoinScript script = new BitcoinScript(outPoint.getScriptBytes());

        if (script.getOutType() == BitcoinScript.ScriptOutTypeStrange)
            continue;

        BitcoinScript inputScript = new BitcoinScript(outPoint.getConnectedPubKeyScript());
        String address = inputScript.getAddress().toString();

        BigInteger addressSendAmount = sendingAddresses.get(address);
        if (addressSendAmount == null) {
            throw new Exception("Invalid transaction address send amount is null");
        }

        final BigInteger addressTotalUnspentValue = addressTotalUnspentValues.get(address);

        if (addressTotalUnspentValue == null) {
            addressTotalUnspentValues.put(address, outPoint.value);
        } else {
            addressTotalUnspentValues.put(address, addressTotalUnspentValue.add(outPoint.value));
        }

        MyTransactionInput input = new MyTransactionInput(getParams(), null, new byte[0], outPoint);

        input.outpoint = outPoint;
        //         Log.d("MyRemoteWallet", "MyRemoteWallet makeTransactionCustom fromAddress: " + address + "amount: " + outPoint.value);

        tx.addInput(input);

        valueSelected = valueSelected.add(outPoint.value);

        priority += outPoint.value.longValue() * outPoint.confirmations;

        //if (valueSelected.compareTo(valueNeeded) == 0 || valueSelected.compareTo(valueNeeded.add(minFreeOutputSize)) >= 0)
        //   break;
    }

    //Check the amount we have selected is greater than the amount we need
    if (valueSelected.compareTo(valueNeeded) < 0) {
        throw new InsufficientFundsException("Insufficient Funds");
    }

    //decide change
    if (changeAddress == null) {
        BigInteger feeAmountLeftToAccountedFor = fee;

        for (Iterator<Entry<String, BigInteger>> iterator = addressTotalUnspentValues.entrySet()
                .iterator(); iterator.hasNext();) {
            final Entry<String, BigInteger> entry = iterator.next();
            final String address = entry.getKey();
            final BigInteger addressTotalUnspentValue = entry.getValue();
            final BigInteger addressSendAmount = sendingAddresses.get(address);
            BigInteger addressChangeAmount = addressTotalUnspentValue.subtract(addressSendAmount);

            if (feeAmountLeftToAccountedFor.compareTo(BigInteger.ZERO) > 0) {

                if (addressChangeAmount.compareTo(feeAmountLeftToAccountedFor) >= 0) {
                    //have enough to fill fee
                    addressChangeAmount = addressChangeAmount.subtract(feeAmountLeftToAccountedFor);
                    feeAmountLeftToAccountedFor = BigInteger.ZERO;
                } else {
                    // do not have enough to fill fee
                    feeAmountLeftToAccountedFor = feeAmountLeftToAccountedFor.subtract(addressChangeAmount);
                    addressChangeAmount = BigInteger.ZERO;
                }
            }

            if (addressChangeAmount.compareTo(BigInteger.ZERO) > 0) {
                //Add the output
                BitcoinScript toOutputScript = BitcoinScript
                        .createSimpleOutBitoinScript(new BitcoinAddress(address));
                //                Log.d("MyRemoteWallet", "MyRemoteWallet makeTransactionCustom changeAddress == null: " + address + "addressChangeAmount: " + addressChangeAmount);

                TransactionOutput output = new TransactionOutput(getParams(), null, addressChangeAmount,
                        toOutputScript.getProgram());

                tx.addOutput(output);
            }
        }
    } else {
        BigInteger addressChangeAmountSum = BigInteger.ZERO;
        for (Iterator<Entry<String, BigInteger>> iterator = addressTotalUnspentValues.entrySet()
                .iterator(); iterator.hasNext();) {
            final Entry<String, BigInteger> entry = iterator.next();
            final String address = entry.getKey();
            final BigInteger addressTotalUnspentValue = entry.getValue();
            final BigInteger addressSendAmount = sendingAddresses.get(address);
            final BigInteger addressChangeAmount = addressTotalUnspentValue.subtract(addressSendAmount);
            addressChangeAmountSum = addressChangeAmountSum.add(addressChangeAmount);
        }

        if (addressChangeAmountSum.compareTo(BigInteger.ZERO) > 0) {
            //Add the output
            BitcoinScript toOutputScript = BitcoinScript
                    .createSimpleOutBitoinScript(new BitcoinAddress(changeAddress));

            TransactionOutput output = new TransactionOutput(getParams(), null,
                    addressChangeAmountSum.subtract(fee), toOutputScript.getProgram());
            //             Log.d("MyRemoteWallet", "MyRemoteWallet makeTransactionCustom changeAddress != null: " + changeAddress + "addressChangeAmount: " + output.getValue());
            tx.addOutput(output);
        }
    }

    long estimatedSize = tx.bitcoinSerialize().length + (114 * tx.getInputs().size());

    priority /= estimatedSize;

    return new Pair<Transaction, Long>(tx, priority);
}

From source file:org.apache.chemistry.opencmis.client.bindings.spi.http.AbstractApacheClientHttpInvoker.java

protected Response invoke(UrlBuilder url, String method, String contentType, Map<String, String> headers,
        final Output writer, final BindingSession session, BigInteger offset, BigInteger length) {
    int respCode = -1;

    try {/*  ww  w  .j  a v a2  s . c om*/
        // log before connect
        if (LOG.isDebugEnabled()) {
            LOG.debug("Session {}: {} {}", session.getSessionId(), method, url);
        }

        // get HTTP client object from session
        DefaultHttpClient httpclient = (DefaultHttpClient) session.get(HTTP_CLIENT);
        if (httpclient == null) {
            session.writeLock();
            try {
                httpclient = (DefaultHttpClient) session.get(HTTP_CLIENT);
                if (httpclient == null) {
                    httpclient = createHttpClient(url, session);
                    session.put(HTTP_CLIENT, httpclient, true);
                }
            } finally {
                session.writeUnlock();
            }
        }

        HttpRequestBase request = null;

        if ("GET".equals(method)) {
            request = new HttpGet(url.toString());
        } else if ("POST".equals(method)) {
            request = new HttpPost(url.toString());
        } else if ("PUT".equals(method)) {
            request = new HttpPut(url.toString());
        } else if ("DELETE".equals(method)) {
            request = new HttpDelete(url.toString());
        } else {
            throw new CmisRuntimeException("Invalid HTTP method!");
        }

        // set content type
        if (contentType != null) {
            request.setHeader("Content-Type", contentType);
        }
        // set other headers
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                request.addHeader(header.getKey(), header.getValue());
            }
        }

        // authenticate
        AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session);
        if (authProvider != null) {
            Map<String, List<String>> httpHeaders = authProvider.getHTTPHeaders(url.toString());
            if (httpHeaders != null) {
                for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) {
                    if (header.getKey() != null && isNotEmpty(header.getValue())) {
                        String key = header.getKey();
                        if (key.equalsIgnoreCase("user-agent")) {
                            request.setHeader("User-Agent", header.getValue().get(0));
                        } else {
                            for (String value : header.getValue()) {
                                if (value != null) {
                                    request.addHeader(key, value);
                                }
                            }
                        }
                    }
                }
            }
        }

        // range
        if ((offset != null) || (length != null)) {
            StringBuilder sb = new StringBuilder("bytes=");

            if ((offset == null) || (offset.signum() == -1)) {
                offset = BigInteger.ZERO;
            }

            sb.append(offset.toString());
            sb.append('-');

            if ((length != null) && (length.signum() == 1)) {
                sb.append(offset.add(length.subtract(BigInteger.ONE)).toString());
            }

            request.setHeader("Range", sb.toString());
        }

        // compression
        Object compression = session.get(SessionParameter.COMPRESSION);
        if ((compression != null) && Boolean.parseBoolean(compression.toString())) {
            request.setHeader("Accept-Encoding", "gzip,deflate");
        }

        // locale
        if (session.get(CmisBindingsHelper.ACCEPT_LANGUAGE) instanceof String) {
            request.setHeader("Accept-Language", session.get(CmisBindingsHelper.ACCEPT_LANGUAGE).toString());
        }

        // send data
        if (writer != null) {
            Object clientCompression = session.get(SessionParameter.CLIENT_COMPRESSION);
            final boolean clientCompressionFlag = (clientCompression != null)
                    && Boolean.parseBoolean(clientCompression.toString());
            if (clientCompressionFlag) {
                request.setHeader("Content-Encoding", "gzip");
            }

            AbstractHttpEntity streamEntity = new AbstractHttpEntity() {
                @Override
                public boolean isChunked() {
                    return true;
                }

                @Override
                public boolean isRepeatable() {
                    return false;
                }

                @Override
                public long getContentLength() {
                    return -1;
                }

                @Override
                public boolean isStreaming() {
                    return false;
                }

                @Override
                public InputStream getContent() throws IOException {
                    throw new UnsupportedOperationException();
                }

                @Override
                public void writeTo(final OutputStream outstream) throws IOException {
                    OutputStream connOut = null;

                    if (clientCompressionFlag) {
                        connOut = new GZIPOutputStream(outstream, 4096);
                    } else {
                        connOut = outstream;
                    }

                    OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE);
                    try {
                        writer.write(out);
                    } catch (IOException ioe) {
                        throw ioe;
                    } catch (Exception e) {
                        throw new IOException(e);
                    }
                    out.flush();

                    if (connOut instanceof GZIPOutputStream) {
                        ((GZIPOutputStream) connOut).finish();
                    }
                }
            };
            ((HttpEntityEnclosingRequestBase) request).setEntity(streamEntity);
        }

        // connect
        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();

        // get stream, if present
        respCode = response.getStatusLine().getStatusCode();
        InputStream inputStream = null;
        InputStream errorStream = null;

        if ((respCode == 200) || (respCode == 201) || (respCode == 203) || (respCode == 206)) {
            if (entity != null) {
                inputStream = entity.getContent();
            } else {
                inputStream = new ByteArrayInputStream(new byte[0]);
            }
        } else {
            if (entity != null) {
                errorStream = entity.getContent();
            } else {
                errorStream = new ByteArrayInputStream(new byte[0]);
            }
        }

        // collect headers
        Map<String, List<String>> responseHeaders = new HashMap<String, List<String>>();
        for (Header header : response.getAllHeaders()) {
            List<String> values = responseHeaders.get(header.getName());
            if (values == null) {
                values = new ArrayList<String>();
                responseHeaders.put(header.getName(), values);
            }
            values.add(header.getValue());
        }

        // log after connect
        if (LOG.isTraceEnabled()) {
            LOG.trace("Session {}: {} {} > Headers: {}", session.getSessionId(), method, url,
                    responseHeaders.toString());
        }

        // forward response HTTP headers
        if (authProvider != null) {
            authProvider.putResponseHeaders(url.toString(), respCode, responseHeaders);
        }

        // get the response
        return new Response(respCode, response.getStatusLine().getReasonPhrase(), responseHeaders, inputStream,
                errorStream);
    } catch (Exception e) {
        String status = (respCode > 0 ? " (HTTP status code " + respCode + ")" : "");
        throw new CmisConnectionException("Cannot access \"" + url + "\"" + status + ": " + e.getMessage(), e);
    }
}