Example usage for java.math BigInteger add

List of usage examples for java.math BigInteger add

Introduction

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

Prototype

BigInteger add(long val) 

Source Link

Document

Package private methods used by BigDecimal code to add a BigInteger with a long.

Usage

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   www .j a v a  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;/*w ww  . ja va 2  s  .  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 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.fenixedu.treasury.services.integration.erp.ERPExporter.java

private String generateERPFile(FinantialInstitution institution, DateTime fromDate, DateTime toDate,
        List<? extends FinantialDocument> allDocuments, Boolean generateAllCustomers,
        Boolean generateAllProducts,
        java.util.function.UnaryOperator<AuditFile> preProcessFunctionBeforeSerialize) {

    // Build SAFT-AuditFile
    AuditFile auditFile = new AuditFile();
    // ThreadInformation information = 
    // SaftThreadRegister.retrieveCurrentThreadInformation();

    // Build SAFT-HEADER (Chapter 1 in AuditFile)
    Header header = this.createSAFTHeader(fromDate, toDate, institution, ERP_HEADER_VERSION_1_00_00);
    // SetHeader/* ww w . ja  va2  s  . c  o  m*/
    auditFile.setHeader(header);

    // Build Master-Files
    oecd.standardauditfile_tax.pt_1.AuditFile.MasterFiles masterFiles = new oecd.standardauditfile_tax.pt_1.AuditFile.MasterFiles();

    // SetMasterFiles
    auditFile.setMasterFiles(masterFiles);

    // Build SAFT-MovementOfGoods (Customer and Products are built inside)
    // ProductsTable (Chapter 2.4 in AuditFile)
    List<oecd.standardauditfile_tax.pt_1.Product> productList = masterFiles.getProduct();
    Map<String, oecd.standardauditfile_tax.pt_1.Product> productMap = new HashMap<String, oecd.standardauditfile_tax.pt_1.Product>();
    Set<String> productCodes = new HashSet<String>();

    // ClientsTable (Chapter 2.2 in AuditFile)
    List<oecd.standardauditfile_tax.pt_1.Customer> customerList = masterFiles.getCustomer();
    Map<String, oecd.standardauditfile_tax.pt_1.Customer> customerMap = new HashMap<String, oecd.standardauditfile_tax.pt_1.Customer>();

    // Readd All  Clients if needed
    if (generateAllCustomers) {
        logger.info("Reading all Customers in Institution " + institution.getCode());

        Set<Customer> allCustomers = new HashSet<Customer>();
        for (DebtAccount debt : institution.getDebtAccountsSet()) {
            allCustomers.add(debt.getCustomer());
        }

        // Update the Total Objects Count
        // information.setTotalCounter(allCustomers.size() +
        // allProducts.size() + allDocuments.size() * 10);

        int i = 0;
        for (Customer customer : allCustomers) {
            oecd.standardauditfile_tax.pt_1.Customer saftCustomer = this
                    .convertCustomerToSAFTCustomer(customer);
            // information.setCurrentCounter(information.getCurrentCounter()
            // + 1);
            customerMap.put(saftCustomer.getCustomerID(), saftCustomer);
            i++;
            if (i % 100 == 0) {
                logger.info("Processing " + i + "/" + allCustomers.size() + " Customers in Institution "
                        + institution.getCode());
            }
        }
    }
    // Readd All Products if needed
    if (generateAllProducts) {

        logger.info("Reading all Customers in Institution " + institution.getCode());
        Set<Product> allProducts = institution.getAvailableProductsSet();
        int i = 0;
        for (Product product : allProducts) {
            if (!productCodes.contains(product.getCode())) {
                oecd.standardauditfile_tax.pt_1.Product saftProduct = this.convertProductToSAFTProduct(product);
                productCodes.add(product.getCode());
                productMap.put(saftProduct.getProductCode(), saftProduct);
            }

            i++;
            if (i % 100 == 0) {
                logger.info("Processing " + i + "/" + allProducts.size() + " Products in Institution "
                        + institution.getCode());
            }

            // information.setCurrentCounter(information.getCurrentCounter()
            // + 1);
        }
    } else {
        // information.setTotalCounter(allDocuments.size() * 10);
        // Update the Total Objects Count
        // information.setCurrentCounter(0);
    }

    // TaxTable (Chapter 2.5 in AuditFile)
    oecd.standardauditfile_tax.pt_1.TaxTable taxTable = new oecd.standardauditfile_tax.pt_1.TaxTable();
    masterFiles.setTaxTable(taxTable);

    for (Vat vat : institution.getVatsSet()) {
        taxTable.getTaxTableEntry().add(this.convertVATtoTaxTableEntry(vat, institution));
    }

    // Set MovementOfGoods in SourceDocuments(AuditFile)
    oecd.standardauditfile_tax.pt_1.SourceDocuments sourceDocuments = new oecd.standardauditfile_tax.pt_1.SourceDocuments();
    auditFile.setSourceDocuments(sourceDocuments);

    SourceDocuments.SalesInvoices invoices = new SourceDocuments.SalesInvoices();
    SourceDocuments.WorkingDocuments workingDocuments = new SourceDocuments.WorkingDocuments();
    Payments paymentsDocuments = new Payments();

    BigInteger numberOfPaymentsDocuments = BigInteger.ZERO;
    BigDecimal totalDebitOfPaymentsDocuments = BigDecimal.ZERO;
    BigDecimal totalCreditOfPaymentsDocuments = BigDecimal.ZERO;

    BigInteger numberOfWorkingDocuments = BigInteger.ZERO;
    BigDecimal totalDebitOfWorkingDocuments = BigDecimal.ZERO;
    BigDecimal totalCreditOfWorkingDocuments = BigDecimal.ZERO;

    invoices.setNumberOfEntries(BigInteger.ZERO);
    invoices.setTotalCredit(BigDecimal.ZERO);
    invoices.setTotalDebit(BigDecimal.ZERO);

    //        int i = 0;
    for (FinantialDocument document : allDocuments) {
        if ((document.isCreditNote() || document.isDebitNote())
                && (document.isClosed() || document.isAnnulled())) {
            try {
                WorkDocument workDocument = convertToSAFTWorkDocument((Invoice) document, customerMap,
                        productMap);
                workingDocuments.getWorkDocument().add(workDocument);

                // AcumulateValues
                numberOfWorkingDocuments = numberOfWorkingDocuments.add(BigInteger.ONE);
                if (!document.isAnnulled()) {
                    if (document.isDebitNote()) {
                        totalDebitOfWorkingDocuments = totalDebitOfWorkingDocuments
                                .add(workDocument.getDocumentTotals().getNetTotal());
                    } else if (document.isCreditNote()) {
                        totalCreditOfWorkingDocuments = totalCreditOfWorkingDocuments
                                .add(workDocument.getDocumentTotals().getNetTotal());
                    }
                }

                //                    i++;

            } catch (Exception ex) {
                logger.error("Error processing document " + document.getUiDocumentNumber() + ": "
                        + ex.getLocalizedMessage());
                throw ex;
            }
        } else {
            logger.info("Ignoring document " + document.getUiDocumentNumber() + " because is not closed yet.");
        }

    }
    // Update Totals of Workingdocuments
    workingDocuments.setNumberOfEntries(numberOfWorkingDocuments);
    workingDocuments.setTotalCredit(totalCreditOfWorkingDocuments.setScale(2, RoundingMode.HALF_EVEN));
    workingDocuments.setTotalDebit(totalDebitOfWorkingDocuments.setScale(2, RoundingMode.HALF_EVEN));

    sourceDocuments.setWorkingDocuments(workingDocuments);

    //PROCESSING PAYMENTS TABLE

    paymentsDocuments.setNumberOfEntries(BigInteger.ZERO);
    paymentsDocuments.setTotalCredit(BigDecimal.ZERO);
    paymentsDocuments.setTotalDebit(BigDecimal.ZERO);
    for (FinantialDocument document : allDocuments) {
        if (document.isSettlementNote() && (document.isClosed() || document.isAnnulled())) {
            try {
                Payment paymentDocument = convertToSAFTPaymentDocument((SettlementNote) document, customerMap,
                        productMap);
                paymentsDocuments.getPayment().add(paymentDocument);

                // AcumulateValues
                numberOfPaymentsDocuments = numberOfPaymentsDocuments.add(BigInteger.ONE);
                if (!document.isAnnulled()) {
                    totalCreditOfPaymentsDocuments = totalCreditOfPaymentsDocuments
                            .add(((SettlementNote) document).getTotalCreditAmount());
                    totalDebitOfPaymentsDocuments = totalDebitOfPaymentsDocuments
                            .add(((SettlementNote) document).getTotalDebitAmount());
                }
                //                    i++;
            } catch (Exception ex) {
                // persistenceSupport.flush();
                logger.error("Error processing document " + document.getUiDocumentNumber() + ": "
                        + ex.getLocalizedMessage());
                throw ex;
            }
        } else {
            logger.info("Ignoring document " + document.getUiDocumentNumber() + " because is not closed yet.");
        }

    }

    // Update Totals of Payment Documents
    paymentsDocuments.setNumberOfEntries(numberOfPaymentsDocuments);
    paymentsDocuments.setTotalCredit(totalCreditOfPaymentsDocuments.setScale(2, RoundingMode.HALF_EVEN));
    paymentsDocuments.setTotalDebit(totalDebitOfPaymentsDocuments.setScale(2, RoundingMode.HALF_EVEN));
    sourceDocuments.setPayments(paymentsDocuments);

    // Update the Customer Table in SAFT
    for (oecd.standardauditfile_tax.pt_1.Customer customer : customerMap.values()) {
        customerList.add(customer);
    }

    // Update the Product Table in SAFT
    for (oecd.standardauditfile_tax.pt_1.Product product : productMap.values()) {
        productList.add(product);
    }

    if (preProcessFunctionBeforeSerialize != null) {
        auditFile = preProcessFunctionBeforeSerialize.apply(auditFile);
    }
    String xml = exportAuditFileToXML(auditFile);

    logger.info("SAFT File export concluded with success.");
    return xml;
}

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   w w  w.  j  a v a2s  .  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  w w .j  ava2  s.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:service.actions.OrderSearch.java

private List<List<String>> getTestAdminOrderListData(Set<Long> rightBranchIds, OrderStatus status,
        List<OrderStatus> commonAvailebleStatusList, OrderSearchData searchData, User authUser, Integer start,
        Integer numberOfRecords, List<OrderStatus> rightStatusList, Boolean overdue) {

    Long starttime = System.currentTimeMillis();

    User currentUser = authManager.getCurrentUser();
    String currentDate = getCurrentDateToString();
    OrderCssManager ocm = new OrderCssManager(currentUser);
    ViewResolver vr = new ViewResolver(currentUser, branchRightsHolder);
    HashMap<Long, HashMap<String, Boolean>> br = branchRightsHolder.getBranchRights();
    HashMap<Rights, Boolean> cr = new HashMap();
    for (Rights r : Rights.values()) {
        cr.put(r, UserRightsUtil.isRight(r));
    }// www.ja  v  a 2s .  com
    List<Long> toWork = branchRightsHolder.getBranches(BranchRights.ORDER_NEW_TO_WORK);
    List<Long> toReject = branchRightsHolder.getBranches(BranchRights.ORDER_NEW_TO_REJECT);
    Authentication a = SecurityContextHolder.getContext().getAuthentication();

    SimpleDateFormat df = new SimpleDateFormat("dd/MM");
    DateFormatter fullDateFormatter = new DateFormatter();

    //LinkedHashMap<Long, HashMap> rawRes = new LinkedHashMap();
    List<List<String>> result = new ArrayList();

    List<Object[]> preRes = orderDao.getTestOrdersAndCountsForAdminBySql(rightBranchIds, status, searchData,
            authUser.getUserId(), start, numberOfRecords, rightStatusList, overdue);

    Set<Long> orderIds = new HashSet();
    for (Object[] rawOrder : preRes) {
        Long orderId = getLong(rawOrder[0]);
        orderIds.add(orderId);
    }

    HashMap<Long, List<HashMap>> otherOrders = new HashMap();
    HashMap<Long, List<HashMap>> orderDirections = new HashMap();
    HashMap<Long, List<HashMap>> orderSalaries = new HashMap();

    //log.warn("searchLogicTime1:" + Long.valueOf(System.currentTimeMillis() - starttime));

    List<Object[]> otherOrdersRawRes = orderDao.getTestOtherOrdersForAdminBySql(orderIds);
    //log.warn("searchLogicTime2:" + Long.valueOf(System.currentTimeMillis() - starttime));
    for (Object[] rawOtherOrder : otherOrdersRawRes) {
        Long orderId = getLong(rawOtherOrder[0]);

        List<HashMap> otherOrdersList = otherOrders.get(orderId);
        if (otherOrdersList == null) {
            otherOrdersList = new ArrayList();
        }
        if (otherOrdersList.size() < 5) {
            HashMap<String, Object> otherOrderData = new HashMap();

            Long otherOrderId = getLong(rawOtherOrder[1]);
            Long otherOrderBranchId = getLong(rawOtherOrder[2]);
            String otherOrderOldId = (String) rawOtherOrder[3];
            String otherOrderNumber = otherOrderOldId;
            if (otherOrderOldId == null || otherOrderOldId.equals("")) {
                otherOrderNumber = otherOrderId.toString();
            }

            otherOrderData.put("orderId", otherOrderId);
            otherOrderData.put("branchId", otherOrderBranchId);
            otherOrderData.put("number", otherOrderNumber);
            otherOrdersList.add(otherOrderData);
            otherOrders.put(orderId, otherOrdersList);
        }
    }

    List<Object[]> orderDirectionRawRes = orderDao.getTestDirectionsForAdminBySql(orderIds);
    for (Object[] rawDirectionData : orderDirectionRawRes) {
        Long orderId = getLong(rawDirectionData[0]);

        List<HashMap> directionsList = orderDirections.get(orderId);
        if (directionsList == null) {
            directionsList = new ArrayList();
        }
        HashMap<String, Object> directionData = new HashMap();

        Long directionId = getLong(rawDirectionData[1]);
        String directionName = (String) rawDirectionData[2];

        directionData.put("directionId", directionId);
        directionData.put("directionName", directionName);
        directionsList.add(directionData);
        orderDirections.put(orderId, directionsList);
    }

    List<Object[]> authorSalariesRawRes = orderDao.getTestSalariesForAdminBySql(orderIds);
    for (Object[] rawSalaryData : authorSalariesRawRes) {
        Long orderId = getLong(rawSalaryData[0]);

        List<HashMap> salaryList = orderSalaries.get(orderId);
        if (salaryList == null) {
            salaryList = new ArrayList();
        }
        HashMap<String, Object> salaryData = new HashMap();

        Double authorSalaryCost = (Double) rawSalaryData[1];
        Long authorSalaryId = getLong(rawSalaryData[2]);

        salaryData.put("salaryId", authorSalaryId);
        salaryData.put("cost", authorSalaryCost);
        salaryList.add(salaryData);
        orderSalaries.put(orderId, salaryList);
    }
    //log.warn("rawRes= "+rawRes.size());

    /*for (Map.Entry<Long, HashMap> order : rawRes.entrySet()) {
     Long orderId = order.getKey();
     HashMap orderData = order.getValue();
     List<HashMap> otherOrdersData = otherOrders.get(orderId);
     List<HashMap> directionsData = orderDirections.get(orderId);
     List<HashMap> SalaryData = orderSalaries.get(orderId);
     if (otherOrdersData == null) {
     otherOrdersData = new ArrayList();
     }
     if (directionsData == null) {
     directionsData = new ArrayList();
     }
     if (SalaryData == null) {
     SalaryData = new ArrayList();
     }
     orderData.put("otherOrders", otherOrdersData);
     orderData.put("directions", directionsData);
     orderData.put("authorSalaries", SalaryData);
            
     result.add(orderData);
     }*/
    for (Object[] rawOrder : preRes) {
        List<String> orderData = new ArrayList();
        Long orderId = getLong(rawOrder[0]);

        Date deadlineDate = (Date) rawOrder[1];
        Date realDate = (Date) rawOrder[2];
        String clientFio = (String) rawOrder[3];
        String clientPhone = (String) rawOrder[4];
        String clientEmail = (String) rawOrder[5];
        String city = (String) rawOrder[6];
        Double cost = (Double) rawOrder[7];
        Double authorSalary = (Double) rawOrder[8];
        Boolean firstFlag = (Boolean) rawOrder[9];
        Boolean secondFlag = (Boolean) rawOrder[10];
        String statusStr = (String) rawOrder[11];
        OrderStatus orderStatus = OrderStatus.valueOf(statusStr);
        Long branchId = getLong(rawOrder[12]);
        Long orderTypeId = getLong(rawOrder[13]);
        Long authorId = getLong(rawOrder[14]);
        String comment = (String) rawOrder[15];
        String authorComment = (String) rawOrder[16];
        Date readyDate = (Date) rawOrder[17];
        String commentToAuthorSalary = (String) rawOrder[18];
        Boolean unloadedInShop = (Boolean) rawOrder[19];
        Long parentOrderId = getLong(rawOrder[20]);
        Boolean selected = (Boolean) rawOrder[21];
        Boolean childSelected = (Boolean) rawOrder[22];
        Boolean statusOfUser = (Boolean) rawOrder[23];
        /*log.warn("");
         log.warn("oid:"+orderId);
         log.warn("statusOfUser:"+statusOfUser);*/

        String oldId = (String) rawOrder[24];
        String number = oldId;
        if (oldId == null || oldId.equals("")) {
            number = orderId.toString();
        }

        String subject = (String) rawOrder[25];
        Date orderDate = (Date) rawOrder[26];
        String branchName = (String) rawOrder[27];
        String abbrevation = (String) rawOrder[28];
        String orderTypeName = (String) rawOrder[29];
        String authorLogin = (String) rawOrder[30];
        String authorName = (String) rawOrder[31];
        String authorSurname = (String) rawOrder[32];

        Boolean existReject = false;

        BigInteger bi = (BigInteger) rawOrder[33];
        Integer countMess = (bi != null ? bi.intValue() : null);

        Double paymentSum = (Double) rawOrder[34];
        paymentSum = (paymentSum != null ? paymentSum : 0D);

        BigInteger countAllAuthorMess = (BigInteger) rawOrder[35];
        BigInteger countAllAdminMess = (BigInteger) rawOrder[36];
        BigInteger countNotReadyAdminMess = (BigInteger) rawOrder[37];
        BigInteger countAllDelegateMess = (BigInteger) rawOrder[38];
        BigInteger countNotReadyDelegateMess = (BigInteger) rawOrder[39];

        BigInteger countNotReadyAuthorMessages = new BigInteger("0");
        if (countMess != null) {
            countNotReadyAuthorMessages = bi;
        }
        if (countNotReadyDelegateMess != null) {
            countNotReadyAuthorMessages = countNotReadyAuthorMessages.add(countNotReadyDelegateMess);
        }

        List<OrderStatus> availableStatusList = new ArrayList(commonAvailebleStatusList);
        if (statusStr.equals(OrderStatus.NEW.name())) {
            if (!toWork.contains(branchId)) {
                availableStatusList.remove(OrderStatus.WORKING);
            }
            if (!toReject.contains(branchId)) {
                availableStatusList.remove(OrderStatus.REJECTION);
            }
        }

        List<HashMap> otherOrdersData = otherOrders.get(orderId);
        List<HashMap> directionsData = orderDirections.get(orderId);
        List<HashMap> SalaryData = orderSalaries.get(orderId);
        if (otherOrdersData == null) {
            otherOrdersData = new ArrayList();
        }
        if (directionsData == null) {
            directionsData = new ArrayList();
        }
        if (SalaryData == null) {
            SalaryData = new ArrayList();
        }

        HashMap<String, Boolean> branchRights = br.get(branchId);
        boolean rightChangeOrder = false;
        if ((childSelected == null || !childSelected) && branchRights.get("CHANGE_ORDER")
                && webPrivs.isAllowed("/Order/change", a)) {
            rightChangeOrder = true;
        }

        String rowClass = ocm.getRowClass(selected, authorId, cost, statusOfUser, orderStatus, SalaryData,
                null);

        orderData.add("<tr class=" + rowClass + ">");

        /*log.warn("sou:"+statusOfUser+";");
         log.warn("cost:"+StringAdapter.getString(cost)+";");
         if(cost!=null){
         log.warn("costcomp:"+(cost>0D)+";");
         }*/
        String col = "";
        if (cr.get(Rights.TABLE_FLAGS)) {
            col = "<td><a class='info red " + (firstFlag != null && firstFlag ? "active" : "")
                    + "' data-orderId=" + orderId + " onclick='return changeFirstFlag(this);'></a>";
            col += "<br/>";
            col += "<a class='info blue " + (secondFlag != null && secondFlag ? "active" : "")
                    + "' data-orderId=" + orderId + " onclick='return changeSecondFlag(this);'></a></td>";
            orderData.add(col);
        }

        if (cr.get(Rights.TABLE_NUMBER)) {
            if (branchRights.get("GET_ORDER") && webPrivs.isAllowed("/Order/get", a)) {
                col = "<td><a href='#' class='orderShow flat' data-id=" + orderId + " data-number=" + number
                        + ">";
                col += "<p class='order-num'><span class='orderCount'>" + abbrevation + "</span>" + number
                        + "</p></a></td>";
            } else {
                col = "<td>" + StringAdapter.getString(number) + "</td>";
            }
            orderData.add(col);
        }

        if (cr.get(Rights.TABLE_DIRECTIONS)) {
            col = "<td class='directionsTd' data-orderId=" + orderId + ">";
            if (branchRights.get("ORDER_CHANGE_DIRECTIONS") && (childSelected == null || !childSelected)) {
                col += "<div class='directionDiv add-order-select' data-orderId=" + orderId + ">";
                for (HashMap dir : directionsData) {
                    col += "<select class='directionSelect' data-orderId=" + orderId + " data-value="
                            + dir.get("directionId") + ">";
                    col += "<option value=''></option>";
                    for (Direction d : directionService.getAll()) {
                        col += "<option value=" + d.getDirectionId() + " "
                                + (d.getDirectionId().equals(dir.get("directionId")) ? "selected" : "") + ">"
                                + d.getName() + "</option>";
                    }
                    col += "</select></br>";
                }
                col += "</div>";
                col += "<a class='add-direction addDirectionSubmit info add active' data-orderId=" + orderId
                        + ">+</a>";
            } else {
                for (HashMap d : directionsData) {
                    col += d.get("directionName");
                }
            }
            col += "</td>";
            orderData.add(col);
        }

        if (cr.get(Rights.TABLE_TYPE)) {
            col = "<td><div class='changeDiv dbl-area-select' data-orderId=" + orderId
                    + " data-parameterName='orderType' data-isRight=" + rightChangeOrder + ">";
            col += "<div class='text'>" + orderTypeName + "</div>";
            col += "<select>";
            for (OrderType ot : orderTypeService.getAll()) {
                col += "<option value=" + ot.getOrderTypeId() + " "
                        + (ot.getOrderTypeId().equals(orderTypeId) ? "selected" : "") + ">" + ot.getName()
                        + "</option>";
            }
            col += "</select></div></td>";
            orderData.add(col);
        }

        if (cr.get(Rights.TABLE_SUBJECT)) {
            col = "<td><div class='changeDiv dbl-area-auto' data-orderId=" + orderId
                    + " data-parameterName='subject' data-isRight=" + rightChangeOrder + ">";
            col += "<div class='text'>" + subject + "</div>";
            col += "<textarea>" + subject + "</textarea></div></td>";
            orderData.add(col);
        }

        if (cr.get(Rights.TABLE_DATE)) {
            col = "<td><div data-fromTable='true' class='changeDiv dbl-area' data-orderId=" + orderId
                    + " data-parameterName='deadlineDate' style='width: inherit;' data-isRight="
                    + rightChangeOrder + ">";
            col += "<div style='font-size: 0.8em;'>" + (deadlineDate != null ? df.format(deadlineDate) : "")
                    + "</div>";
            col += "<input type='text' class='date' value="
                    + (deadlineDate != null ? fullDateFormatter.date(deadlineDate) : "") + "></div>";
            col += "<div data-fromTable='true' class='changeDiv dbl-area' data-orderId=" + orderId
                    + " data-parameterName='realDate' style='width: inherit;' data-isRight=" + rightChangeOrder
                    + ">";
            col += "<div style='font-size: 0.8em;'>" + (realDate != null ? df.format(realDate) : "") + "</div>";
            col += "<input type='text' class='date' value="
                    + (realDate != null ? fullDateFormatter.date(realDate) : "") + "></div></td>";
            orderData.add(col);
        }

        if (cr.get(Rights.TABLE_CLIENT)) {
            col = "<td>";
            if (parentOrderId == null) {
                col += "<div class='changeDiv dbl-area-auto' data-orderId=" + orderId
                        + " data-parameterName='clientFio' data-isRight=" + rightChangeOrder + ">";
                col += "<div class='text'>" + clientFio + "</div>";
                col += "<input type='text' value='" + clientFio + "'></div>";
                if (branchRights.get("ORDER_SHOW_CLIENT_EMAIL") != null) {
                    col += "<div class='changeDiv dbl-area-auto' data-orderId=" + orderId
                            + " data-parameterName='clientEmail' data-isRight=" + rightChangeOrder + ">";
                    col += "<div class='text'>" + clientEmail + "</div>";
                    col += "<input type='text' value=" + clientEmail + "></div>";
                }
                if (branchRights.get("ORDER_SHOW_CLIENT_PHONE") != null) {
                    col += "<div class='changeDiv dbl-area-auto' data-orderId=" + orderId
                            + " data-parameterName='clientPhone' data-isRight=" + rightChangeOrder + ">";
                    col += "<div class='text'>" + clientPhone + "</div>";
                    col += "<input type='text' value=" + clientPhone + "></div>";
                }
                if (vr.showButtonsDivInTable(branchId, clientEmail, clientPhone)) {
                    col += "<div class='icon-contacts' style='width: 80px;'>";
                    if (vr.showSendEmailButtomInTable(branchId, clientEmail)
                            && webPrivs.isAllowed("/Notice/addEmailByClient", a)) {
                        col += "<a href='' class='mail orderEmailLink' ";
                        if (webPrivs.isAllowed("/Order/showClientEmailTitle", a)
                                && branchRights.get("ORDER_SHOW_CLIENT_EMAIL_TITLE") != null) {
                            col += " data=" + clientEmail + " title=" + clientEmail + " ";
                        }
                        col += " onclick='createWindowEmailNotice('/Notice/addEmailByClient?orderId=" + orderId
                                + "'); return false;' > </a>";
                    }
                    if (vr.showSendSmsButtomInTable(branchId, clientPhone)
                            && webPrivs.isAllowed("/Notice/addSmsByClient", a)) {
                        col += "<a href='' class='sms orderSmsLink' ";
                        if (webPrivs.isAllowed("/Order/showClientPhoneTitle", a)
                                && branchRights.get("ORDER_SHOW_CLIENT_PHONE_TITLE") != null) {
                            col += " data=" + clientPhone + " title=" + clientPhone + " ";
                        }
                        col += " onclick='createFloatWindow('/Notice/addSmsByClient?orderId=" + orderId
                                + "'); return false;' > </a>";
                    }
                }
                col += "<div class='clearfix'></div>";
                if (!otherOrdersData.isEmpty()) {
                    col += "<div class='other-order'>";
                    col += "<a class='other-title' onclick='$(this).next().toggle()'> </a>";
                    col += "<ul style='display: none;' > ";
                    for (HashMap od : otherOrdersData) {
                        if (webPrivs.isAllowed("/Order/get", a)
                                && br.get((Long) od.get("branchId")).get("GET_ORDER") != null) {
                            col += "<li><a href='#' class='orderShow' data-url='/Order/get?orderId="
                                    + od.get("orderId") + "&ajax=1' data-id=" + od.get("orderId")
                                    + " data-number=" + od.get("number") + " > #" + od.get("number")
                                    + "</a></li>";
                        }
                    }
                    col += "</ul>";
                }
            } else {
                col += "";
            }
            col += "</td>";
            orderData.add(col);
        }

        if (cr.get(Rights.TABLE_PRICE)) {
            if (webPrivs.isAllowed("/Order/changeCost", a) && branchRights.get("ORDER_CHANGE_COST") != null) {
                col = "<td id='updatableCostTd" + orderId
                        + "' class='updatableTd dbl-area' data-type='cost' data-orderId=" + orderId + ">"
                        + (cost != null ? cost : "") + "</td>";
            } else {
                if (webPrivs.isAllowed("/Order/showCost", a) && branchRights.get("ORDER_SHOW_COST") != null) {
                    col = "<td><div class='dbl-area'>" + (cost != null ? cost : "") + "</div></td>";
                }
            }
            orderData.add(col);
        }

        String userString = authUser.getSurname() + " " + authUser.getName();
        if (cr.get(Rights.TABLE_PREPAYMENT)) {
            col = "<td>";
            if (webPrivs.isAllowed("/Payment/search", a) && branchRights.get("PAYMENT_SEARCH") != null) {
                col += "<div class='advance-payment modal-window'>";
                col += "<form id='paymentObj' onsubmit='return false;' data-orderid=" + orderId
                        + " class='add-payment-form' action='" + SystemVariables.BASE_URL
                        + "/Payment/add?ajax=true' method='post' enctype='multipart/form-data'>";
                col += "<div class='value'><span>" + paymentSum + "</span>";
                col += "<div class='modal-content'><table><tr><td class='title'>?</td><td>"
                        + userString + "</td></tr>";
                col += "<tr><td class='title'></td><td>" + (currentDate != null ? currentDate : "")
                        + "</td></tr>";
                col += "<tr><td class='title'></td><td><input id='amount' name='amount' type='text' value='' autocomplete='off'></td></tr>";
                col += "<tr><td class='title'>C?<br/></td><td><select id='paymentType' name='paymentType'>";
                for (PaymentType pt : paymentTypeService.getActive()) {
                    col += "<option value=" + pt.getId() + ">" + pt.getName() + "</option>";
                }
                col += "</select></td></tr>";
                col += "<tr><td colspan='2'><div class='uploadify-button' data-id=" + orderId
                        + " data-num='0' style='width: 50%;'> </div><input name='file' type='file' class='hidden ajaxUpload' id='fileInput"
                        + orderId + "' data-id=" + orderId + " data-num='0'></td></tr>";
                col += "</table><br/><input type='hidden' name='orderId' value=" + orderId + " />";
                col += "<input type='submit' class='modal-close' value=''></div></div></form></div>";
            }
            col += "</td>";
            orderData.add(col);
        }

        if (cr.get(Rights.TABLE_AUTHOR_SALARY)) {
            if (webPrivs.isAllowed("/Order/changeAuthorSalary", a)
                    && branchRights.get("ORDER_CHANGE_AUTHOR_SALARY") != null) {
                col = "<td class='author-salary dbl-area' data-orderId=" + orderId + ">";
                col += "<div class='value-area "
                        + (commentToAuthorSalary != null && !commentToAuthorSalary.equals("") ? "warning" : "")
                        + "'>" + (authorSalary != null ? authorSalary : "") + "</div>";
                col += "<div class='input-area' style='display: none;' >";
                col += "<input class='author-salary-input' type='text' name='authorSalary' value="
                        + (authorSalary != null ? authorSalary : "") + ">";
                col += "<textarea class='comment-salary-input' >"
                        + (commentToAuthorSalary != null ? commentToAuthorSalary : "")
                        + "</textarea></div></td>";
            } else {
                col = "<td>" + (authorSalary != null ? authorSalary : "") + "</td>";
            }
            orderData.add(col);
        }

        if (cr.get(Rights.TABLE_STATUS)) {
            col = "<td class=" + ocm.getStatusClass(statusStr, cost, paymentSum)
                    + "><div class='dbl-area-select color' >";
            if (webPrivs.isAllowed("/Order/changeStatus", a)
                    && webPrivs.isAllowed("/Order/changeStatusFromTable", a)
                    && branchRights.get("ORDER_CHANGE_STATUS") != null
                    && branchRights.get("ORDER_CHANGE_STATUS_FROM_TABLE") != null) {
                col += "<div class='status-in-table text order-status' id='statusDiv" + orderId + "' >"
                        + vr.getStatusName(orderStatus, existReject, cost, statusOfUser) + "</div>";
                col += "<select id='statuSelect" + orderId + "' data-orderId=" + orderId
                        + " class='statusSelect' name='status'>";
                for (OrderStatus os : availableStatusList) {
                    col += "<option value=" + os.toString() + " " + (os.equals(orderStatus) ? "selected" : "")
                            + " >" + os.getName() + "</option>";
                }
                col += "</select>";
            } else {
                col += "<div class='text'>" + vr.getStatusName(orderStatus, existReject, cost, statusOfUser)
                        + "</div>";
            }
            col += "</div></td>";
            orderData.add(col);
        }

        if (cr.get(Rights.TABLE_AUTHOR)) {
            col = "<td>";
            if (vr.allowShowAuthor()) {
                col += vr.getAuthorParams(authorId, authorSurname, authorName, authorLogin, branchId, "<br/>");
            }
            col += "</td>";
            orderData.add(col);
        }

        if (cr.get(Rights.TABLE_AUTHOR_MESSAGE)) {
            col = "<td>";
            if (!countNotReadyAuthorMessages.equals(BigInteger.valueOf(0L))) {
                col += "<p class='circle'>" + countNotReadyAuthorMessages + "</p>";
            } else {
                col += "(" + countAllAuthorMess + ")";
            }
            col += "<br/>";
            if (orderStatus != null && orderStatus.equals(OrderStatus.NEW)) {
                for (HashMap sal : SalaryData) {
                    col += "<br/> " + sal.get("cost");
                }
            }
            col += "</td>";
            orderData.add(col);
        }

        if (cr.get(Rights.TABLE_ADMIN_MESSAGE)) {
            col = "<td>";
            if (!countNotReadyAdminMess.equals(BigInteger.valueOf(0L))) {
                col += "<p class='circle'>" + countNotReadyAdminMess + "</p>";
            } else {
                col += "(" + countAllAdminMess + ")";
            }
            if (unloadedInShop != null && unloadedInShop) {
                col += "<br/><span class='info check'></span>";
            }
            col += "</td>";
            orderData.add(col);
        }

        orderData.add("</tr>");

        result.add(orderData);
    }

    //log.warn("searchLogicTime:" + Long.valueOf(System.currentTimeMillis() - starttime));

    return result;
}

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

/**
 * Helper function to create a new node.
 *
 * @param con             an open and valid connection
 * @param seq             reference to a sequencer
 * @param ce              reference to the content engine
 * @param mode            Live or Edit mode
 * @param parentNodeId    the parent node (1=root)
 * @param name            the name of the new node (only informative value)
 * @param label           label for Caption property (only used if new reference is created)
 * @param position        the position within the childs (0 based, Integer.MAX_VALUE may be used to
 *                        append to the end)
 * @param reference       a reference to an existing content (must exist!)
 * @param data            the optional data
 * @param nodeId          the id to use or create a new one if < 0
 * @param activateContent change the step of contents that have no live step to live in the max version?
 * @return the used or created node id//from   w w  w .  ja  v  a2  s. c o m
 * @throws FxTreeException if the function fails
 */
private long _createNode(Connection con, SequencerEngine seq, ContentEngine ce, FxTreeMode mode,
        long parentNodeId, String name, FxString label, int position, FxPK reference, String data, long nodeId,
        boolean activateContent) throws FxApplicationException {

    // acquire exclusive lock for parent node
    acquireLocksForUpdate(con, mode, Arrays.asList(parentNodeId));

    //        makeSpace(con, seq/*irrelevant*/, mode, parentNodeId, position/*irrelevant*/, 1);
    FxTreeNodeInfoSpreaded parentNode = (FxTreeNodeInfoSpreaded) getTreeNodeInfo(con, mode, parentNodeId);
    BigInteger boundaries[] = getBoundaries(con, parentNode, position);
    BigInteger leftBoundary = boundaries[0]; //== left border
    BigInteger rightBoundary = boundaries[1]; //== right border

    // Node has to be inserted between the left and right boundary and needs 2 slots for its left and right border
    BigInteger spacing = rightBoundary.subtract(leftBoundary).subtract(TWO);
    // Compute spacing for left,inner and right part
    spacing = spacing.divide(THREE);

    // We need at least 2 open slots (for the left and right boundary of the new node)
    //if the spacing is <= 0 we need more space
    if (spacing.compareTo(BigInteger.ZERO) <= 0/*less than*/) {
        throw new FxTreeException("ex.tree.create.noSpace", parentNodeId);
    }

    // try to use space more efficiently for flat structures, otherwise the first node of a folder
    // will get a third of the subtree space, the second one ninth, and so on.
    // Maxspacing indicates the number of nodes (*2) we expect to put in this node before space reorg
    spacing = spacing.compareTo(DEFAULT_NODE_SPACING) > 0 ? DEFAULT_NODE_SPACING : spacing;

    //        final BigInteger left = leftBoundary.add(spacing).add(BigInteger.ONE);
    // don't add gap to left boundary (doesn't seem to have any benefits since that space is lost
    // unless the tree is reorganized anyway
    final BigInteger left = leftBoundary.add(BigInteger.ONE);
    final BigInteger right = left.add(spacing).add(BigInteger.ONE);

    NodeCreateInfo nci = getNodeCreateInfo(mode, seq, ce, nodeId, name, label, reference, activateContent);

    // Create the node
    PreparedStatement ps = null;
    try {
        ps = con.prepareStatement("INSERT INTO " + getTable(mode) + " (ID,PARENT,DEPTH,DIRTY,REF,LFT,RGT,"
                + "CHILDCOUNT,NAME,MODIFIED_AT,TEMPLATE) VALUES " + "(" + nci.id + "," + parentNodeId + ","
                + (parentNode.getDepth() + 1) + ",?," + nci.reference.getId() + ",?,?,0,?,"
                + StorageManager.getTimestampFunction() + ",?)");
        ps.setBoolean(1, mode != FxTreeMode.Live);
        setNodeBounds(ps, 2, left);
        setNodeBounds(ps, 3, right);
        ps.setString(4, FxFormatUtils.escapeTreePath(nci.name));
        if (StringUtils.isEmpty(data)) {
            ps.setNull(5, java.sql.Types.VARCHAR);
        } else {
            ps.setString(6, data);
        }
        ps.executeUpdate();
        ps.close();

        //update the parents childcount
        ps = con.prepareStatement(
                "UPDATE " + getTable(mode) + " SET CHILDCOUNT=CHILDCOUNT+1 WHERE ID=" + parentNodeId);
        ps.executeUpdate();
    } catch (SQLException e) {
        throw new FxTreeException(LOG, e, "ex.db.sqlError", e.getMessage());
    } finally {
        try {
            if (ps != null)
                ps.close();
        } catch (Throwable t) {
            /*ignore*/
        }
    }
    return nci.id;
}

From source file:org.fenixedu.treasury.services.integration.erp.ERPExporter.java

private Payment convertToSAFTPaymentDocument(SettlementNote document,
        Map<String, oecd.standardauditfile_tax.pt_1.Customer> baseCustomers,
        Map<String, oecd.standardauditfile_tax.pt_1.Product> productMap) {
    Payment payment = new Payment();

    // Find the Customer in BaseCustomers
    oecd.standardauditfile_tax.pt_1.Customer customer = null;

    if (baseCustomers.containsKey(document.getDebtAccount().getCustomer().getCode())) {
        customer = baseCustomers.get(document.getDebtAccount().getCustomer().getCode());
    } else {//from w w w  . j a  va  2s . c  om
        // If not found, create a new one and add it to baseCustomers
        customer = convertCustomerToSAFTCustomer(document.getDebtAccount().getCustomer());
        baseCustomers.put(customer.getCustomerID(), customer);
    }

    // MovementDate
    DatatypeFactory dataTypeFactory;
    try {
        dataTypeFactory = DatatypeFactory.newInstance();
        DateTime documentDate = document.getDocumentDate();

        // SystemEntryDate
        payment.setSystemEntryDate(convertToXMLDateTime(dataTypeFactory, documentDate));

        payment.setTransactionDate(convertToXMLDateTime(dataTypeFactory, documentDate));

        // DocumentNumber
        payment.setPaymentRefNo(document.getUiDocumentNumber());

        // CustomerID
        payment.setCustomerID(document.getDebtAccount().getCustomer().getCode());

        // DocumentStatus
        /*
         * Deve ser preenchido com: ?N? ? Normal; Texto 1 ?T? ? Por conta de
         * terceiros; ?A? ? Documento anulado.
         */
        SourceDocuments.Payments.Payment.DocumentStatus status = new SourceDocuments.Payments.Payment.DocumentStatus();
        if (document.isAnnulled()) {
            status.setPaymentStatus("A");
        } else {
            status.setPaymentStatus("N");
        }
        status.setPaymentStatusDate(payment.getSystemEntryDate());
        // status.setReason("");
        // Utilizador responsvel pelo estado atual do docu-mento.
        status.setSourceID(document.getVersioningUpdatedBy());
        // Deve ser preenchido com:
        // 'P' - Documento produzido na aplicacao;
        if (Boolean.TRUE.equals(document.getDocumentNumberSeries().getSeries().getExternSeries())
                || Boolean.TRUE.equals(document.getDocumentNumberSeries().getSeries().getLegacy())) {
            status.setSourcePayment(SAFTPTSourcePayment.I);
        } else {
            status.setSourcePayment(SAFTPTSourcePayment.P);
        }

        payment.setDocumentStatus(status);

        //Check if is Rehimbursement/Payment
        if (Constants.isPositive(document.getTotalPayedAmount())) {
            //PaymentMethods
            for (PaymentEntry paymentEntry : document.getPaymentEntriesSet()) {
                PaymentMethod method = new PaymentMethod();
                method.setPaymentAmount(paymentEntry.getPayedAmount().setScale(2, RoundingMode.HALF_EVEN));
                method.setPaymentDate(payment.getTransactionDate());
                method.setPaymentMechanism(convertToSAFTPaymentMechanism(paymentEntry.getPaymentMethod()));
                payment.getPaymentMethod().add(method);
            }
            payment.setSettlementType(SAFTPTSettlementType.NL);
        } else if (Constants.isPositive(document.getTotalReimbursementAmount())) {
            //Reimbursments
            for (ReimbursementEntry reimbursmentEntry : document.getReimbursementEntriesSet()) {
                PaymentMethod method = new PaymentMethod();
                method.setPaymentAmount(
                        reimbursmentEntry.getReimbursedAmount().setScale(2, RoundingMode.HALF_EVEN));
                method.setPaymentDate(payment.getTransactionDate());
                method.setPaymentMechanism(convertToSAFTPaymentMechanism(reimbursmentEntry.getPaymentMethod()));
                payment.getPaymentMethod().add(method);
                payment.setSettlementType(SAFTPTSettlementType.NR);
            }
        } else {
            payment.setSettlementType(SAFTPTSettlementType.NN);
        }

        payment.setSourceID(document.getVersioningCreator());

        // DocumentTotals
        SourceDocuments.Payments.Payment.DocumentTotals docTotals = new SourceDocuments.Payments.Payment.DocumentTotals();

        //Lines
        BigInteger i = BigInteger.ONE;
        for (SettlementEntry settlementEntry : document.getSettlemetEntriesSet()) {
            SourceDocuments.Payments.Payment.Line line = new SourceDocuments.Payments.Payment.Line();
            line.setLineNumber(i);
            //SourceDocument
            SourceDocumentID sourceDocument = new SourceDocumentID();
            sourceDocument.setLineNumber(BigInteger.valueOf(settlementEntry.getInvoiceEntry().getEntryOrder()));
            sourceDocument.setOriginatingON(
                    settlementEntry.getInvoiceEntry().getFinantialDocument().getUiDocumentNumber());
            sourceDocument.setInvoiceDate(convertToXMLDateTime(dataTypeFactory,
                    settlementEntry.getInvoiceEntry().getFinantialDocument().getDocumentDate()));
            sourceDocument.setDescription(settlementEntry.getDescription());
            line.getSourceDocumentID().add(sourceDocument);
            //SettlementAmount
            line.setSettlementAmount(BigDecimal.ZERO);
            if (settlementEntry.getInvoiceEntry().isDebitNoteEntry()) {
                line.setDebitAmount(settlementEntry.getTotalAmount());
            } else if (settlementEntry.getInvoiceEntry().isCreditNoteEntry()) {
                line.setCreditAmount(settlementEntry.getTotalAmount());
            }
            payment.getLine().add(line);
            i = i.add(BigInteger.ONE);
        }
        docTotals.setGrossTotal(document.getTotalAmount().setScale(2, RoundingMode.HALF_EVEN));
        docTotals.setNetTotal(document.getTotalAmount().setScale(2, RoundingMode.HALF_EVEN));
        docTotals.setTaxPayable(BigDecimal.ZERO.setScale(2, RoundingMode.HALF_EVEN));
        payment.setDocumentTotals(docTotals);

        // Period
        /*
         * Per?odo contabil?stico (Period) . . . . . . . . . . Deve ser
         * indicado o n?mero do m?s do per?odo de tributa??o, de ?1? a ?12?,
         * contado desde a data do in?cio. Pode ainda ser preenchido com
         * ?13?, ?14?, ?15? ou ?16? para movimentos efectuados no ?ltimo m?s
         * do per?odo de tributa??o, relacionados com o apuramento do
         * resultado. Ex.: movimentos de apuramentos de invent?rios,
         * deprecia??es, ajustamentos ou apuramentos de resultados.
         */
        payment.setPeriod(document.getDocumentDate().getMonthOfYear());

        // SourceID
        /*
         * C?digo do utilizador que registou o movimento (SourceID).
         */
        payment.setSourceID(document.getVersioningCreator());

    } catch (DatatypeConfigurationException e) {

        e.printStackTrace();
    }

    return payment;
}

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;
        }/*  w  w w  .j  ava 2s . com*/

        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: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  a va2  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;
}