List of usage examples for java.math BigInteger equals
public boolean equals(Object x)
From source file:org.springframework.cloud.consul.bus.EventService.java
/** * from https://github.com/hashicorp/consul/blob/master/watch/funcs.go#L169-L194 *//* w ww . ja v a2 s .com*/ protected List<Event> filterEvents(List<Event> toFilter, BigInteger lastIndex) { List<Event> events = toFilter; if (lastIndex != null) { for (int i = 0; i < events.size(); i++) { Event event = events.get(i); BigInteger eventIndex = toIndex(event.getId()); if (eventIndex.equals(lastIndex)) { events = events.subList(i + 1, events.size()); break; } } } return events; }
From source file:gov.nih.nci.caarray.security.SecurityUtils.java
private static Map<Long, Privileges> createPrivilegesMapFromResults(List<Object[]> results) { final Map<Long, Privileges> permissionsMap = new HashMap<Long, Privileges>(); BigInteger currId = null;//from ww w . j av a 2 s . co m Privileges perm = null; for (final Object[] result : results) { final BigInteger id = (BigInteger) result[0]; final String privilegeName = (String) result[1]; if (!id.equals(currId)) { currId = id; perm = new Privileges(); permissionsMap.put(currId.longValue(), perm); } perm.getPrivilegeNames().add(privilegeName); } return permissionsMap; }
From source file:com.ntsync.android.sync.client.NetworkUtilities.java
@SuppressLint("TrulyRandom") private static Pair<String, byte[]> authenticate(Context context, String username, String password, byte[] srpPassword) throws NetworkErrorException, ServerException { LogHelper.logD(TAG, "Authenticating to: {}", AUTH1_URI); if (username == null) { Log.e(TAG, "Username or password is null."); return null; }//from www. java2s.com if (password == null && srpPassword == null) { Log.e(TAG, "Either password or srpPassword is needed."); } Pair<String, byte[]> returnData = null; try { // Step 1 byte[] content = sendAuthStep1(context, username); int pwdSaltLen = SRP6Helper.PWD_SALT_LENGTH; if (content == null || content.length <= INT_LEN + pwdSaltLen) { Log.i(TAG, "Authentification failed."); return null; } int index = 0; byte[] pwdSalt = new byte[pwdSaltLen]; System.arraycopy(content, index, pwdSalt, 0, pwdSaltLen); index += pwdSaltLen; int len = SyncDataHelper.readInt(content, index); index += INT_LEN; if (len + index >= content.length) { Log.i(TAG, "Invalid datastructure. "); return null; } byte[] salt = new byte[len]; System.arraycopy(content, index, salt, 0, salt.length); index += len; byte[] serverB = new byte[content.length - index]; System.arraycopy(content, index, serverB, 0, serverB.length); byte[] validSRPPassword = srpPassword; if (validSRPPassword == null) { validSRPPassword = SRP6Helper.createSRPPassword(password, pwdSalt); } // Step 2 BigInteger srpB = new BigInteger(1, serverB); SRP6Client srpClient = new SRP6Client(); Digest srpHashFn = SRP6Helper.createDigest(); srpClient.init(SRP6Helper.N_2024, SRP6Helper.G_2024, srpHashFn, new SecureRandom()); BigInteger srpA = srpClient.generateClientCredentials(salt, username.getBytes("UTF-8"), validSRPPassword); BigInteger clientS = srpClient.calculateSecret(srpB); BigInteger srpK = SRP6Helper.createHash(srpHashFn, clientS); BigInteger clientM = SRP6Helper.createClientM(srpHashFn, username, new BigInteger(1, salt), srpA, srpB, srpK); // Send Proof of Session and get Session-Id and Session-Prof of // Server content = sendAuthStep2(context, clientM, username, srpA); if (content == null || content.length == 0) { Log.i(TAG, "Authentification failed."); return null; } len = SyncDataHelper.readInt(content, 0); if (len + INT_LEN >= content.length) { Log.i(TAG, "Invalid datastructure. "); return null; } byte[] sessionId = new byte[len]; System.arraycopy(content, INT_LEN, sessionId, 0, sessionId.length); byte[] serverMByte = new byte[content.length - INT_LEN - sessionId.length]; System.arraycopy(content, INT_LEN + sessionId.length, serverMByte, 0, serverMByte.length); String authtoken = new String(sessionId, SyncDataHelper.DEFAULT_CHARSET_NAME); BigInteger verifServerM = SRP6Helper.createServerM(SRP6Helper.createDigest(), srpA, clientM, srpK); BigInteger serverM = new BigInteger(1, serverMByte); if (!verifServerM.equals(serverM)) { Log.i(TAG, "Server verification failed. CalcServerM:" + verifServerM + " ServerM:" + verifServerM); authtoken = null; } else if ((authtoken != null) && (authtoken.length() > 0)) { Log.v(TAG, "Successful authentication"); } else { Log.i(TAG, "Error authenticating. Authtoken:" + authtoken); authtoken = null; } if (authtoken != null) { returnData = new Pair<String, byte[]>(authtoken, validSRPPassword); } } catch (CryptoException e) { LogHelper.logWCause(TAG, "Invalid server credentials", e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("No support for UTF-8 available.", e); } return returnData; }
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;/*from w w w .j a v a2 s . com*/ // 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; } 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:com.boldust.math001.Math001Test.java
/** * Test of pow001 method, of class Math001. *//*from ww w .ja va 2 s .c o m*/ @Test public void testPow001() { System.out.println("pow001"); Logger l = Logger.getLogger("powtest001"); // l.addHandler(new java.util.logging.ConsoleHandler()); l.log(Level.SEVERE, "Powtest001"); int base = 20; int exp = 5; BigInteger expResult = new BigInteger(Integer.valueOf(3200000).toString()); BigInteger result1 = new BigInteger(Integer.valueOf(3200000).toString()); BigInteger result = Math001.pow001(base, exp); System.out.println(expResult.equals(result)); assertEquals(expResult, result); assertEquals(result1, result); // TODO review the generated test code and remove the default call to fail. //fail("The test case is a prototype."); }
From source file:com.spotify.cassandra.opstools.autobalance.Main.java
private void run(CommandLine cmd) throws IOException, InterruptedException { boolean dryrun = cmd.hasOption("d"); boolean force = cmd.hasOption("f"); boolean noresolve = cmd.hasOption("r"); int port = cmd.hasOption("p") ? Integer.parseInt(cmd.getOptionValue("p")) : 7199; String nodehost = cmd.hasOption("h") ? cmd.getOptionValue("h") : "localhost"; System.out.println("Collecting information about the cluster..."); NodeProbe nodeProbe = new NodeProbe(nodehost, port); if (nodeProbe.getTokens().size() != 1) { System.err.println("Cluster is using vnodes and should already be automatically balanced!"); System.exit(1);/*from ww w .j a va2s .c o m*/ } boolean hasData = false; if (!dryrun) { Map<String, String> loadMap = nodeProbe.getLoadMap(); for (String s : loadMap.values()) { if (s.contains("KB")) continue; if (s.contains("MB") || s.contains("GB") || s.contains("TB")) { hasData = true; continue; } throw new RuntimeException("Unknown suffix in load map; don't dare to continue"); } } String partitioner = nodeProbe.getPartitioner(); BigInteger minToken, maxToken; if (partitioner.equals(RandomPartitioner.class.getName())) { minToken = RandomPartitioner.ZERO; maxToken = RandomPartitioner.MAXIMUM; } else if (partitioner.equals(Murmur3Partitioner.class.getName())) { minToken = BigInteger.valueOf(Murmur3Partitioner.MINIMUM.token); maxToken = BigInteger.valueOf(Murmur3Partitioner.MAXIMUM); } else { throw new RuntimeException("Unsupported partitioner: " + partitioner); } // Get current mapping of all live nodes List<String> liveNodes = nodeProbe.getLiveNodes(); Map<String, BigInteger> hostTokenMap = new HashMap<String, BigInteger>(); Map<String, String> hostDcMap = new HashMap<String, String>(); for (String host : liveNodes) { String dc = nodeProbe.getEndpointSnitchInfoProxy().getDatacenter(host); String decoratedHost = host; if (!noresolve) { // Prefix host with canonical host name. // This makes things prettier and also causes tokens to be assigned in logical order. decoratedHost = InetAddress.getByName(host).getCanonicalHostName() + "/" + host; } else { decoratedHost = "/" + host; } hostDcMap.put(decoratedHost, dc); List<String> tokens = nodeProbe.getTokens(host); if (tokens.size() > 1) { throw new RuntimeException("vnodes not supported"); } if (tokens.size() == 0) { throw new RuntimeException("No token for " + host + "; aborting"); } hostTokenMap.put(decoratedHost, new BigInteger(tokens.get(0))); } Balancer balancer = new Balancer(hostTokenMap, hostDcMap, minToken, maxToken); Map<String, BigInteger> newMap = balancer.balance(); List<Operation> operations = new ArrayList<Operation>(); boolean movesNeeded = false; for (Map.Entry<String, BigInteger> entry : hostTokenMap.entrySet()) { String host = entry.getKey(); BigInteger oldToken = entry.getValue(); BigInteger newToken = newMap.get(host); if (!oldToken.equals(newToken)) { movesNeeded = true; } operations.add(new Operation(host, hostDcMap.get(host), oldToken, newToken)); } if (movesNeeded && hasData && !dryrun && !force) { dryrun = true; System.out.println( "The cluster is unbalanced but has data, so no operations will actually be carried out. Use --force if you want the cluster to balance anyway."); } Collections.sort(operations); boolean unbalanced = false, moved = false; for (Operation op : operations) { if (op.oldToken.equals(op.newToken)) { System.out.println(op.host + ": Stays on token " + op.oldToken); } else { System.out.println(op.host + ": Moving from token " + op.oldToken + " to token " + op.newToken); if (!dryrun) { String ip = op.host.substring(op.host.lastIndexOf("/") + 1); NodeProbe np = new NodeProbe(ip, 7199); np.move(op.newToken.toString()); moved = true; } else { unbalanced = true; } } } if (!unbalanced && moved) { System.out.println("The cluster is now balanced!"); } }
From source file:org.opendaylight.netvirt.dhcpservice.DhcpUCastMacListener.java
@Override protected void add(InstanceIdentifier<LocalUcastMacs> identifier, LocalUcastMacs add) { NodeId torNodeId = identifier.firstKeyOf(Node.class).getNodeId(); InstanceIdentifier<LogicalSwitches> logicalSwitchRef = (InstanceIdentifier<LogicalSwitches>) add .getLogicalSwitchRef().getValue(); Optional<LogicalSwitches> logicalSwitchOptional = MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, logicalSwitchRef);/*from w ww. j a va 2 s . c o m*/ if (!logicalSwitchOptional.isPresent()) { LOG.error("Logical Switch ref doesn't have data {}", logicalSwitchRef); return; } LogicalSwitches logicalSwitch = logicalSwitchOptional.get(); String elanInstanceName = logicalSwitch.getHwvtepNodeName().getValue(); String macAddress = add.getMacEntryKey().getValue(); BigInteger vni = new BigInteger(logicalSwitch.getTunnelKey()); Port port = dhcpExternalTunnelManager.readVniMacToPortCache(vni, macAddress); if (port == null) { LOG.trace("No neutron port created for macAddress {}, tunnelKey {}", macAddress, vni); return; } L2GatewayDevice device = ElanL2GwCacheUtils.getL2GatewayDeviceFromCache(elanInstanceName, torNodeId.getValue()); if (device == null) { LOG.error("Logical Switch Device with name {} is not present in L2GWCONN cache", elanInstanceName); return; } IpAddress tunnelIp = device.getTunnelIp(); Subnet subnet = dhcpManager.getNeutronSubnet(port); if (null != subnet && !subnet.isEnableDhcp()) { dhcpExternalTunnelManager.updateExistingVMTunnelIPCache(tunnelIp, elanInstanceName, macAddress); LOG.warn( "DhcpUCastMacListener add: flag for the subnetId {} is False so Table 18 entries are not added", subnet.getUuid()); return; } BigInteger designatedDpnId = dhcpExternalTunnelManager.readDesignatedSwitchesForExternalTunnel(tunnelIp, elanInstanceName); if (designatedDpnId == null || designatedDpnId.equals(DhcpMConstants.INVALID_DPID)) { LOG.trace( "Unable to install flows for macAddress {}. TunnelIp {}, elanInstanceName {}, designatedDpn {} ", macAddress, tunnelIp, elanInstanceName, designatedDpnId); dhcpExternalTunnelManager.updateLocalCache(tunnelIp, elanInstanceName, macAddress); return; } dhcpExternalTunnelManager.installDhcpFlowsForVms(tunnelIp, elanInstanceName, DhcpServiceUtils.getListOfDpns(broker), designatedDpnId, macAddress); }
From source file:cherry.windows.charset.ListCreator.java
public void createList() throws IOException { Charset ms932 = Charset.forName("MS932"); Charset cp943 = Charset.forName("CP943"); Charset win31j = Charset.forName("Windows-31J"); System.out.println("WIN\tUNI\tMS932(1)\tMS932(2)\tCP943(1)\tCP943(2)\tWin31J(1)\tWin31J(2)\tCOMMENT"); List<Entry> list = tableParser.parse("CP932.TXT"); for (Entry entry : list) { System.out.print(entry.getWinCode()); System.out.print("\t"); System.out.print(entry.getUniCode()); System.out.print("\t"); BigInteger winCode = new BigInteger(entry.getWinCode(), 16); BigInteger bi932x1 = new BigInteger((new String(winCode.toByteArray(), ms932)).getBytes(ms932)); BigInteger bi932x2 = new BigInteger((new String(bi932x1.toByteArray(), ms932)).getBytes(ms932)); System.out.print(winCode.equals(bi932x1)); System.out.print("\t"); System.out.print(bi932x1.equals(bi932x2)); System.out.print("\t"); BigInteger bi943x1 = new BigInteger((new String(winCode.toByteArray(), cp943)).getBytes(cp943)); BigInteger bi943x2 = new BigInteger((new String(bi943x1.toByteArray(), cp943)).getBytes(cp943)); System.out.print(winCode.equals(bi943x1)); System.out.print("\t"); System.out.print(bi943x1.equals(bi943x2)); System.out.print("\t"); BigInteger bi31jx1 = new BigInteger((new String(winCode.toByteArray(), win31j)).getBytes(win31j)); BigInteger bi31jx2 = new BigInteger((new String(bi31jx1.toByteArray(), win31j)).getBytes(win31j)); System.out.print(winCode.equals(bi31jx1)); System.out.print("\t"); System.out.print(bi31jx1.equals(bi31jx2)); System.out.print("\t"); System.out.print(entry.getComment()); System.out.println();//from w w w .ja v a 2 s .co m } }
From source file:co.rsk.validators.BlockTxsValidationRule.java
@Override public boolean isValid(Block block, Block parent) { if (block == null || parent == null) { return false; }/*from ww w. ja va 2 s . c o m*/ List<Transaction> txs = block.getTransactionsList(); if (CollectionUtils.isEmpty(txs)) return true; Repository parentRepo = repository.getSnapshotTo(parent.getStateRoot()); Map<ByteArrayWrapper, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { byte[] txSender = tx.getSender(); ByteArrayWrapper key = new ByteArrayWrapper(txSender); BigInteger expectedNonce = curNonce.get(key); if (expectedNonce == null) { expectedNonce = parentRepo.getNonce(txSender); } curNonce.put(key, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.error("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, parentRepo.getNonce(txSender), tx); panicProcessor.panic("invalidtransaction", String.format( "Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s", txNonce.toString(), expectedNonce.toString(), parentRepo.getNonce(txSender).toString(), Hex.toHexString(tx.getHash()))); return false; } } return true; }
From source file:eu.europa.esig.dss.client.ocsp.OnlineOCSPSource.java
@Override public OCSPToken getOCSPToken(CertificateToken certificateToken, CertificateToken issuerCertificateToken) { if (dataLoader == null) { throw new NullPointerException("DataLoad is not provided !"); }/*from www . ja va 2s . c o m*/ try { final String dssIdAsString = certificateToken.getDSSIdAsString(); if (logger.isTraceEnabled()) { logger.trace("--> OnlineOCSPSource queried for " + dssIdAsString); } final X509Certificate x509Certificate = certificateToken.getCertificate(); final String ocspAccessLocation = getAccessLocation(x509Certificate); if (StringUtils.isEmpty(ocspAccessLocation)) { if (logger.isDebugEnabled()) { logger.info("No OCSP location found for " + dssIdAsString); } certificateToken.extraInfo().infoNoOcspUriFoundInCertificate(); return null; } final X509Certificate issuerX509Certificate = issuerCertificateToken.getCertificate(); final byte[] content = buildOCSPRequest(x509Certificate, issuerX509Certificate); final byte[] ocspRespBytes = dataLoader.post(ocspAccessLocation, content); final OCSPResp ocspResp = new OCSPResp(ocspRespBytes); final BasicOCSPResp basicOCSPResp = (BasicOCSPResp) ocspResp.getResponseObject(); if (nonceSource != null) { Extension extension = basicOCSPResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); DEROctetString derReceivedNonce = (DEROctetString) extension.getExtnValue(); BigInteger receivedNonce = new BigInteger(derReceivedNonce.getOctets()); if (!receivedNonce.equals(nonceSource.getNonce())) { throw new DSSException("The OCSP request for " + dssIdAsString + " was the victim of replay attack: nonce [sent:" + nonceSource.getNonce() + ", received:" + receivedNonce + "]"); } } Date bestUpdate = null; SingleResp bestSingleResp = null; final CertificateID certId = DSSRevocationUtils.getOCSPCertificateID(x509Certificate, issuerX509Certificate); for (final SingleResp singleResp : basicOCSPResp.getResponses()) { if (DSSRevocationUtils.matches(certId, singleResp)) { final Date thisUpdate = singleResp.getThisUpdate(); if ((bestUpdate == null) || thisUpdate.after(bestUpdate)) { bestSingleResp = singleResp; bestUpdate = thisUpdate; } } } if (bestSingleResp != null) { final OCSPToken ocspToken = new OCSPToken(basicOCSPResp, bestSingleResp); ocspToken.setSourceURI(ocspAccessLocation); certificateToken.setRevocationToken(ocspToken); return ocspToken; } } catch (NullPointerException e) { throw new DSSException( "OCSPResp is initialised with a null OCSP response... (and there is no nullity check in the OCSPResp implementation)", e); } catch (OCSPException e) { throw new DSSException(e); } catch (IOException e) { throw new DSSException(e); } return null; }