Example usage for java.math BigInteger longValue

List of usage examples for java.math BigInteger longValue

Introduction

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

Prototype

public long longValue() 

Source Link

Document

Converts this BigInteger to a long .

Usage

From source file:org.plasma.sdo.helper.DataConverter.java

public Object fromInteger(Type targetType, BigInteger value) {
    DataType targetDataType = DataType.valueOf(targetType.getName());
    switch (targetDataType) {
    case Integer:
        return value;
    case Double:
        return new Double(value.doubleValue());
    case Float:
        return new Float(value.floatValue());
    case Int://w  w  w . ja va  2s. c  o m
        return new Integer(value.intValue());
    case Long:
        return new Long(value.longValue());
    case Decimal:
        return new BigDecimal(value.doubleValue());
    case Bytes:
        return value.toByteArray();
    case String:
        //as per spec: ('+'|'-')? [0-9]+
        return value.toString();
    default:
        throw new InvalidDataConversionException(targetDataType, DataType.Integer, value);
    }
}

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

/**
 * Create a JSONRPCBalance object for Bitcoin asset
 * @param w/*from  www. j  av a 2s .  co m*/
 * @param rawBalanceSatoshi   In BitcoinJ terms, this is the estimated total balance
 * @param rawSpendableSatoshi       In BitcoinJ terms, this is the available amount to spend
 *                                  If null, will set amount instead of total and spendable.
 * @return 
 */
private JSONRPCBalance createBitcoinBalance(Wallet w, BigInteger rawBalanceSatoshi,
        BigInteger rawSpendableSatoshi) {
    JSONRPCBalance balance = new JSONRPCBalance();
    balance.setAsset_ref("bitcoin");

    BigDecimal rawBalanceBTC = new BigDecimal(rawBalanceSatoshi).divide(new BigDecimal(Utils.COIN));
    String rawBalanceDisplay = Utils.bitcoinValueToFriendlyString(rawBalanceSatoshi) + " BTC";
    JSONRPCBalanceAmount bitcoinBalanceAmount = new JSONRPCBalanceAmount(rawBalanceSatoshi.longValue(),
            rawBalanceBTC.doubleValue(), rawBalanceDisplay);

    if (rawSpendableSatoshi != null) {
        BigDecimal rawSpendableBTC = new BigDecimal(rawSpendableSatoshi).divide(new BigDecimal(Utils.COIN));
        String rawSpendableDisplay = Utils.bitcoinValueToFriendlyString(rawSpendableSatoshi) + " BTC";
        JSONRPCBalanceAmount bitcoinSpendableAmount = new JSONRPCBalanceAmount(rawSpendableSatoshi.longValue(),
                rawSpendableBTC.doubleValue(), rawSpendableDisplay);
        balance.setTotal(bitcoinBalanceAmount);
        balance.setSpendable(bitcoinSpendableAmount);
    } else {
        balance.setAmount(bitcoinBalanceAmount);
    }
    balance.setVisible(true);
    balance.setValid(true);
    balance.setRefreshing(false);
    return balance;
}

From source file:edu.pitt.apollo.db.ApolloDbUtils.java

public void addRunIdsToSimulationGroup(BigInteger simulationGroupId, List<BigInteger> runIds)
        throws ApolloDatabaseException, Md5UtilsException {

    String query = "INSERT IGNORE INTO simulation_group_definition (simulation_group_id, run_id) VALUES (?,?)";

    try (Connection conn = datasource.getConnection()) {
        PreparedStatement pstmt = conn.prepareStatement(query);
        for (BigInteger runId : runIds) {
            pstmt.setLong(1, simulationGroupId.longValue());
            pstmt.setLong(2, runId.longValue());
            pstmt.execute();//w w w .  jav  a2  s  . com
        }
    } catch (SQLException ex) {
        throw new ApolloDatabaseException(
                "SQLException adding run IDs to simulation group: " + ex.getMessage());
    }
}

From source file:edu.pitt.apollo.db.ApolloDbUtils.java

public BigInteger[] addVisualizationRun(RunVisualizationMessage runVisualizationMessage, int md5CollisionId,
        Authentication authentication)//from   w  w  w . j a  va 2  s .c  o m
        throws ApolloDatabaseException, ApolloDatabaseRecordNotInsertedException, Md5UtilsException {

    String userName = authentication.getRequesterId();
    String password = authentication.getRequesterPassword();

    String[] userIdTokens = parseUserId(userName);
    userName = userIdTokens[0];

    int userKey = getUserKey(userName, password);

    int softwareKey = getSoftwareIdentificationKey(runVisualizationMessage.getSoftwareIdentification());

    try (Connection conn = datasource.getConnection()) {
        //conn = getConn();
        List<BigInteger> runIds = new ArrayList<>();
        for (RunIdentificationAndLabel runIdentificationAndLabel : runVisualizationMessage
                .getSimulationRunIds()) {
            runIds.add(runIdentificationAndLabel.getRunIdentification());
        }
        BigInteger simulationGroupId = getNewSimulationGroupId();
        addRunIdsToSimulationGroup(simulationGroupId, runIds);

        String query = "INSERT INTO run (md5_hash_of_run_message, software_id, requester_id, last_service_to_be_called, simulation_group_id, md5_collision_id) VALUES (?, ?, ?, ?, ?, ?)";
        PreparedStatement pstmt = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
        pstmt.setString(1, md5Utils.getMd5(runVisualizationMessage));
        pstmt.setInt(2, softwareKey);
        pstmt.setInt(3, userKey);
        pstmt.setInt(4, 4); // 4 is translator
        pstmt.setLong(5, simulationGroupId.longValue());
        pstmt.setInt(6, md5CollisionId);
        pstmt.execute();

        BigInteger runId = null;
        ResultSet rs = pstmt.getGeneratedKeys();
        if (rs.next()) {
            runId = new BigInteger(rs.getString(1));
        } else {
            throw new ApolloDatabaseRecordNotInsertedException("Record not inserted!");
        }

        // ALSO NEED TO ADD serialized runVisualizationMessage(JSON) to
        // run_data_content table...
        // use insertDataContentForRun for this
        int dataContentKey = addTextDataContent(jsonUtils.getJSONString(runVisualizationMessage));
        int runDataDescriptionId = getRunDataDescriptionId(ContentDataFormatEnum.TEXT, "run_message.json",
                ContentDataTypeEnum.RUN_MESSAGE, 0,
                getSoftwareIdentificationKey(runVisualizationMessage.getSoftwareIdentification()));
        // int runDataId = the following line returns the runDataId, but
        // it's not used at this point.
        associateContentWithRunId(new BigInteger(String.valueOf(runId)), dataContentKey, runDataDescriptionId);
        BigInteger[] runIdSimulationGroupId = new BigInteger[2];
        runIdSimulationGroupId[0] = runId;
        runIdSimulationGroupId[1] = simulationGroupId;
        return runIdSimulationGroupId;
        //  } catch (ClassNotFoundException ex) {
        //     throw new ApolloDatabaseException(
        //            "ClassNotFoundException attempting to add visualization run: "
        //                   + ex.getMessage());
    } catch (SQLException ex) {
        throw new ApolloDatabaseException(
                "SQLException attempting to add visualization run: " + ex.getMessage());
    }
}

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;//  ww w. j a  v a  2  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:org.egov.services.payment.PaymentService.java

private void populateDeductionData(final List<EgBillregister> billList,
        final Map<Long, BigDecimal> deductionAmtMap, final String type,
        final List<CChartOfAccounts> glcodeList) {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Starting populateDeductionData...");
    List<Object[]> dedList;
    final List<Long> billIds = new ArrayList<Long>();
    if (billList != null && billList.size() != 0)
        for (final EgBillregister row : billList)
            billIds.add(row.getId());/*from  ww w .  j a  va2 s .  c  om*/
    if (billList != null && billList.size() != 0) {
        dedList = getDeductionList(type, glcodeList);
        if (dedList != null && dedList.size() != 0)
            for (final Object[] obj : dedList) {
                final BigInteger id = ((BigInteger) obj[0]);
                if (billIds.contains(id.longValue()))
                    deductionAmtMap.put(id.longValue(), obj[1] == null ? BigDecimal.ZERO : (BigDecimal) obj[1]);
            }
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Completed populateDeductionData.");
}

From source file:org.nuxeo.ecm.core.opencmis.impl.server.NuxeoCmisService.java

protected ObjectInFolderList getChildrenInternal(String repositoryId, String folderId, String filter,
        String orderBy, Boolean includeAllowableActions, IncludeRelationships includeRelationships,
        String renditionFilter, Boolean includePathSegment, BigInteger maxItems, BigInteger skipCount,
        boolean folderOnly) {
    ObjectInFolderListImpl result = new ObjectInFolderListImpl();
    List<ObjectInFolderData> list = new ArrayList<ObjectInFolderData>();
    DocumentModel folder = getDocumentModel(folderId);
    if (!folder.isFolder()) {
        return null;
    }/*from  w  w  w  .j  a  va 2  s . com*/

    String query = String.format("SELECT * FROM %s WHERE " // Folder/Document
            + "%s = '%s' AND " // ecm:parentId = 'folderId'
            + "%s <> '%s' AND " // ecm:mixinType <> 'HiddenInNavigation'
            + "%s <> '%s' AND " // ecm:currentLifeCycleState <> 'deleted'
            + "%s = 0", // ecm:isProxy = 0
            folderOnly ? "Folder" : "Document", //
            NXQL.ECM_PARENTID, folderId, //
            NXQL.ECM_MIXINTYPE, FacetNames.HIDDEN_IN_NAVIGATION, //
            NXQL.ECM_LIFECYCLESTATE, LifeCycleConstants.DELETED_STATE, //
            NXQL.ECM_ISPROXY);
    if (!StringUtils.isBlank(orderBy)) {
        CMISQLtoNXQL converter = new CMISQLtoNXQL();
        query += " ORDER BY " + converter.convertOrderBy(orderBy, repository.getTypeManager());
    }

    long limit = maxItems == null ? 0 : maxItems.longValue();
    if (limit < 0) {
        limit = 0;
    }
    long offset = skipCount == null ? 0 : skipCount.longValue();
    if (offset < 0) {
        offset = 0;
    }

    DocumentModelList children;
    try {
        children = coreSession.query(query, null, limit, offset, true);
    } catch (ClientException e) {
        throw new CmisRuntimeException(e.toString(), e);
    }

    for (DocumentModel child : children) {
        NuxeoObjectData data = new NuxeoObjectData(this, child, filter, includeAllowableActions,
                includeRelationships, renditionFilter, Boolean.FALSE, Boolean.FALSE, null);
        ObjectInFolderDataImpl oifd = new ObjectInFolderDataImpl();
        oifd.setObject(data);
        if (Boolean.TRUE.equals(includePathSegment)) {
            oifd.setPathSegment(child.getName());
        }
        list.add(oifd);
        collectObjectInfo(repositoryId, data.getId());
    }

    Boolean hasMoreItems;
    if (limit == 0) {
        hasMoreItems = Boolean.FALSE;
    } else {
        hasMoreItems = Boolean.valueOf(children.totalSize() > offset + limit);
    }
    result.setObjects(list);
    result.setHasMoreItems(hasMoreItems);
    result.setNumItems(BigInteger.valueOf(children.totalSize()));
    collectObjectInfo(repositoryId, folderId);
    return result;
}

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

/**
 * Create and populate a JSONRPCBalance object given an assetID and balance
 * @param w//  www  .j av a  2 s  .c  o m
 * @param assetID
 * @param totalRaw
 * @param spendableRaw If null, we set the amount field, instead of total and spendable.
 * @return 
 */
private JSONRPCBalance createAssetBalance(Wallet w, int assetID, BigInteger totalRaw, BigInteger spendableRaw) {
    //Wallet.CoinSpark.AssetBalance assetBalance;
    CSAsset asset = w.CS.getAsset(assetID);

    String name = asset.getName();
    String nameShort = asset.getNameShort();

    if (name == null) {
        CoinSparkGenesis genesis = asset.getGenesis();
        if (genesis != null) {
            name = "Asset from " + genesis.getDomainName();
            nameShort = name;
        } else {
            // No genesis block found yet
            name = "Other Asset";
            nameShort = "Other Asset";
        }
    }

    String assetRef = CSMiscUtils.getHumanReadableAssetRef(asset);
    if (assetRef == null) {
        assetRef = "Awaiting new asset confirmation...";
    }

    JSONRPCBalance ab = new JSONRPCBalance();
    ab.setAsset_ref(assetRef);

    // Compute total balance
    Double balanceQty = CSMiscUtils.getDisplayUnitsForRawUnits(asset, totalRaw).doubleValue();
    String balanceDisplay = CSMiscUtils.getFormattedDisplayStringForRawUnits(asset, totalRaw);
    JSONRPCBalanceAmount balanceAmount = new JSONRPCBalanceAmount(totalRaw.longValue(), balanceQty,
            balanceDisplay);

    if (spendableRaw != null) {
        Double spendableQty = CSMiscUtils.getDisplayUnitsForRawUnits(asset, spendableRaw).doubleValue();
        String spendableDisplay = CSMiscUtils.getFormattedDisplayStringForRawUnits(asset, spendableRaw);
        JSONRPCBalanceAmount spendableAmount = new JSONRPCBalanceAmount(spendableRaw.longValue(), spendableQty,
                spendableDisplay);

        ab.setTotal(balanceAmount);
        ab.setSpendable(spendableAmount);
    } else {
        ab.setAmount(balanceAmount);
    }

    ab.setName(name);
    ab.setName_short(nameShort);
    String domain = CSMiscUtils.getDomainHost(asset.getDomainURL());
    ab.setDomain(domain);
    ab.setUrl(asset.getAssetWebPageURL());
    ab.setIssuer(asset.getIssuer());
    ab.setDescription(asset.getDescription());
    ab.setUnits(asset.getUnits());
    ab.setMultiple(asset.getMultiple());
    boolean isValid = (asset.getAssetState() == CSAsset.CSAssetState.VALID);

    if (asset.getAssetState() == CSAsset.CSAssetState.REFRESH) {
        ab.setRefreshing(true);
        ab.setStatus(CSMiscUtils.getHumanReadableAssetState(asset.getAssetStateBeforeRefresh()));
    } else {
        ab.setRefreshing(false);
        ab.setStatus(CSMiscUtils.getHumanReadableAssetState(asset.getAssetState()));
    }

    ab.setValid(isValid);
    Date validCheckedDate = asset.getValidChecked();
    if (validCheckedDate != null) {
        ab.setChecked_unixtime(validCheckedDate.getTime() / 1000L);
    }
    ab.setContract_url(asset.getContractUrl());

    String contractPath = asset.getContractPath();
    if (contractPath != null) {
        String appDirPath = controller.getApplicationDataDirectoryLocator().getApplicationDataDirectory();
        File file = new File(contractPath);
        File dir = new File(appDirPath);
        try {
            URI absolute = file.toURI();
            URI base = dir.toURI();
            URI relative = base.relativize(absolute);
            contractPath = relative.getPath();
        } catch (Exception e) {
            // do nothing, if error, just use full contractPath
        }
    }
    ab.setContract_file(contractPath);
    ab.setGenesis_txid(asset.getGenTxID());
    Date creationDate = asset.getDateCreation();
    if (creationDate != null) {
        ab.setAdded_unixtime(creationDate.getTime() / 1000L);
    }
    // 3 October 2014, 1:47 am
    SimpleDateFormat sdf = new SimpleDateFormat("d MMMM yyyy, h:mm");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // CoinSpark asset web page shows GMT/UTC.
    SimpleDateFormat ampmdf = new SimpleDateFormat(" a"); // by default is uppercase and we need lower to match website
    Date issueDate = asset.getIssueDate();
    if (issueDate != null) {
        ab.setIssue_date(sdf.format(issueDate) + ampmdf.format(issueDate).toLowerCase());
        ab.setIssue_unixtime(issueDate.getTime() / 1000L);
    }

    // Never expires
    Date expiryDate = asset.getExpiryDate();
    if (expiryDate != null) {
        ab.setExpiry_date(sdf.format(expiryDate) + ampmdf.format(expiryDate).toLowerCase());
        ab.setExpiry_unixtime(expiryDate.getTime() / 1000L);
    }
    ab.setTracker_urls(asset.getCoinsparkTrackerUrls());
    ab.setIcon_url(asset.getIconUrl());
    ab.setImage_url(asset.getImageUrl());
    ab.setFeed_url(asset.getFeedUrl());
    ab.setRedemption_url(asset.getRedemptionUrl());
    ab.setVisible(asset.isVisible());
    return ab;
}

From source file:edu.pitt.apollo.db.ApolloDbUtils.java

public BigInteger[] addSimulationRun(RunMessage runMessage, int md5CollisionId,
        SoftwareIdentification identificationOfSoftwareToRun, int sourceSoftwareIdKey,
        SoftwareIdentification destinationSoftwareForRunSimulationMessage, Authentication authentication)
        throws ApolloDatabaseException, Md5UtilsException {

    String userName = authentication.getRequesterId();
    String password = authentication.getRequesterPassword();

    runMessage.setAuthentication(new Authentication());

    String[] userIdTokens = parseUserId(userName);
    userName = userIdTokens[0];/*from w  ww  . j  a v  a2 s  .com*/

    Integer softwareKey = null;
    if (identificationOfSoftwareToRun != null) {
        softwareKey = getSoftwareIdentificationKey(identificationOfSoftwareToRun);
    }
    int userKey = getUserKey(userName, password);

    BigInteger simulationGroupId = null;
    String additionalInsertField = "";
    String additionalParamHolder = "";
    BigInteger[] runIdSimulationGroupId = new BigInteger[2];
    String md5 = md5Utils.getMd5(runMessage);

    try (Connection conn = datasource.getConnection()) {

        simulationGroupId = getNewSimulationGroupId();
        runIdSimulationGroupId[1] = simulationGroupId;
        additionalInsertField = ", simulation_group_id";
        additionalParamHolder = ",?";

        String query = "INSERT IGNORE INTO run (md5_hash_of_run_message, software_id, requester_id, last_service_to_be_called, md5_collision_id "
                + additionalInsertField + ") VALUES (?, ?, ?, ?, ? " + additionalParamHolder + ")";
        PreparedStatement pstmt = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
        pstmt.setString(1, md5);
        if (softwareKey != null) {
            pstmt.setInt(2, softwareKey);
        } else {
            pstmt.setNull(2, Types.INTEGER);
        }
        pstmt.setInt(3, userKey);
        pstmt.setInt(4, 1);
        pstmt.setInt(5, md5CollisionId);
        pstmt.setLong(6, simulationGroupId.longValue());

        ResultSet rs;
        int rowsAffected = pstmt.executeUpdate();

        if (rowsAffected > 0) {
            rs = pstmt.getGeneratedKeys();
        } else {
            query = "SELECT id FROM run WHERE md5_hash_of_run_message = ? and md5_collision_id = ?";
            pstmt = conn.prepareStatement(query);
            pstmt.setString(1, md5);
            pstmt.setInt(2, md5CollisionId);
            rs = pstmt.executeQuery();
        }

        BigInteger runId;
        if (rs.next()) {
            runId = new BigInteger(rs.getString(1));
        } else {
            throw new ApolloDatabaseRecordNotInsertedException("Record not inserted!");
        }

        List<BigInteger> runIds = new ArrayList<>();
        runIds.add(runId);
        if (!(runMessage instanceof RunSimulationsMessage)) {
            addRunIdsToSimulationGroup(simulationGroupId, runIds);
        }

        // ALSO NEED TO ADD serialized runSimulationMessage(JSON) to
        // run_data_content table...
        // use insertDataContentForRun for this
        int dataContentKey = addTextDataContent(jsonUtils.getJSONString(runMessage));
        int runDataDescriptionId = getRunDataDescriptionId(ContentDataFormatEnum.TEXT, "run_message.json",
                ContentDataTypeEnum.RUN_MESSAGE, sourceSoftwareIdKey,
                getSoftwareIdentificationKey(destinationSoftwareForRunSimulationMessage));
        // int runDataId = the following line returns the runDataId, but
        // it's not used at this point.
        associateContentWithRunId(new BigInteger(String.valueOf(runId)), dataContentKey, runDataDescriptionId);

        runIdSimulationGroupId[0] = runId;
        if (runIdSimulationGroupId.length == 2) {
            runIdSimulationGroupId[1] = simulationGroupId;
        }

        updateStatusOfRun(runId, MethodCallStatusEnum.LOADED_RUN_CONFIG_INTO_DATABASE,
                "Adding config information to the database for runId: " + runId.toString());

        return runIdSimulationGroupId;
        // } catch (ClassNotFoundException ex) {
        //     throw new ApolloDatabaseException(
        //             "ClassNotFoundException attempting to add simulation run: "
        //                     + ex.getMessage());
    } catch (SQLException ex) {
        throw new ApolloDatabaseException("SQLException attempting to add simulation run: " + ex.getMessage());
    }
}

From source file:org.energy_home.jemma.javagal.layers.business.GalController.java

/**
 * Gets the Short Address from network cache.
 * /*ww w  .j  a  v a  2  s  .c o  m*/
 * @param IeeeAddress
 *            the address of interest.
 * @return null if the address does not exist in network cache or a positive
 *         number indicating the index of the desired object
 * @throws GatewayException
 */
public Integer getShortAddress_FromIeeeAddress(BigInteger IeeeAddress) throws Exception {
    LOG.debug("[getShortAddress_FromIeeeAddress] Start Search Node: {}", String.format("%016X", IeeeAddress));
    synchronized (getNetworkcache()) {
        for (WrapperWSNNode y : getNetworkcache()) {
            LOG.debug("[getShortAddress_FromIeeeAddress] Short Address: {}",
                    ((y.get_node().getAddress().getNetworkAddress() != null)
                            ? String.format("%04X", y.get_node().getAddress().getNetworkAddress())
                            : "NULL")
                            + " - IEEE Address:"
                            + ((y.get_node().getAddress().getIeeeAddress() != null)
                                    ? String.format("%016X", y.get_node().getAddress().getIeeeAddress())
                                    : "NULL")
                            + " - - Discovery Completed:" + y.is_discoveryCompleted());
            if (y.is_discoveryCompleted() && (y.get_node() != null) && (y.get_node().getAddress() != null)
                    && (y.get_node().getAddress().getIeeeAddress() != null)
                    && (y.get_node().getAddress().getNetworkAddress() != null)
                    && y.get_node().getAddress().getIeeeAddress().longValue() == IeeeAddress.longValue()) {
                LOG.debug("[getShortAddress_FromIeeeAddress] FOUND Node: {} ",
                        String.format("%016X", IeeeAddress));

                if (y.get_node().getAddress().getNetworkAddress() == null)
                    throw new Exception("Shoort Address null on GAL: " + String.format("%016X", IeeeAddress));
                else
                    return new Integer(y.get_node().getAddress().getNetworkAddress());
            }
        }
        throw new Exception("Ieee Address not found on GAL: " + String.format("%016X", IeeeAddress));
    }
}