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:spade.reporter.Audit.java

/**
 * Converts syscall args: 'a0', 'a1', 'a2', and 'a3' from hexadecimal values to decimal values
 * /*  w w  w.j a v a 2s .co  m*/
 * Conversion done based on the length of the hex value string. If length <= 8 then integer else a long.
 * If length > 16 then truncated to long.
 * 
 * Done so to avoid the issue of incorrectly fitting a small negative (i.e. int) value into a big (i.e. long) value
 * causing a wrong interpretation of bits.
 * 
 * @param eventData map that contains the above-mentioned args keys and values
 * @param time time of the event
 * @param eventId id of the event
 * @param syscall syscall of the event
 */
private void convertArgsHexToDec(Map<String, String> eventData, String time, String eventId, SYSCALL syscall) {
    String[] argKeys = { AuditEventReader.ARG0, AuditEventReader.ARG1, AuditEventReader.ARG2,
            AuditEventReader.ARG3 };
    for (String argKey : argKeys) {
        String hexArgValue = eventData.get(argKey);
        if (hexArgValue != null) {
            int hexArgValueLength = hexArgValue.length();
            try {
                BigInteger bigInt = new BigInteger(hexArgValue, 16);
                String argValueString = null;
                if (hexArgValueLength <= 8) {
                    int argInt = bigInt.intValue();
                    argValueString = Integer.toString(argInt);
                } else { // greater than 8
                    if (hexArgValueLength > 16) {
                        log(Level.SEVERE, "Truncated value for '" + argKey + "': '" + hexArgValue
                                + "'. Too big for 'long' datatype", null, time, eventId, syscall);
                    }
                    long argLong = bigInt.longValue();
                    argValueString = Long.toString(argLong);
                }
                eventData.put(argKey, argValueString);
            } catch (Exception e) {
                log(Level.SEVERE, "Non-numerical value for '" + argKey + "': '" + hexArgValue + "'", e, time,
                        eventId, syscall);
            }
        } else {
            log(Level.SEVERE, "NULL value for '" + argKey + "'", null, time, eventId, syscall);
        }
    }
}

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

/**
 * Gets the content from the repository.
 *///w w  w  . j  a  v  a  2 s  .com
public ContentStream getContentStream(CMISNodeInfo info, String streamId, BigInteger offset,
        BigInteger length) {
    // get the type and check if the object can have content
    TypeDefinitionWrapper type = info.getType();
    checkDocumentTypeForContent(type);

    // looks like a document, now get the content
    ContentStreamImpl result = new ContentStreamImpl();
    result.setFileName(info.getName());

    // if streamId is set, fetch other content
    NodeRef streamNodeRef = info.getNodeRef();
    if ((streamId != null) && (streamId.length() > 0)) {
        CMISNodeInfo streamInfo = createNodeInfo(streamId);
        if (!streamInfo.isVariant(CMISObjectVariant.CURRENT_VERSION)) {
            throw new CmisInvalidArgumentException("Stream id is invalid: " + streamId + ", expected variant "
                    + CMISObjectVariant.CURRENT_VERSION + ", got variant " + streamInfo.getObjectVariant());
        }

        streamNodeRef = streamInfo.getNodeRef();
        type = streamInfo.getType();
        checkDocumentTypeForContent(type);
    }

    // get the stream now
    try {
        ContentReader contentReader = contentService.getReader(streamNodeRef, ContentModel.PROP_CONTENT);
        if (contentReader == null) {
            throw new CmisConstraintException("Document has no content!");
        }

        result.setMimeType(contentReader.getMimetype());
        long contentSize = contentReader.getSize();

        if ((offset == null) && (length == null)) {
            result.setStream(contentReader.getContentInputStream());
            result.setLength(BigInteger.valueOf(contentSize));
            publishReadEvent(streamNodeRef, info.getName(), result.getMimeType(), contentSize,
                    contentReader.getEncoding(), null);
        } else {
            long off = (offset == null ? 0 : offset.longValue());
            long len = (length == null ? contentSize : length.longValue());
            if (off + len > contentSize) {
                len = contentReader.getSize() - off;
            }

            result.setStream(new RangeInputStream(contentReader.getContentInputStream(), off, len));
            result.setLength(BigInteger.valueOf(len));
            publishReadEvent(streamNodeRef, info.getName(), result.getMimeType(), contentSize,
                    contentReader.getEncoding(), off + " - " + len);
        }
    } catch (Exception e) {
        if (e instanceof CmisBaseException) {
            throw (CmisBaseException) e;
        } else {
            StringBuilder msg = new StringBuilder("Failed to retrieve content: " + e.getMessage());
            Throwable cause = e.getCause();
            if (cause != null) {
                // add the cause to the CMIS exception
                msg.append(", ");
                msg.append(cause.getMessage());
            }
            throw new CmisRuntimeException(msg.toString(), e);
        }
    }

    return result;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return resultList;
}

From source file:ca.oson.json.Oson.java

private <E, R> BigInteger json2BigIntegerDefault(FieldData objectDTO) {
    E value = (E) objectDTO.valueToProcess;
    Class<R> returnType = objectDTO.returnType;
    boolean required = objectDTO.required();

    Long min = objectDTO.getMin();
    Long max = objectDTO.getMax();

    if (getDefaultType() == JSON_INCLUDE.DEFAULT || required) {
        BigInteger defaultValue = (BigInteger) objectDTO.getDefaultValue();
        if (defaultValue != null) {
            if (min != null && min > defaultValue.longValue()) {
                return BigInteger.valueOf(min);
            }//  w  w  w .  j ava  2  s .  co m

            if (max != null && defaultValue.compareTo(BigInteger.valueOf(max)) > 0) {
                return BigInteger.valueOf(max);
            }

            return defaultValue;
        }

        if (min != null && DefaultValue.bigInteger.compareTo(BigInteger.valueOf(min)) < 0) {
            return BigInteger.valueOf(min);
        }

        return DefaultValue.bigInteger;
    }

    return null;
}

From source file:ca.oson.json.Oson.java

private <E, R> String bigInteger2Json(FieldData objectDTO) {
    if (objectDTO == null || objectDTO.json2Java) {
        return null;
    }//from  ww w . jav  a 2s.c  om

    E value = (E) objectDTO.valueToProcess;
    Class<R> returnType = objectDTO.returnType;

    if (value != null && value.toString().trim().length() > 0) {
        BigInteger valueToProcess = null;
        String valueToReturn = null;

        if (value instanceof BigInteger) {
            valueToProcess = (BigInteger) value;
        } else {
            try {
                valueToProcess = new BigInteger(value.toString().trim());
            } catch (Exception ex) {
            }
        }

        if (valueToProcess != null) {
            try {
                Function function = objectDTO.getSerializer();
                if (function != null) {
                    try {
                        if (function instanceof DataMapper2JsonFunction) {
                            DataMapper classData = new DataMapper(returnType, value, objectDTO.classMapper,
                                    objectDTO.level, getPrettyIndentation());
                            return ((DataMapper2JsonFunction) function).apply(classData);

                        } else if (function instanceof BigInteger2JsonFunction) {
                            return ((BigInteger2JsonFunction) function).apply(valueToProcess);

                        } else {

                            Object returnedValue = null;
                            if (function instanceof FieldData2JsonFunction) {
                                FieldData2JsonFunction f = (FieldData2JsonFunction) function;
                                FieldData fieldData = objectDTO.clone();
                                returnedValue = f.apply(fieldData);
                            } else {
                                returnedValue = function.apply(value);
                            }

                            if (returnedValue instanceof Optional) {
                                returnedValue = ObjectUtil.unwrap(returnedValue);
                            }

                            if (returnedValue == null) {
                                return null;

                            } else if (returnedValue instanceof BigInteger) {
                                valueToProcess = (BigInteger) returnedValue;

                            } else {
                                objectDTO.valueToProcess = returnedValue;
                                return object2String(objectDTO);
                            }

                        }

                    } catch (Exception e) {
                    }
                }

                if (valueToProcess != null) {
                    Long min = objectDTO.getMin();
                    Long max = objectDTO.getMax();

                    if (min != null && min > valueToProcess.longValue()) {
                        valueToProcess = BigInteger.valueOf(min);
                    }

                    if (max != null && valueToProcess.compareTo(BigInteger.valueOf(max)) > 0) {
                        valueToProcess = BigInteger.valueOf(max);
                    }

                    Integer precision = objectDTO.getPrecision();
                    if (precision != null) {
                        valueToProcess = (BigInteger) NumberUtil.setPrecision(valueToProcess, precision,
                                getRoundingMode());
                    }

                    return NumberUtil.toPlainString(valueToProcess);
                }

            } catch (Exception ex) {
                //ex.printStackTrace();
            }
        }
    }

    return bigInteger2JsonDefault(objectDTO);
}

From source file:ca.oson.json.Oson.java

private <E, R> BigInteger json2BigInteger(FieldData objectDTO) {
    if (objectDTO == null || !objectDTO.json2Java) {
        return null;
    }//ww  w  .  j  ava  2  s. co m

    E value = (E) objectDTO.valueToProcess;
    Class<R> returnType = objectDTO.returnType;

    if (value != null && value.toString().trim().length() > 0) {
        String valueToProcess = value.toString().trim();
        BigInteger valueToReturn = null;

        try {
            Function function = objectDTO.getDeserializer();

            if (function != null) {
                try {
                    Object returnedValue = null;

                    if (function instanceof Json2DataMapperFunction) {
                        DataMapper classData = new DataMapper(returnType, value, objectDTO.classMapper,
                                objectDTO.level, getPrettyIndentation());
                        returnedValue = ((Json2DataMapperFunction) function).apply(classData);

                    } else if (function instanceof Json2FieldDataFunction) {
                        Json2FieldDataFunction f = (Json2FieldDataFunction) function;
                        FieldData fieldData = objectDTO.clone();

                        returnedValue = f.apply(fieldData);

                    } else if (function instanceof Json2BigIntegerFunction) {
                        return ((Json2BigIntegerFunction) function).apply(valueToProcess);
                    } else {
                        returnedValue = function.apply(valueToProcess);
                    }

                    if (returnedValue instanceof Optional) {
                        returnedValue = ObjectUtil.unwrap(returnedValue);
                    }

                    if (returnedValue == null) {
                        return null;

                    } else if (Number.class.isAssignableFrom(returnedValue.getClass())
                            || returnedValue.getClass().isPrimitive()) {

                        if (returnedValue instanceof BigInteger) {
                            valueToReturn = (BigInteger) returnedValue;
                        } else if (returnedValue instanceof String) {
                            valueToReturn = new BigInteger((String) returnedValue);

                        } else if (returnedValue instanceof Integer) {
                            valueToReturn = BigInteger.valueOf((Integer) returnedValue);
                        } else if (returnedValue instanceof Long) {
                            valueToReturn = BigInteger.valueOf((Long) returnedValue);
                        } else if (returnedValue instanceof Short) {
                            valueToReturn = BigInteger.valueOf((Short) returnedValue);
                        } else if (returnedValue instanceof Double) {
                            valueToReturn = BigInteger.valueOf(((Double) returnedValue).longValue());
                        } else if (returnedValue instanceof Float) {
                            valueToReturn = BigInteger.valueOf(((Float) returnedValue).intValue());
                        } else if (returnedValue instanceof BigDecimal) {
                            valueToReturn = BigInteger.valueOf(((BigDecimal) returnedValue).longValue());
                        } else if (returnedValue instanceof Byte) {
                            valueToReturn = BigInteger.valueOf((Byte) returnedValue);
                        } else if (returnedValue instanceof AtomicInteger) {
                            valueToReturn = BigInteger.valueOf(((AtomicInteger) returnedValue).intValue());
                        } else if (returnedValue instanceof AtomicLong) {
                            valueToReturn = BigInteger.valueOf(((AtomicLong) returnedValue).longValue());
                        } else {
                            valueToReturn = BigInteger.valueOf(((Number) returnedValue).longValue());
                        }

                    } else if (returnedValue instanceof Character) {
                        valueToReturn = BigInteger.valueOf(((Character) returnedValue));

                    } else if (returnedValue instanceof Boolean) {
                        if ((Boolean) returnedValue)
                            valueToReturn = BigInteger.valueOf(1);
                        else
                            valueToReturn = BigInteger.valueOf(0);

                    } else if (Enum.class.isAssignableFrom(returnedValue.getClass())) {
                        valueToReturn = BigInteger.valueOf(((Enum) returnedValue).ordinal());

                    } else if (Date.class.isAssignableFrom(returnedValue.getClass())) {
                        valueToReturn = BigInteger.valueOf(((Date) returnedValue).getTime());

                    } else {
                        valueToReturn = new BigInteger((returnedValue.toString()));
                    }

                    return valueToReturn;

                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                valueToReturn = new BigInteger(valueToProcess);
            }

            if (valueToReturn != null) {
                Long min = objectDTO.getMin();
                Long max = objectDTO.getMax();

                if (min != null && min > valueToReturn.longValue()) {
                    return BigInteger.valueOf(min.intValue());
                }

                if (max != null && valueToReturn.compareTo(BigInteger.valueOf(max)) > 0) {
                    valueToReturn = BigInteger.valueOf(max);
                }

                return valueToReturn;
            }

        } catch (Exception ex) {
            //ex.printStackTrace();
        }

    }

    return json2BigIntegerDefault(objectDTO);
}