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:ubic.gemma.persistence.util.EntityUtils.java

/**
 * Expert use only. Used to expose some ACL information to the DAO layer (normally this happens in an interceptor).
 *
 * @param sess             session//from ww  w .  j a va 2  s  .c o m
 * @param securedClass     Securable type
 * @param ids              to be filtered
 * @param showPublic       also show public items (won't work if showOnlyEditable is true)
 * @param showOnlyEditable show only editable
 * @return filtered IDs, at the very least limited to those that are readable by the current user
 */
public static Collection<Long> securityFilterIds(Class<? extends Securable> securedClass, Collection<Long> ids,
        boolean showOnlyEditable, boolean showPublic, Session sess) {

    if (ids.isEmpty())
        return ids;
    if (SecurityUtil.isUserAdmin()) {
        return ids;
    }

    /*
     * Find groups user is a member of
     */

    String userName = SecurityUtil.getCurrentUsername();

    boolean isAnonymous = SecurityUtil.isUserAnonymous();

    if (isAnonymous && (showOnlyEditable || !showPublic)) {
        return new HashSet<>();
    }

    String queryString = "select aoi.OBJECT_ID";
    queryString += " from ACLOBJECTIDENTITY aoi";
    queryString += " join ACLENTRY ace on ace.OBJECTIDENTITY_FK = aoi.ID ";
    queryString += " join ACLSID sid on sid.ID = aoi.OWNER_SID_FK ";
    queryString += " where aoi.OBJECT_ID in (:ids)";
    queryString += " and aoi.OBJECT_CLASS = :clazz and ";
    queryString += EntityUtils.addGroupAndUserNameRestriction(showOnlyEditable, showPublic);

    // will be empty if anonymous
    //noinspection unchecked
    Collection<String> groups = sess.createQuery(
            "select ug.name from UserGroup ug inner join ug.groupMembers memb where memb.userName = :user")
            .setParameter("user", userName).list();

    Query query = sess.createSQLQuery(queryString).setParameter("clazz", securedClass.getName())
            .setParameterList("ids", ids);

    if (queryString.contains(":groups")) {
        query.setParameterList("groups", groups);
    }

    if (queryString.contains(":userName")) {
        query.setParameter("userName", userName);
    }

    //noinspection unchecked
    List<BigInteger> r = query.list();
    Set<Long> rl = new HashSet<>();
    for (BigInteger bi : r) {
        rl.add(bi.longValue());
    }

    if (!ids.containsAll(rl)) {
        // really an assertion, but being extra-careful
        throw new SecurityException("Security filter failure");
    }

    return rl;
}

From source file:com.github.chrbayer84.keybits.KeyBits.java

public static void encodeAddresses(String wallet_file_name, String chain_file_name,
        String checkpoints_file_name, String[] addresses, int amount, int depth, String passphrase)
        throws Exception {
    // compute necessary amount of satoshis for encoding addresses using second wallet (keypair or message wallet)
    double satoshis_of_bitcoin = 100000000.0;

    int fee = MyWallet.getFees(1, addresses.length);
    int amount_per_address = SendRequest.DEFAULT_FEE_PER_KB.intValue();
    int number_of_addresses = addresses.length;
    BigInteger needed = new BigInteger("" + (number_of_addresses * amount_per_address + fee + amount));

    // create or update second wallet and get available funds
    BigInteger available = MyWallet.getBalanceOfWallet(wallet_file_name, chain_file_name);

    System.out.println("number of outputs: " + number_of_addresses);
    System.out.println("available funds  : " + available + " satoshis ("
            + available.longValue() / satoshis_of_bitcoin + " XBT)");
    System.out.println("needed fees      : " + fee + " satoshis (" + fee / satoshis_of_bitcoin + " XBT)");
    System.out.println("needed funds     : " + needed + " satoshis (" + needed.longValue() / satoshis_of_bitcoin
            + " XBT)");

    // test if there are enough funds in second wallet
    // if yes, create addresses, else move enough founds to second wallet   
    if (available.longValue() >= needed.longValue()) {
        createAddresses(wallet_file_name, chain_file_name, checkpoints_file_name, addresses,
                new BigInteger(fee + ""), new BigInteger(amount_per_address + ""), depth, passphrase);
    } else {//  w  w  w .j a  va  2 s  .c  om
        // get first (and only) address in second wallet
        String address = MyWallet.getAddress(wallet_file_name, chain_file_name, 0); //System.out.println(address);

        BigInteger to_send = new BigInteger("" + (needed.longValue() - available.longValue()));
        System.out.println();
        System.out.println("please send " + to_send.longValue() + " satoshis ("
                + to_send.longValue() / satoshis_of_bitcoin + " XBT) to address " + address);

        System.exit(0);
    }
}

From source file:org.opendaylight.controller.sal.core.Node.java

/**
 * Static method to get back a Node from a string
 *
 * @param str string formatted in toString mode that can be
 * converted back to a Node format.//from  ww w .  jav  a 2 s . c  o m
 *
 * @return a Node if succed or null if no
 */
public static Node fromString(String str) {
    if (str == null) {
        return null;
    }

    String parts[] = str.split("\\|");
    if (parts.length != 2) {
        // Try to guess from a String formatted as a long because
        // for long time openflow has been prime citizen so lets
        // keep this legacy for now
        String numStr = str.toUpperCase();

        Long ofNodeID = null;
        if (numStr.startsWith("0X")) {
            // Try as an hex number
            try {
                BigInteger b = new BigInteger(numStr.replaceFirst("0X", ""), 16);
                ofNodeID = Long.valueOf(b.longValue());
            } catch (Exception ex) {
                ofNodeID = null;
            }
        } else {
            // Try as a decimal number
            try {
                BigInteger b = new BigInteger(numStr);
                ofNodeID = Long.valueOf(b.longValue());
            } catch (Exception ex) {
                ofNodeID = null;
            }
        }

        // Startegy #3 parse as HexLong
        if (ofNodeID == null) {
            try {
                ofNodeID = Long.valueOf(HexEncode.stringToLong(numStr));
            } catch (Exception ex) {
                ofNodeID = null;
            }
        }

        // We ran out of ideas ... return null
        if (ofNodeID == null) {
            return null;
        }

        // Lets return the cooked up NodeID
        try {
            return new Node(NodeIDType.OPENFLOW, ofNodeID);
        } catch (ConstructionException ex) {
            return null;
        }
    }

    String typeStr = parts[0];
    String IDStr = parts[1];

    return fromString(typeStr, IDStr);
}

From source file:com.aegiswallet.utils.BasicUtils.java

public static String formatValue(@Nonnull final BigInteger value, @Nonnull final String plusSign,
        @Nonnull final String minusSign, final int precision, final int shift) {
    long longValue = value.longValue();

    final String sign = longValue < 0 ? minusSign : plusSign;

    if (shift == 0) {
        if (precision == 2)
            longValue = longValue - longValue % 1000000 + longValue % 1000000 / 500000 * 1000000;
        else if (precision == 4)
            longValue = longValue - longValue % 10000 + longValue % 10000 / 5000 * 10000;
        else if (precision == 6)
            longValue = longValue - longValue % 100 + longValue % 100 / 50 * 100;
        else if (precision == 8)
            ;//  w  ww . j  a va  2  s  .  c o  m
        else
            throw new IllegalArgumentException("cannot handle precision/shift: " + precision + "/" + shift);

        final long absValue = Math.abs(longValue);
        final long coins = absValue / ONE_BTC_INT;
        final int satoshis = (int) (absValue % ONE_BTC_INT);

        if (satoshis % 1000000 == 0)
            return String.format(Locale.US, "%s%d.%02d", sign, coins, satoshis / 1000000);
        else if (satoshis % 10000 == 0)
            return String.format(Locale.US, "%s%d.%04d", sign, coins, satoshis / 10000);
        else if (satoshis % 100 == 0)
            return String.format(Locale.US, "%s%d.%06d", sign, coins, satoshis / 100);
        else
            return String.format(Locale.US, "%s%d.%08d", sign, coins, satoshis);
    } else if (shift == 3) {
        if (precision == 2)
            longValue = longValue - longValue % 1000 + longValue % 1000 / 500 * 1000;
        else if (precision == 4)
            longValue = longValue - longValue % 10 + longValue % 10 / 5 * 10;
        else if (precision == 5)
            ;
        else
            throw new IllegalArgumentException("cannot handle precision/shift: " + precision + "/" + shift);

        final long absValue = Math.abs(longValue);
        final long coins = absValue / ONE_MBTC_INT;
        final int satoshis = (int) (absValue % ONE_MBTC_INT);

        if (satoshis % 1000 == 0)
            return String.format(Locale.US, "%s%d.%02d", sign, coins, satoshis / 1000);
        else if (satoshis % 10 == 0)
            return String.format(Locale.US, "%s%d.%04d", sign, coins, satoshis / 10);
        else
            return String.format(Locale.US, "%s%d.%05d", sign, coins, satoshis);
    } else {
        throw new IllegalArgumentException("cannot handle shift: " + shift);
    }
}

From source file:com.github.jessemull.microflex.util.BigIntegerUtil.java

/**
 * Converts a list of BigIntegers to a list of longs.
 * @param    List<BigInteger>    list of BigIntegers
 * @return                       list of longs
 *///from  ww  w  .j av a 2  s . c  om
public static List<Long> toLongList(List<BigInteger> list) {

    List<Long> longList = new ArrayList<Long>();

    for (BigInteger val : list) {
        if (!OverFlowUtil.longOverflow(val)) {
            OverFlowUtil.overflowError(val);
        }
        longList.add(val.longValue());
    }

    return longList;

}

From source file:com.abiquo.am.services.ovfformat.TemplateFromOVFEnvelope.java

/**
 * TODO TBD/*from  w  w w .  j a v  a 2  s.c  om*/
 **/
private static TemplateDto getDiskInfo(final VirtualSystemType vsystem,
        final Map<String, VirtualDiskDescType> diskDescByName, final Map<String, List<String>> diskIdToVSs)
        throws IdAlreadyExistsException, RequiredAttributeException, SectionNotPresentException {
    TemplateDto dReq = new TemplateDto();
    VirtualHardwareSectionType hardwareSectionType;

    try {
        hardwareSectionType = OVFEnvelopeUtils.getSection(vsystem, VirtualHardwareSectionType.class);
    } catch (InvalidSectionException e) {
        throw new SectionNotPresentException("VirtualHardware on a virtualSystem", e);
    }

    dReq.setCpu(-1);
    dReq.setHd(Long.valueOf(-1));
    dReq.setRam(Long.valueOf(-1));

    // XXX now we are using ONLY the Disk format

    // XXX String vsType = hardwareSectionType.getSystem().getVirtualSystemType().getValue();
    // XXX dReq.setImageType(vsType);
    // XXX log.debug("Using ''virtualSystemType'' [{}]", vsType);

    for (RASDType rasdType : hardwareSectionType.getItem()) {
        ResourceType resourceType = rasdType.getResourceType();
        int resTnumeric = Integer.parseInt(resourceType.getValue());

        // TODO use CIMResourceTypeEnum from value and then a SWITCH

        // Get the information on the ram
        if (CIMResourceTypeEnum.Processor.getNumericResourceType() == resTnumeric) {
            String cpuVal = rasdType.getVirtualQuantity().getValue().toString();

            dReq.setCpu(Integer.parseInt(cpuVal));

            // TODO if(rasdType.getAllocationUnits()!= null)
        } else if (CIMResourceTypeEnum.Memory.getNumericResourceType() == resTnumeric) {
            BigInteger ramVal = rasdType.getVirtualQuantity().getValue();

            dReq.setRam(ramVal.longValue());

            if (rasdType.getAllocationUnits() != null & rasdType.getAllocationUnits().getValue() != null) {
                final String allocationUnits = rasdType.getAllocationUnits().getValue();

                final MemorySizeUnit ramSizeUnit = getMemoryUnitsFromOVF(allocationUnits);

                dReq.setRamSizeUnit(ramSizeUnit);
            }
        } else if (CIMResourceTypeEnum.Disk_Drive.getNumericResourceType() == resTnumeric) {
            // HD requirements are extracted from the associated Disk on ''hostResource''
            String diskId = getVirtualSystemDiskId(rasdType.getHostResource());

            if (!diskDescByName.containsKey(diskId)) {
                String msg = "DiskId [" + diskId + "] not found on disk section";
                throw new IdAlreadyExistsException(msg);
            }

            if (!diskIdToVSs.containsKey(diskId)) {
                List<String> vss = new LinkedList<String>();
                vss.add(vsystem.getId()); // XXX

                diskIdToVSs.put(diskId, vss);
            } else {
                diskIdToVSs.get(diskId).add(vsystem.getId());
            }

            VirtualDiskDescType diskDescType = diskDescByName.get(diskId);

            String capacity = diskDescType.getCapacity();

            dReq.setHd(Long.parseLong(capacity));

            final String allocationUnits = diskDescType.getCapacityAllocationUnits();
            final MemorySizeUnit hdSizeUnit = getMemoryUnitsFromOVF(allocationUnits);

            dReq.setHdSizeUnit(hdSizeUnit);
            // dReq.setImageSize(diskDescType.get);
        } else if (CIMResourceTypeEnum.Ethernet_Adapter.getNumericResourceType() == resTnumeric) {
            String ethDriver = null;
            EthernetDriverType ethDriverType = null;
            try {
                ethDriver = rasdType.getResourceSubType().getValue();
                ethDriverType = EthernetDriverType.valueOf(ethDriver);
            } catch (Exception e) {
                LOG.error("Invalid ethernet adapter type {}",
                        ethDriver != null ? ethDriver : "-ResourceSubType- not found");
            }

            if (dReq.getEthernetDriverType() != null && ethDriverType != null) {
                LOG.warn("Overwrite ethernet adapter type form {} to {}", dReq.getEthernetDriverType().name(),
                        ethDriverType.name());
            } else if (ethDriverType != null) {
                dReq.setEthernetDriverType(ethDriverType);
            }
        }
    } // rasd

    if (dReq.getCpu() == -1) {
        throw new RequiredAttributeException("Not CPU RASD element found on the envelope");
    }
    if (dReq.getRam() == -1) {
        throw new RequiredAttributeException("Not RAM RASD element found on the envelope");
    }
    if (dReq.getHd() == -1) {
        throw new RequiredAttributeException("Not HD RASD element found on the envelope");
    }

    return dReq;
}

From source file:uk.co.anthonycampbell.java.mp4reader.util.Util.java

/**
 * Convert the provided big integer time stamp to a date instance.
 * Time stamps in the MP4 specification resolve to the number of
 * seconds since 1904.//from   w w w  .j a  v  a2  s  . co m
 * 
 * @param bigInteger - big integer instance to convert.
 * @return date instance.
 */
public static Date generateDate(final BigInteger bigInteger) {
    // Validate
    if (bigInteger != null) {
        /*
         *  TODO If once upon a time we have a very LARGE time stamp
         *  this call will only return the lower order 64 bits.
         */
        final Calendar calendar = Calendar.getInstance();
        calendar.set(1904, Calendar.JANUARY, 1, 0, 0, 0);
        calendar.setTimeInMillis(calendar.getTimeInMillis() + (bigInteger.longValue() * 1000));
        return calendar.getTime();

    } else {
        throw new IllegalArgumentException(
                "Unable to generate date, provided argument is invalid! " + "(bigInteger=" + bigInteger + ")");
    }
}

From source file:com.guldencoin.androidwallet.nlg.ui.RequestCoinsFragment.java

private static byte[] createPaymentRequest(final BigInteger amount, @Nonnull final Address toAddress,
        final String memo, final String paymentUrl) {
    if (amount != null && amount.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0)
        throw new IllegalArgumentException("amount too big for protobuf: " + amount);

    final Protos.Output.Builder output = Protos.Output.newBuilder();
    output.setAmount(amount != null ? amount.longValue() : 0);
    output.setScript(ByteString.copyFrom(ScriptBuilder.createOutputScript(toAddress).getProgram()));

    final Protos.PaymentDetails.Builder paymentDetails = Protos.PaymentDetails.newBuilder();
    paymentDetails.setNetwork(Constants.NETWORK_PARAMETERS.getPaymentProtocolId());
    paymentDetails.addOutputs(output);//from   w  w  w .  j ava  2  s  .c  o  m
    if (memo != null)
        paymentDetails.setMemo(memo);
    if (paymentUrl != null)
        paymentDetails.setPaymentUrl(paymentUrl);
    paymentDetails.setTime(System.currentTimeMillis());

    final Protos.PaymentRequest.Builder paymentRequest = Protos.PaymentRequest.newBuilder();
    paymentRequest.setSerializedPaymentDetails(paymentDetails.build().toByteString());

    return paymentRequest.build().toByteArray();
}

From source file:com.bonsai.btcreceive.WalletService.java

static public long getDefaultFee() {
    final BigInteger dmtf = Transaction.REFERENCE_DEFAULT_MIN_TX_FEE;
    return dmtf.longValue();
}

From source file:uniol.apt.analysis.synthesize.SynthesizePN.java

private static long bigIntToLong(BigInteger value) {
    if (value.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0
            || value.compareTo(BigInteger.valueOf(Long.MIN_VALUE)) < 0)
        throw new ArithmeticException("Cannot represent value as long: " + value);
    return value.longValue();
}