List of usage examples for java.math BigInteger add
BigInteger add(long val)
From source file:password.pwm.config.stored.ConfigurationReader.java
public void saveConfiguration(final StoredConfigurationImpl storedConfiguration, final PwmApplication pwmApplication, final SessionLabel sessionLabel) throws IOException, PwmUnrecoverableException, PwmOperationalException { File backupDirectory = null;/*w w w .j a va2 s.c o m*/ int backupRotations = 0; if (pwmApplication != null) { final Configuration configuration = new Configuration(storedConfiguration); final String backupDirSetting = configuration.readAppProperty(AppProperty.BACKUP_LOCATION); if (backupDirSetting != null && backupDirSetting.length() > 0) { final File pwmPath = pwmApplication.getPwmEnvironment().getApplicationPath(); backupDirectory = FileSystemUtility.figureFilepath(backupDirSetting, pwmPath); } backupRotations = Integer.parseInt(configuration.readAppProperty(AppProperty.BACKUP_CONFIG_COUNT)); } { // increment the config epoch String epochStrValue = storedConfiguration.readConfigProperty(ConfigurationProperty.CONFIG_EPOCH); try { final BigInteger epochValue = epochStrValue == null || epochStrValue.length() < 0 ? BigInteger.ZERO : new BigInteger(epochStrValue); epochStrValue = epochValue.add(BigInteger.ONE).toString(); } catch (Exception e) { LOGGER.error(sessionLabel, "error trying to parse previous config epoch property: " + e.getMessage()); epochStrValue = "0"; } storedConfiguration.writeConfigProperty(ConfigurationProperty.CONFIG_EPOCH, epochStrValue); } if (backupDirectory != null && !backupDirectory.exists()) { if (!backupDirectory.mkdirs()) { throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_UNKNOWN, "unable to create backup directory structure '" + backupDirectory.toString() + "'")); } } try { final File tempWriteFile = new File(configFile.getAbsoluteFile() + ".new"); LOGGER.info(sessionLabel, "beginning write to configuration file " + tempWriteFile); saveInProgress = true; storedConfiguration.toXml(new FileOutputStream(tempWriteFile, false)); LOGGER.info("saved configuration " + JsonUtil.serialize(storedConfiguration.toJsonDebugObject())); if (pwmApplication != null) { final String actualChecksum = storedConfiguration.settingChecksum(); pwmApplication.writeAppAttribute(PwmApplication.AppAttribute.CONFIG_HASH, actualChecksum); } LOGGER.trace( "renaming file " + tempWriteFile.getAbsolutePath() + " to " + configFile.getAbsolutePath()); try { Files.move(tempWriteFile.toPath(), configFile.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } catch (Exception e) { final String errorMsg = "unable to rename temporary save file from " + tempWriteFile.getAbsolutePath() + " to " + configFile.getAbsolutePath() + "; error: " + e.getMessage(); throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg)); } if (backupDirectory != null) { final String configFileName = configFile.getName(); final String backupFilePath = backupDirectory.getAbsolutePath() + File.separatorChar + configFileName + "-backup"; final File backupFile = new File(backupFilePath); FileSystemUtility.rotateBackups(backupFile, backupRotations); storedConfiguration.toXml(new FileOutputStream(backupFile, false)); } } finally { saveInProgress = false; } }
From source file:org.multibit.utils.CSMiscUtils.java
public static String getDescriptionOfTransactionAssetChanges(Wallet wallet, Transaction tx) { if (wallet == null || tx == null) return ""; 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<String> nameAmounts = 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; }// ww w . j a v a 2 s . c o 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 = getDisplayUnitsForRawUnits(asset, netAmount); s1 = CSMiscUtils.getFormattedDisplayString(asset, displayUnits); } String s2 = name + ": " + s1; nameAmounts.add(s2); //break; // TODO: return the first asset we find, in future return map<Integer,BigInteger> } if (!nameAmounts.isEmpty()) { Collections.sort(nameAmounts); } BigInteger satoshiAmount = receiveMap.get(0); satoshiAmount = satoshiAmount.subtract(sendMap.get(0)); String btcAmount = Utils.bitcoinValueToFriendlyString(satoshiAmount); nameAmounts.add("BTC: " + btcAmount); String result = StringUtils.join(nameAmounts, ", "); // System.out.println(">>>> result = " + result); return result; }
From source file:org.techytax.digipoort.XbrlNtp8Helper.java
public void addBalanceData(VatDeclarationData vatDeclarationData, VatBalanceWithinEu vatBalanceWithinEu) throws Exception { BigInteger totaleKosten = AmountHelper.roundToInteger(vatBalanceWithinEu.getTotaleKosten()); BigInteger correction = AmountHelper.roundToInteger(vatBalanceWithinEu.getCorrection()); BigInteger turnover = vatBalanceWithinEu.getNettoOmzet(); BigInteger totaleBaten = AmountHelper.roundDownToInteger( new BigDecimal(turnover).multiply(BigDecimal.valueOf(VatType.HIGH.getValue(new Date())))); BigInteger vatOutEu = vatBalanceWithinEu.getVatOutEu(); BigInteger owed = totaleBaten.add(correction).add(vatOutEu); BigInteger owedToBePaidBack = owed.subtract(totaleKosten.add(vatOutEu)); vatDeclarationData.setValueAddedTaxOwed(owed); vatDeclarationData.setValueAddedTaxOnInput(totaleKosten.add(vatOutEu)); vatDeclarationData.setValueAddedTaxOwedToBePaidBack(owedToBePaidBack); vatDeclarationData.setValueAddedTaxPrivateUse(correction); vatDeclarationData.setValueAddedTaxSuppliesServicesGeneralTariff(totaleBaten); vatDeclarationData.setTaxedTurnoverSuppliesServicesGeneralTariff(turnover); vatDeclarationData//from w w w. j a v a 2 s. c om .setTurnoverFromTaxedSuppliesFromCountriesWithinTheEC(vatBalanceWithinEu.getTurnoverNetEu()); vatDeclarationData.setValueAddedTaxOnSuppliesFromCountriesWithinTheEC(vatOutEu); }
From source file:com.amazonaws.services.kinesis.clientlibrary.proxies.KinesisLocalFileProxy.java
/** * {@inheritDoc}//from w ww .j a va2 s. co m */ @Override public String getIterator(String shardId, String iteratorEnum, String sequenceNumber) throws ResourceNotFoundException, InvalidArgumentException { /* * If we don't have records in this shard, any iterator will return the empty list. Using a * sequence number of 1 on an empty shard will give this behavior. */ List<Record> shardRecords = shardedDataRecords.get(shardId); if (shardRecords == null) { throw new ResourceNotFoundException(shardId + " does not exist"); } if (shardRecords.isEmpty()) { return serializeIterator(shardId, "1"); } if (ShardIteratorType.LATEST.toString().equals(iteratorEnum)) { /* * If we do have records, LATEST should return an iterator that can be used to read the * last record. Our iterators are inclusive for convenience. */ Record last = shardRecords.get(shardRecords.size() - 1); return serializeIterator(shardId, last.getSequenceNumber()); } else if (ShardIteratorType.TRIM_HORIZON.toString().equals(iteratorEnum)) { return serializeIterator(shardId, shardRecords.get(0).getSequenceNumber()); } else if (ShardIteratorType.AT_SEQUENCE_NUMBER.toString().equals(iteratorEnum)) { return serializeIterator(shardId, sequenceNumber); } else if (ShardIteratorType.AFTER_SEQUENCE_NUMBER.toString().equals(iteratorEnum)) { BigInteger num = new BigInteger(sequenceNumber); num = num.add(BigInteger.ONE); return serializeIterator(shardId, num.toString()); } else { throw new IllegalArgumentException("IteratorEnum value was invalid: " + iteratorEnum); } }
From source file:org.jcryptool.visual.verifiablesecretsharing.views.ReconstructionChartComposite.java
private XYDataset createDataset() { final XYSeries playerAndSharesSeries = new XYSeries("Shares"); final XYSeries reconstructionSeries = new XYSeries("Reconstructed Polynom"); final XYSeries secretSeries = new XYSeries("Secret"); BigInteger[] coef = reconstructedPolynom.getCoef(); BigInteger y = BigInteger.ZERO; for (int i = 0; i < playerID.length && playerID[i] != 0; i++) { playerAndSharesSeries.add(playerID[i], shares[i]); }//from www. j ava 2 s. c o m for (int i = 0; i <= playerID[playerID.length - 1]; i++) { for (int j = 0; j < coef.length; j++) { y = y.add(coef[j].multiply(new BigInteger(i + "").pow(j))); } reconstructionSeries.add(i, y); y = BigInteger.ZERO; } secretSeries.add(0, secret); final XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(playerAndSharesSeries); dataset.addSeries(reconstructionSeries); dataset.addSeries(secretSeries); return dataset; }
From source file:com.stratio.cassandra.lucene.schema.mapping.BigIntegerMapper.java
/** {@inheritDoc} */ @Override/*from w ww . j ava2 s . c om*/ protected String doBase(String name, Object value) { // Parse big decimal String svalue = value.toString(); BigInteger bi; try { bi = new BigInteger(svalue); } catch (NumberFormatException e) { throw new IndexException("Field '%s' requires a base 10 integer, but found '%s'", name, svalue); } // Check size if (bi.abs().toString().length() > digits) { throw new IndexException("Field '%s' with value '%s' has more than %d digits", name, value, digits); } // Map bi = bi.add(complement); String bis = encode(bi); return StringUtils.leftPad(bis, hexDigits + 1, '0'); }
From source file:org.opendaylight.neutron.spi.NeutronSubnet.java
@Override public void initDefaults() { if (enableDHCP == null) { enableDHCP = true;// w ww. j av a2s .co m } if (ipVersion == null) { ipVersion = IPV4_VERSION; } if (dnsNameservers == null) { dnsNameservers = new ArrayList<String>(); } if (hostRoutes == null) { hostRoutes = new ArrayList<NeutronRoute>(); } if (allocationPools == null) { allocationPools = new ArrayList<NeutronSubnetIpAllocationPool>(); 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; } } if (ipVersion == IPV6_VERSION) { String[] parts = cidr.split("/"); if (parts.length != 2) { return; } int length = Integer.parseInt(parts[1]); BigInteger lowAddressBi = NeutronSubnetIpAllocationPool.convertV6(parts[0]); String lowAddress = NeutronSubnetIpAllocationPool.bigIntegerToIp(lowAddressBi.add(BigInteger.ONE)); BigInteger mask = BigInteger.ONE.shiftLeft(length).subtract(BigInteger.ONE); String highAddress = NeutronSubnetIpAllocationPool .bigIntegerToIp(lowAddressBi.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); } } } }
From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java
private BigInteger step2cComputeLowerBound(final BigInteger r, final BigInteger modulus, final BigInteger upperIntervalBound) { BigInteger lowerBound = BigInteger.valueOf(2).multiply(this.bigB); lowerBound = lowerBound.add(r.multiply(modulus)); lowerBound = lowerBound.divide(upperIntervalBound); return lowerBound; }
From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java
private BigInteger step2cComputeUpperBound(final BigInteger r, final BigInteger modulus, final BigInteger lowerIntervalBound) { BigInteger upperBound = BigInteger.valueOf(3).multiply(this.bigB); upperBound = upperBound.add(r.multiply(modulus)); upperBound = upperBound.divide(lowerIntervalBound); return upperBound; }
From source file:com.stratio.cassandra.index.schema.ColumnMapperBigInteger.java
/** {@inheritDoc} */ @Override/*from w w w . j a v a2 s . co m*/ public String indexValue(String name, Object value) { // Check not null if (value == null) { return null; } // Parse big decimal String svalue = value.toString(); BigInteger bi; try { bi = new BigInteger(svalue); } catch (NumberFormatException e) { String message = String.format("Field %s requires a base 10 integer, but found \"%s\"", name, svalue); throw new IllegalArgumentException(message); } // Check size if (bi.abs().toString().length() > digits) { throw new IllegalArgumentException("Value has more than " + digits + " digits"); } // Map bi = bi.add(complement); String bis = encode(bi); return StringUtils.leftPad(bis, hexDigits + 1, '0'); }