List of usage examples for java.math BigInteger add
BigInteger add(long val)
From source file:com.buildabrand.gsb.util.URLUtils.java
private String convertIpAddress(String ipAddr) { String[] ipAddrSplit = StringUtils.split(ipAddr, '.'); if (ipAddrSplit.length == 0 || ipAddrSplit.length > 4) { return null; }//from www . ja v a 2s . c om // Basically we should parse octal if we can, but if there are illegal octal // numbers, i.e. 08 or 09, then we should just look at decimal and hex. boolean allowOctal = !FIND_BAD_OCTAL_REGEXP.matcher(ipAddr).find(); BigInteger ipNumeric = BigInteger.ZERO; int i = 0; while (i < ipAddrSplit.length - 1) { ipNumeric = ipNumeric.shiftLeft(8); BigInteger componentBigInt = convertComponent(ipAddrSplit[i], allowOctal); if (componentBigInt == null) { return null; } ipNumeric = ipNumeric.add(componentBigInt); i++; } while (i < 4) { ipNumeric = ipNumeric.shiftLeft(8); i++; } BigInteger componentBigInt = convertComponent(ipAddrSplit[ipAddrSplit.length - 1], allowOctal); if (componentBigInt == null) { return null; } ipNumeric = ipNumeric.add(componentBigInt); return InetAddresses.fromInteger((ipNumeric.intValue())).getHostAddress(); }
From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java
private BigInteger step3ComputeLowerBound(final BigInteger s, final BigInteger modulus, final BigInteger lowerIntervalBound) { BigInteger lowerBound = lowerIntervalBound.multiply(s); lowerBound = lowerBound.subtract(BigInteger.valueOf(3).multiply(this.bigB)); lowerBound = lowerBound.add(BigInteger.ONE); lowerBound = lowerBound.divide(modulus); return lowerBound; }
From source file:org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet.java
public boolean initDefaults() { if (enableDHCP == null) { enableDHCP = true;/*from w w w.j ava 2s . c om*/ } if (ipVersion == null) { ipVersion = IPV4_VERSION; } dnsNameservers = new ArrayList<>(); if (hostRoutes == null) { hostRoutes = new ArrayList<>(); } if (allocationPools == null) { allocationPools = new ArrayList<>(); if (ipVersion == IPV4_VERSION) { try { SubnetUtils util = new SubnetUtils(cidr); SubnetInfo info = util.getInfo(); if (gatewayIP == null || ("").equals(gatewayIP)) { gatewayIP = info.getLowAddress(); } if (allocationPools.size() < 1) { NeutronSubnetIPAllocationPool source = new NeutronSubnetIPAllocationPool( info.getLowAddress(), info.getHighAddress()); allocationPools = source.splitPool(gatewayIP); } } catch (IllegalArgumentException e) { LOGGER.warn("Failure in initDefault()", e); return false; } } if (ipVersion == IPV6_VERSION) { String[] parts = cidr.split("/"); if (parts.length != 2) { return false; } try { int length = Integer.parseInt(parts[1]); BigInteger lowAddress_bi = NeutronSubnetIPAllocationPool.convertV6(parts[0]); String lowAddress = NeutronSubnetIPAllocationPool .bigIntegerToIP(lowAddress_bi.add(BigInteger.ONE)); BigInteger mask = BigInteger.ONE.shiftLeft(length).subtract(BigInteger.ONE); String highAddress = NeutronSubnetIPAllocationPool .bigIntegerToIP(lowAddress_bi.add(mask).subtract(BigInteger.ONE)); if (gatewayIP == null || ("").equals(gatewayIP)) { gatewayIP = lowAddress; } if (allocationPools.size() < 1) { NeutronSubnetIPAllocationPool source = new NeutronSubnetIPAllocationPool(lowAddress, highAddress); allocationPools = source.splitPoolV6(gatewayIP); } } catch (Exception e) { LOGGER.warn("Failure in initDefault()", e); return false; } } } return true; }
From source file:com.cloud.utils.net.NetUtils.java
public static String getIp6FromRange(final String ip6Range) { final String[] ips = ip6Range.split("-"); final String startIp = ips[0]; final IPv6Address start = IPv6Address.fromString(startIp); final BigInteger gap = countIp6InRange(ip6Range); BigInteger next = new BigInteger(gap.bitLength(), s_rand); while (next.compareTo(gap) >= 0) { next = new BigInteger(gap.bitLength(), s_rand); }//w w w . j a va2s.c o m InetAddress resultAddr = null; final BigInteger startInt = convertIPv6AddressToBigInteger(start); if (startInt != null) { final BigInteger resultInt = startInt.add(next); try { resultAddr = InetAddress.getByAddress(resultInt.toByteArray()); } catch (final UnknownHostException e) { return null; } } if (resultAddr != null) { final IPv6Address ip = IPv6Address.fromInetAddress(resultAddr); return ip.toString(); } return null; }
From source file:org.apache.blur.command.BaseCommandManager.java
protected BigInteger checkContents(FileStatus fileStatus, FileSystem fileSystem) throws IOException { if (fileStatus.isDir()) { LOG.debug("Scanning directory [{0}].", fileStatus.getPath()); BigInteger count = BigInteger.ZERO; Path path = fileStatus.getPath(); FileStatus[] listStatus = fileSystem.listStatus(path); for (FileStatus fs : listStatus) { count = count.add(checkContents(fs, fileSystem)); }/*from w w w . ja va2s. c o m*/ return count; } else { int hashCode = fileStatus.getPath().toString().hashCode(); long modificationTime = fileStatus.getModificationTime(); long len = fileStatus.getLen(); BigInteger bi = BigInteger.valueOf(hashCode) .add(BigInteger.valueOf(modificationTime).add(BigInteger.valueOf(len))); LOG.debug("File path hashcode [{0}], mod time [{1}], len [{2}] equals file code [{3}].", Integer.toString(hashCode), Long.toString(modificationTime), Long.toString(len), bi.toString(Character.MAX_RADIX)); return bi; } }
From source file:org.ethereum.core.Block.java
public BigInteger getCumulativeDifficulty() { if (!parsed)/*from w w w .j a v a 2 s . co m*/ parseRLP(); BigInteger calcDifficulty = new BigInteger(1, this.header.getDifficulty()); for (BlockHeader uncle : uncleList) { calcDifficulty = calcDifficulty.add(new BigInteger(1, uncle.getDifficulty())); } return calcDifficulty; }
From source file:piuk.blockchain.android.ui.dialogs.TransactionSummaryDialog.java
@Override public Dialog onCreateDialog(final Bundle savedInstanceState) { super.onCreateDialog(savedInstanceState); final FragmentActivity activity = getActivity(); final LayoutInflater inflater = LayoutInflater.from(activity); final Builder dialog = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.Theme_Dialog)) .setTitle(R.string.transaction_summary_title); final LinearLayout view = (LinearLayout) inflater.inflate(R.layout.transaction_summary_fragment, null); dialog.setView(view);// w ww . j a v a 2s. c o m try { final MyRemoteWallet wallet = application.getRemoteWallet(); BigInteger totalOutputValue = BigInteger.ZERO; for (TransactionOutput output : tx.getOutputs()) { totalOutputValue = totalOutputValue.add(output.getValue()); } final TextView resultDescriptionView = (TextView) view.findViewById(R.id.result_description); final TextView toView = (TextView) view.findViewById(R.id.transaction_to); final TextView toViewLabel = (TextView) view.findViewById(R.id.transaction_to_label); final View toViewContainer = (View) view.findViewById(R.id.transaction_to_container); final TextView hashView = (TextView) view.findViewById(R.id.transaction_hash); final TextView transactionTimeView = (TextView) view.findViewById(R.id.transaction_date); final TextView confirmationsView = (TextView) view.findViewById(R.id.transaction_confirmations); final TextView noteView = (TextView) view.findViewById(R.id.transaction_note); final Button addNoteButton = (Button) view.findViewById(R.id.add_note_button); final TextView feeView = (TextView) view.findViewById(R.id.transaction_fee); final View feeViewContainer = view.findViewById(R.id.transaction_fee_container); final TextView valueNowView = (TextView) view.findViewById(R.id.transaction_value); final View valueNowContainerView = view.findViewById(R.id.transaction_value_container); String to = null; for (TransactionOutput output : tx.getOutputs()) { try { String toAddress = output.getScriptPubKey().getToAddress().toString(); if (!wallet.isAddressMine(toAddress)) { to = toAddress; } } catch (Exception e) { e.printStackTrace(); } } String from = null; for (TransactionInput input : tx.getInputs()) { try { String fromAddress = input.getFromAddress().toString(); if (!wallet.isAddressMine(fromAddress)) { from = fromAddress; } } catch (Exception e) { e.printStackTrace(); } } long realResult = 0; int confirmations = 0; if (tx instanceof MyTransaction) { MyTransaction myTx = (MyTransaction) tx; realResult = myTx.getResult().longValue(); if (wallet.getLatestBlock() != null) { confirmations = wallet.getLatestBlock().getHeight() - myTx.getHeight() + 1; } } else if (application.isInP2PFallbackMode()) { realResult = tx.getValue(application.bitcoinjWallet).longValue(); if (tx.getConfidence().getConfidenceType() == ConfidenceType.BUILDING) confirmations = tx.getConfidence().getDepthInBlocks(); } final long finalResult = realResult; if (realResult <= 0) { toViewLabel.setText(R.string.transaction_fragment_to); if (to == null) { ((LinearLayout) toViewContainer.getParent()).removeView(toViewContainer); } else { toView.setText(to); } } else { toViewLabel.setText(R.string.transaction_fragment_from); if (from == null) { ((LinearLayout) toViewContainer.getParent()).removeView(toViewContainer); } else { toView.setText(from); } } //confirmations view if (confirmations > 0) { confirmationsView.setText("" + confirmations); } else { confirmationsView.setText("Unconfirmed"); } //Hash String view final String hashString = new String(Hex.encode(tx.getHash().getBytes()), "UTF-8"); hashView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https:/" + Constants.BLOCKCHAIN_DOMAIN + "/tx/" + hashString)); startActivity(browserIntent); } }); //Notes View String note = wallet.getTxNotes().get(hashString); if (note == null) { addNoteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dismiss(); AddNoteDialog.showDialog(getFragmentManager(), hashString); } }); view.removeView(noteView); } else { view.removeView(addNoteButton); noteView.setText(note); noteView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dismiss(); AddNoteDialog.showDialog(getFragmentManager(), hashString); } }); } addNoteButton.setEnabled(!application.isInP2PFallbackMode()); SpannableString content = new SpannableString(hashString); content.setSpan(new UnderlineSpan(), 0, content.length(), 0); hashView.setText(content); if (realResult > 0 && from != null) resultDescriptionView.setText(this.getString(R.string.transaction_fragment_amount_you_received, WalletUtils.formatValue(BigInteger.valueOf(realResult)))); else if (realResult < 0 && to != null) resultDescriptionView.setText(this.getString(R.string.transaction_fragment_amount_you_sent, WalletUtils.formatValue(BigInteger.valueOf(realResult)))); else resultDescriptionView.setText(this.getString(R.string.transaction_fragment_amount_you_moved, WalletUtils.formatValue(totalOutputValue))); final Date time = tx.getUpdateTime(); transactionTimeView.setText(dateFormat.format(time)); //These will be made visible again later once information is fetched from server feeViewContainer.setVisibility(View.GONE); valueNowContainerView.setVisibility(View.GONE); if (tx instanceof MyTransaction) { MyTransaction myTx = (MyTransaction) tx; final long txIndex = myTx.getTxIndex(); final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { try { final JSONObject obj = getTransactionSummary(txIndex, wallet.getGUID(), finalResult); handler.post(new Runnable() { @Override public void run() { try { if (obj.get("fee") != null) { feeViewContainer.setVisibility(View.VISIBLE); feeView.setText(WalletUtils.formatValue( BigInteger.valueOf(Long.valueOf(obj.get("fee").toString()))) + " BTC"); } if (obj.get("confirmations") != null) { int confirmations = ((Number) obj.get("confirmations")).intValue(); confirmationsView.setText("" + confirmations); } String result_local = (String) obj.get("result_local"); String result_local_historical = (String) obj .get("result_local_historical"); if (result_local != null && result_local.length() > 0) { valueNowContainerView.setVisibility(View.VISIBLE); if (result_local_historical == null || result_local_historical.length() == 0 || result_local_historical.equals(result_local)) { valueNowView.setText(result_local); } else { valueNowView.setText(getString(R.string.value_now_ten, result_local, result_local_historical)); } } } catch (Exception e) { e.printStackTrace(); } } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); } } catch (Exception e) { e.printStackTrace(); } Dialog d = dialog.create(); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.dimAmount = 0; lp.width = WindowManager.LayoutParams.FILL_PARENT; lp.height = WindowManager.LayoutParams.WRAP_CONTENT; d.show(); d.getWindow().setAttributes(lp); d.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); return d; }
From source file:org.limewire.mojito.util.DHTSizeEstimator.java
/** * Computes and returns the approximate DHT size based * on the given List of Contacts./* w ww . j a va 2 s .c o m*/ */ public synchronized BigInteger computeSize(Collection<? extends Contact> nodes) { // Works only with more than two Nodes if (nodes.size() < MIN_NODE_COUNT) { // There's always us! return BigInteger.ONE.max(BigInteger.valueOf(nodes.size())); } // Get the Iterator. We assume the Contacts are sorted by // their xor distance! Iterator<? extends Contact> contacts = nodes.iterator(); // See Azureus DHTControlImpl.estimateDHTSize() // Di = nearestId xor NodeIDi // Dc = sum(i * Di) / sum(i * i) // Size = 2**160 / Dc BigInteger sum1 = BigInteger.ZERO; BigInteger sum2 = BigInteger.ZERO; // The algorithm works relative to the ID space. KUID nearestId = contacts.next().getNodeID(); // We start 1 because the nearest Node is the 0th item! for (int i = 1; contacts.hasNext(); i++) { Contact node = contacts.next(); BigInteger distance = nearestId.xor(node.getNodeID()).toBigInteger(); BigInteger j = BigInteger.valueOf(i); sum1 = sum1.add(j.multiply(distance)); sum2 = sum2.add(j.pow(2)); } BigInteger estimatedSize = BigInteger.ZERO; if (!sum1.equals(BigInteger.ZERO)) { estimatedSize = KUID.MAXIMUM.toBigInteger().multiply(sum2).divide(sum1); } // And there is always us! estimatedSize = BigInteger.ONE.max(estimatedSize); // Get the average of the local estimations BigInteger localSize = BigInteger.ZERO; localSizeHistory.add(estimatedSize); // Adjust the size of the List. The Setting is SIMPP-able // and may change! int maxLocalHistorySize = ContextSettings.MAX_LOCAL_HISTORY_SIZE.getValue(); while (localSizeHistory.size() > maxLocalHistorySize && !localSizeHistory.isEmpty()) { localSizeHistory.remove(0); } if (!localSizeHistory.isEmpty()) { BigInteger localSizeSum = BigInteger.ZERO; for (BigInteger size : localSizeHistory) { localSizeSum = localSizeSum.add(size); } localSize = localSizeSum.divide(BigInteger.valueOf(localSizeHistory.size())); } // Get the combined average // S = (localEstimation + sum(remoteEstimation[i]))/count BigInteger combinedSize = localSize; if (ContextSettings.COUNT_REMOTE_SIZE.getValue()) { // Prune all duplicates and sort the values Set<BigInteger> remoteSizeSet = new TreeSet<BigInteger>(remoteSizeHistory); if (remoteSizeSet.size() >= 3) { BigInteger[] remote = remoteSizeSet.toArray(new BigInteger[0]); // Skip the smallest and largest values int count = 1; int skip = ContextSettings.SKIP_REMOTE_ESTIMATES.getValue(); for (int i = skip; (skip >= 0) && (i < (remote.length - skip)); i++) { combinedSize = combinedSize.add(remote[i]); count++; } combinedSize = combinedSize.divide(BigInteger.valueOf(count)); // Make sure we didn't exceed the MAXIMUM number as // we made an addition with the local estimation which // might be already 2**160 bit! combinedSize = combinedSize.min(MAXIMUM); } } // There is always us! return BigInteger.ONE.max(combinedSize); }
From source file:models.persistence.lecture.Lecture.java
/** * calculate cost of this lecture/* w ww . j av a 2 s . c om*/ * the more costs a lecture have it will be more important to place it first */ @JsonIgnore public BigInteger getDifficulty() { BigInteger ret = BigInteger.ZERO; if (criteriaContainer != null) { ret = ret.add(BigInteger.valueOf(criteriaContainer.calculateDifficultLevel())); } if (docents != null) { ret = ret.add(BigInteger.valueOf(docents.parallelStream() .mapToLong(d -> d.getCriteriaContainer().calculateDifficultLevel()).sum())); } if (participants != null) { ret = ret.add(BigInteger.valueOf(participants.size())); } ret = ret.add(BigInteger.valueOf(calculateNumberOfParticipants())); ret = ret.add(difficultLevel); ret = ret.add(BigInteger.valueOf(duration.getSortIndex())); return ret; }
From source file:org.ow2.aspirerfid.demos.warehouse.management.beg.CaptureReport.java
private void handleReports(ECReports reports) throws IOException, JAXBException { log.debug("**********************Handling incomming reports****************************"); // get the current time and set the eventTime XMLGregorianCalendar now = null; try {/* w w w . j a v a2s . c o m*/ DatatypeFactory dataFactory = DatatypeFactory.newInstance(); now = dataFactory.newXMLGregorianCalendar(new GregorianCalendar()); log.debug("Event Time:" + now.getHour() + ":" + now.getMinute() + ":" + ":" + now.getSecond() + "\n"); } catch (DatatypeConfigurationException e) { e.printStackTrace(); } List<ECReport> theReports = reports.getReports().getReport(); // collect all the tags List<EPC> epcs = new LinkedList<EPC>(); if (theReports != null) { for (ECReport report : theReports) { // log.debug("Report Count: "+report.getGroup().size()); log.debug("***************Report Name:" + report.getReportName() + "**************"); if (report.getGroup() != null) { for (ECReportGroup group : report.getGroup()) { if (WarehouseManagement.getEntryDateTextField().equals("")) { WarehouseManagement.setEntryDateTextField( now.getDay() + "/" + now.getMonth() + "/" + now.getYear()); } if (WarehouseManagement.getEntryHourTextField().equals("")) { WarehouseManagement.setEntryHourTextField( now.getHour() + ":" + now.getMinute() + ":" + now.getSecond()); } WarehouseManagement.setZoneIDTextField(zoneID); WarehouseManagement.setWarehouseIDTextField(warehouseID); log.debug("Group Count: " + group.getGroupCount().getCount()); log.debug("Group Name: " + group.getGroupName()); if (group.getGroupList() != null) { deliveredItem = null; // warehousemen if (group.getGroupName().equals(warehousemenGroupName)) { for (ECReportGroupListMember member : group.getGroupList().getMember()) { if (member.getEpc() != null) { WarehouseManagement .setUserIDTextField(member.getTag().getValue().split(":")[4]); } } } // Invoice if (group.getGroupName().equals(invoiceGroupName)) { for (ECReportGroupListMember member : group.getGroupList().getMember()) { if (member.getEpc() != null) { WarehouseManagement .setInvoiceIDTextField(member.getTag().getValue().split(":")[4]); WarehouseManagement.setOfferingDateTextField("22/05/08"); WarehouseManagement.setOfferingHourTextField("10:53:22"); } } } // // Small Packets // if (group.getGroupName().equals("urn:epc:pat:gid-96:145.56.*")) { // for (ECReportGroupListMember member : group.getGroupList().getMember()) { // if (member.getEpc() != null) { // // WarehouseManagement.setInvoiceIDTextField(member.getTag().getValue().split(":")[4]); // } // } // } // // Medium Packets // if (group.getGroupName().equals("urn:epc:pat:gid-96:145.87.*")) { // for (ECReportGroupListMember member : group.getGroupList().getMember()) { // if (member.getEpc() != null) { // // WarehouseManagement.setInvoiceIDTextField(member.getTag().getValue().split(":")[4]); // } // } // } for (int i = 0; i < nOFmerchandise; i++) { if (group.getGroupName().equals(packetsGroupName[i])) { BigInteger quantity = new BigInteger(packetsQuantity[i]); BigInteger expectedQuantity = new BigInteger(packetsExpectedQuantity[i]); BigInteger quantityDelivered = new BigInteger( (group.getGroupCount().getCount()) + ""); BigInteger quantityRemain = quantity.add(quantityDelivered.negate()); for (ECReportGroupListMember member : group.getGroupList().getMember()) { if (member.getEpc() != null) { deliveredItem = new DeliveredItem(); deliveredItem.setCompany(packetsCompany[i]); deliveredItem.setDeliveryDate( now.getDay() + "/" + now.getMonth() + "/" + now.getYear()); deliveredItem.setDescription(packetsDescription[i]); deliveredItem.setExpectedQuantity(expectedQuantity); deliveredItem.setMeasurementID(packetsMeasurementID[i]); deliveredItem.setQuantity(quantity); deliveredItem.setQuantityDelivered(quantityDelivered); deliveredItem.setQuantityRemain(quantityRemain); deliveredItem.setItemCode(member.getTag().getValue().split(":")[4]); WarehouseManagement.updateDeliveryTableModel(deliveredItem); deliveredItem = null; } } } } // Print All for (ECReportGroupListMember member : group.getGroupList().getMember()) { if (member.getEpc() != null) { log.debug("***Recieved Group Values***"); log.debug("RawDecimal Value: " + member.getRawDecimal().getValue()); { if (!(member.getEpc() == null)) epcs.add(member.getEpc()); log.debug("Epc Value: " + member.getEpc().getValue()); if ((member.getEpc() == null)) log.debug("Epc Value: null"); } log.debug("RawHex Value: " + member.getRawHex().getValue()); log.debug("Tag Value: " + member.getTag().getValue()); // log.debug("Group // Value:"+member.getExtension().getFieldList().toString()); } } } } } } } if (epcs.size() == 0) { log.debug("no epc received - generating no event"); return; } }