List of usage examples for java.math BigInteger ZERO
BigInteger ZERO
To view the source code for java.math BigInteger ZERO.
Click Source Link
From source file:com.cisco.dvbu.ps.deploytool.services.DataSourceManagerImpl.java
private void populateAttributesFromRelationalDataSource(DataSourceChoiceType datasource, AttributeList dsAttributeList) { String defaultPropertyFile = CommonConstants.propertyFile; /* Determine the property file name for this environment * 1. Start with default file CommonConstants.propertyFile * 2. Get Java Environment variables * 3. Get OS System Environment variables *//*from w w w. ja va 2 s.com*/ String propertyFile = CommonUtils.getFileOrSystemPropertyValue(defaultPropertyFile, "CONFIG_PROPERTY_FILE"); // Set a default value if not found if (propertyFile == null || propertyFile.trim().length() == 0) { propertyFile = defaultPropertyFile; } String prefix = "DataSourcemanagerImpl.populateAttributesFromRelationalDataSource"; // Add attribute if not null and empty if (datasource.getRelationalDataSource().getHostname() != null && datasource.getRelationalDataSource().getHostname().length() > 0) { Attribute attrHost = new Attribute(); attrHost.setName("urlIP"); attrHost.setType(AttributeType.STRING); // Extract and resolve variables used in the value attribute String value = CommonUtils.extractVariable(prefix, datasource.getRelationalDataSource().getHostname(), propertyFile, false); attrHost.setValue(value); dsAttributeList.getAttribute().add(attrHost); } // Add attribute if not null and greater than 0 if (datasource.getRelationalDataSource().getPort() != null) { Attribute attrUrlPort = new Attribute(); attrUrlPort.setName("urlPort"); attrUrlPort.setType(AttributeType.INTEGER); // Extract and resolve variables used in the value attribute String value = CommonUtils.extractVariable(prefix, datasource.getRelationalDataSource().getPort().toString(), propertyFile, false); // Convert the resolved string value to big integer to verify that it is an integer value. BigInteger intPort = new BigInteger(value); // Only set the value if the port number is greater than 0 if (intPort.compareTo(BigInteger.ZERO) == 1) { attrUrlPort.setValue(value); dsAttributeList.getAttribute().add(attrUrlPort); } } // Add attribute if not null and empty if (datasource.getRelationalDataSource().getDatabaseName() != null && datasource.getRelationalDataSource().getDatabaseName().length() > 0) { Attribute attrDbName = new Attribute(); attrDbName.setName("urlDatabaseName"); attrDbName.setType(AttributeType.STRING); // Extract and resolve variables used in the value attribute String value = CommonUtils.extractVariable(prefix, datasource.getRelationalDataSource().getDatabaseName(), propertyFile, false); attrDbName.setValue(value); dsAttributeList.getAttribute().add(attrDbName); } // Add attribute if not null and empty if (datasource.getRelationalDataSource().getLogin() != null && datasource.getRelationalDataSource().getLogin().length() > 0) { Attribute attrLogin = new Attribute(); attrLogin.setName("login"); attrLogin.setType(AttributeType.STRING); // Extract and resolve variables used in the value attribute String value = CommonUtils.extractVariable(prefix, datasource.getRelationalDataSource().getLogin(), propertyFile, false); attrLogin.setValue(value); dsAttributeList.getAttribute().add(attrLogin); } // Add attribute if not null and empty if (datasource.getRelationalDataSource().getEncryptedPassword() != null && datasource.getRelationalDataSource().getEncryptedPassword().length() > 0) { Attribute attrPassword = new Attribute(); attrPassword.setName("password"); attrPassword.setType(AttributeType.PASSWORD_STRING); attrPassword.setValue(CommonUtils.decrypt(datasource.getRelationalDataSource().getEncryptedPassword())); dsAttributeList.getAttribute().add(attrPassword); } // Add attribute if not null and empty if (datasource.getRelationalDataSource().getValQuery() != null && datasource.getRelationalDataSource().getValQuery().length() > 0) { Attribute attrValQuery = new Attribute(); attrValQuery.setName("connValidateQuery"); attrValQuery.setType(AttributeType.STRING); // Extract and resolve variables used in the value attribute String value = CommonUtils.extractVariable(prefix, datasource.getRelationalDataSource().getValQuery(), propertyFile, false); attrValQuery.setValue(value); dsAttributeList.getAttribute().add(attrValQuery); } }
From source file:org.apache.pig.backend.hadoop.executionengine.physicalLayer.expressionOperators.POCast.java
@SuppressWarnings({ "unchecked", "deprecation" }) private Object convertWithSchema(Object obj, ResourceFieldSchema fs) throws IOException { Object result = null;//from w ww. j ava 2 s . com if (fs == null) { return obj; } if (obj == null) { // handle DataType.NULL return null; } switch (fs.getType()) { case DataType.BAG: if (obj instanceof DataBag) { DataBag db = (DataBag) obj; // Get inner schema of a bag if (fs.getSchema() != null) { ResourceFieldSchema tupleFs = fs.getSchema().getFields()[0]; Iterator<Tuple> iter = db.iterator(); while (iter.hasNext()) { Tuple t = iter.next(); convertWithSchema(t, tupleFs); } } result = db; } else if (obj instanceof DataByteArray) { if (null != caster) { result = caster.bytesToBag(((DataByteArray) obj).get(), fs); } else { int errCode = 1075; String msg = unknownByteArrayErrorMessage + "bag."; throw new ExecException(msg, errCode, PigException.INPUT); } } else { throw new ExecException("Cannot cast " + obj + " to bag.", 1120, PigException.INPUT); } break; case DataType.TUPLE: if (obj instanceof Tuple) { try { Tuple t = (Tuple) obj; ResourceSchema innerSchema = fs.getSchema(); if (innerSchema == null) return t; if (innerSchema.getFields().length != t.size()) return null; int i = 0; for (ResourceFieldSchema fieldSchema : innerSchema.getFields()) { Object field = convertWithSchema(t.get(i), fieldSchema); t.set(i, field); i++; } result = t; } catch (Exception e) { throw new ExecException("Cannot convert " + obj + " to " + fs); } } else if (obj instanceof DataByteArray) { if (null != caster) { result = caster.bytesToTuple(((DataByteArray) obj).get(), fs); } else { int errCode = 1075; String msg = unknownByteArrayErrorMessage + "tuple."; throw new ExecException(msg, errCode, PigException.INPUT); } } else { throw new ExecException("Cannot cast " + obj + " to tuple.", 1120, PigException.INPUT); } break; case DataType.MAP: if (obj instanceof Map) { if (fs != null && fs.getSchema() != null) { ResourceFieldSchema innerFieldSchema = fs.getSchema().getFields()[0]; Map m = (Map) obj; for (Object entry : m.entrySet()) { Object newValue = convertWithSchema(((Map.Entry) entry).getValue(), innerFieldSchema); m.put(((Map.Entry) entry).getKey(), newValue); } result = m; } else result = obj; } else if (obj instanceof DataByteArray) { if (null != caster) { result = caster.bytesToMap(((DataByteArray) obj).get(), fs); } else { int errCode = 1075; String msg = unknownByteArrayErrorMessage + "tuple."; throw new ExecException(msg, errCode, PigException.INPUT); } } else { throw new ExecException("Cannot cast " + obj + " to map.", 1120, PigException.INPUT); } break; case DataType.BOOLEAN: switch (DataType.findType(obj)) { case DataType.BYTEARRAY: if (null != caster) { result = caster.bytesToBoolean(((DataByteArray) obj).get()); } else { int errCode = 1075; String msg = unknownByteArrayErrorMessage + "int."; throw new ExecException(msg, errCode, PigException.INPUT); } break; case DataType.BOOLEAN: result = obj; break; case DataType.INTEGER: result = Boolean.valueOf(((Integer) obj).intValue() != 0); ; break; case DataType.DOUBLE: result = Boolean.valueOf(((Double) obj).doubleValue() != 0.0D); break; case DataType.LONG: result = Boolean.valueOf(((Long) obj).longValue() != 0L); break; case DataType.FLOAT: result = Boolean.valueOf(((Float) obj).floatValue() != 0.0F); break; case DataType.CHARARRAY: result = CastUtils.stringToBoolean((String) obj); break; case DataType.BIGINTEGER: result = Boolean.valueOf(!BigInteger.ZERO.equals((BigInteger) obj)); break; case DataType.BIGDECIMAL: result = Boolean.valueOf(!BigDecimal.ZERO.equals((BigDecimal) obj)); break; default: throw new ExecException("Cannot convert " + obj + " to " + fs, 1120, PigException.INPUT); } break; case DataType.INTEGER: switch (DataType.findType(obj)) { case DataType.BYTEARRAY: if (null != caster) { result = caster.bytesToInteger(((DataByteArray) obj).get()); } else { int errCode = 1075; String msg = unknownByteArrayErrorMessage + "int."; throw new ExecException(msg, errCode, PigException.INPUT); } break; case DataType.BOOLEAN: if ((Boolean) obj) { result = Integer.valueOf(1); } else { result = Integer.valueOf(0); } break; case DataType.INTEGER: result = obj; break; case DataType.DOUBLE: result = Integer.valueOf(((Double) obj).intValue()); break; case DataType.LONG: result = Integer.valueOf(((Long) obj).intValue()); break; case DataType.FLOAT: result = Integer.valueOf(((Float) obj).intValue()); break; case DataType.DATETIME: result = Integer.valueOf(Long.valueOf(((DateTime) obj).getMillis()).intValue()); break; case DataType.CHARARRAY: result = CastUtils.stringToInteger((String) obj); break; case DataType.BIGINTEGER: result = Integer.valueOf(((BigInteger) obj).intValue()); break; case DataType.BIGDECIMAL: result = Integer.valueOf(((BigDecimal) obj).intValue()); break; default: throw new ExecException("Cannot convert " + obj + " to " + fs, 1120, PigException.INPUT); } break; case DataType.DOUBLE: switch (DataType.findType(obj)) { case DataType.BYTEARRAY: if (null != caster) { result = caster.bytesToDouble(((DataByteArray) obj).get()); } else { int errCode = 1075; String msg = unknownByteArrayErrorMessage + "double."; throw new ExecException(msg, errCode, PigException.INPUT); } break; case DataType.BOOLEAN: if ((Boolean) obj) { result = new Double(1); } else { result = new Double(1); } break; case DataType.INTEGER: result = new Double(((Integer) obj).doubleValue()); break; case DataType.DOUBLE: result = (Double) obj; break; case DataType.LONG: result = new Double(((Long) obj).doubleValue()); break; case DataType.FLOAT: result = new Double(((Float) obj).doubleValue()); break; case DataType.DATETIME: result = new Double(Long.valueOf(((DateTime) obj).getMillis()).doubleValue()); break; case DataType.CHARARRAY: result = CastUtils.stringToDouble((String) obj); break; case DataType.BIGINTEGER: result = Double.valueOf(((BigInteger) obj).doubleValue()); break; case DataType.BIGDECIMAL: result = Double.valueOf(((BigDecimal) obj).doubleValue()); break; default: throw new ExecException("Cannot convert " + obj + " to " + fs, 1120, PigException.INPUT); } break; case DataType.LONG: switch (DataType.findType(obj)) { case DataType.BYTEARRAY: if (null != caster) { result = caster.bytesToLong(((DataByteArray) obj).get()); } else { int errCode = 1075; String msg = unknownByteArrayErrorMessage + "long."; throw new ExecException(msg, errCode, PigException.INPUT); } break; case DataType.BOOLEAN: if ((Boolean) obj) { result = Long.valueOf(1); } else { result = Long.valueOf(0); } break; case DataType.INTEGER: result = Long.valueOf(((Integer) obj).longValue()); break; case DataType.DOUBLE: result = Long.valueOf(((Double) obj).longValue()); break; case DataType.LONG: result = (Long) obj; break; case DataType.FLOAT: result = Long.valueOf(((Float) obj).longValue()); break; case DataType.DATETIME: result = Long.valueOf(((DateTime) obj).getMillis()); break; case DataType.CHARARRAY: result = CastUtils.stringToLong((String) obj); break; case DataType.BIGINTEGER: result = Long.valueOf(((BigInteger) obj).longValue()); break; case DataType.BIGDECIMAL: result = Long.valueOf(((BigDecimal) obj).longValue()); break; default: throw new ExecException("Cannot convert " + obj + " to " + fs, 1120, PigException.INPUT); } break; case DataType.FLOAT: switch (DataType.findType(obj)) { case DataType.BYTEARRAY: if (null != caster) { result = caster.bytesToFloat(((DataByteArray) obj).get()); } else { int errCode = 1075; String msg = unknownByteArrayErrorMessage + "float."; throw new ExecException(msg, errCode, PigException.INPUT); } break; case DataType.BOOLEAN: if ((Boolean) obj) { result = new Float(1); } else { result = new Float(0); } break; case DataType.INTEGER: result = new Float(((Integer) obj).floatValue()); break; case DataType.DOUBLE: result = new Float(((Double) obj).floatValue()); break; case DataType.LONG: result = new Float(((Long) obj).floatValue()); break; case DataType.FLOAT: result = obj; break; case DataType.DATETIME: result = new Float(Long.valueOf(((DateTime) obj).getMillis()).floatValue()); break; case DataType.CHARARRAY: result = CastUtils.stringToFloat((String) obj); break; case DataType.BIGINTEGER: result = Float.valueOf(((BigInteger) obj).floatValue()); break; case DataType.BIGDECIMAL: result = Float.valueOf(((BigDecimal) obj).floatValue()); break; default: throw new ExecException("Cannot convert " + obj + " to " + fs, 1120, PigException.INPUT); } break; case DataType.DATETIME: switch (DataType.findType(obj)) { case DataType.BYTEARRAY: if (null != caster) { result = caster.bytesToDateTime(((DataByteArray) obj).get()); } else { int errCode = 1075; String msg = unknownByteArrayErrorMessage + "datetime."; throw new ExecException(msg, errCode, PigException.INPUT); } break; case DataType.INTEGER: result = new DateTime(((Integer) obj).longValue()); break; case DataType.DOUBLE: result = new DateTime(((Double) obj).longValue()); break; case DataType.LONG: result = new DateTime(((Long) obj).longValue()); break; case DataType.FLOAT: result = new DateTime(((Float) obj).longValue()); break; case DataType.DATETIME: result = (DateTime) obj; break; case DataType.CHARARRAY: result = ToDate.extractDateTime((String) obj); break; case DataType.BIGINTEGER: result = new DateTime(((BigInteger) obj).longValue()); break; case DataType.BIGDECIMAL: result = new DateTime(((BigDecimal) obj).longValue()); break; default: throw new ExecException("Cannot convert " + obj + " to " + fs, 1120, PigException.INPUT); } break; case DataType.CHARARRAY: switch (DataType.findType(obj)) { case DataType.BYTEARRAY: if (null != caster) { result = caster.bytesToCharArray(((DataByteArray) obj).get()); } else { int errCode = 1075; String msg = unknownByteArrayErrorMessage + "float."; throw new ExecException(msg, errCode, PigException.INPUT); } break; case DataType.BOOLEAN: if ((Boolean) obj) { //result = "1"; result = Boolean.TRUE.toString(); } else { //result = "0"; result = Boolean.FALSE.toString(); } break; case DataType.INTEGER: result = ((Integer) obj).toString(); break; case DataType.DOUBLE: result = ((Double) obj).toString(); break; case DataType.LONG: result = ((Long) obj).toString(); break; case DataType.FLOAT: result = ((Float) obj).toString(); break; case DataType.DATETIME: result = ((DateTime) obj).toString(); break; case DataType.CHARARRAY: result = obj; break; case DataType.BIGINTEGER: result = ((BigInteger) obj).toString(); break; case DataType.BIGDECIMAL: result = ((BigDecimal) obj).toString(); break; default: throw new ExecException("Cannot convert " + obj + " to " + fs, 1120, PigException.INPUT); } break; case DataType.BIGINTEGER: switch (DataType.findType(obj)) { case DataType.BYTEARRAY: if (null != caster) { result = caster.bytesToBigInteger(((DataByteArray) obj).get()); } else { int errCode = 1075; String msg = unknownByteArrayErrorMessage + "BigInteger."; throw new ExecException(msg, errCode, PigException.INPUT); } break; case DataType.BOOLEAN: if ((Boolean) obj) { result = BigInteger.ONE; } else { result = BigInteger.ZERO; } break; case DataType.INTEGER: result = BigInteger.valueOf(((Integer) obj).longValue()); break; case DataType.DOUBLE: result = BigInteger.valueOf(((Double) obj).longValue()); break; case DataType.LONG: result = BigInteger.valueOf(((Long) obj).longValue()); break; case DataType.FLOAT: result = BigInteger.valueOf(((Float) obj).longValue()); break; case DataType.CHARARRAY: result = new BigInteger((String) obj); break; case DataType.BIGINTEGER: result = (BigInteger) obj; break; case DataType.BIGDECIMAL: result = ((BigDecimal) obj).toBigInteger(); break; case DataType.DATETIME: result = BigInteger.valueOf(((DateTime) obj).getMillis()); break; default: throw new ExecException("Cannot convert " + obj + " to " + fs, 1120, PigException.INPUT); } case DataType.BIGDECIMAL: switch (DataType.findType(obj)) { case DataType.BYTEARRAY: if (null != caster) { result = caster.bytesToBigDecimal(((DataByteArray) obj).get()); } else { int errCode = 1075; String msg = unknownByteArrayErrorMessage + "BigDecimal."; throw new ExecException(msg, errCode, PigException.INPUT); } break; case DataType.BOOLEAN: if ((Boolean) obj) { result = BigDecimal.ONE; } else { result = BigDecimal.ZERO; } break; case DataType.INTEGER: result = BigDecimal.valueOf(((Integer) obj).longValue()); break; case DataType.DOUBLE: result = BigDecimal.valueOf(((Double) obj).doubleValue()); break; case DataType.LONG: result = BigDecimal.valueOf(((Long) obj).longValue()); break; case DataType.FLOAT: result = BigDecimal.valueOf(((Float) obj).doubleValue()); break; case DataType.CHARARRAY: result = new BigDecimal((String) obj); break; case DataType.BIGINTEGER: result = new BigDecimal((BigInteger) obj); break; case DataType.BIGDECIMAL: result = (BigDecimal) obj; break; case DataType.DATETIME: result = BigDecimal.valueOf(((DateTime) obj).getMillis()); break; default: throw new ExecException("Cannot convert " + obj + " to " + fs, 1120, PigException.INPUT); } default: throw new ExecException("Don't know how to convert " + obj + " to " + fs, 1120, PigException.INPUT); } return result; }
From source file:org.sparkbit.jsonrpc.SparkBitJSONRPCServiceImpl.java
/** * Returns an array of unspent transaction outputs, detailing the Bitcoin and * asset balances tied to that UTXO.//from w w w . j a v a 2 s. c o m * * Behavior is modeled from bitcoin: https://bitcoin.org/en/developer-reference#listunspent * minconf "Default is 1; use 0 to count unconfirmed transactions." * maxconf "Default is 9,999,999; use 0 to count unconfirmed transactions." * As minconf and maxconf are not optional, the default values above are ignored. * * @param walletname * @param minconf * @param maxconf * @param addresses List of CoinSpark or Bitcoin addresses * @return * @throws com.bitmechanic.barrister.RpcException */ @Override public JSONRPCUnspentTransactionOutput[] listunspent(String walletname, Long minconf, Long maxconf, String[] addresses) throws com.bitmechanic.barrister.RpcException { log.info("LIST UNSPENT TRANSACTION OUTPUTS"); log.info("wallet name = " + walletname); log.info("min number of confirmations = " + minconf); log.info("max number of confirmations = " + maxconf); log.info("addresses = " + Arrays.toString(addresses)); Wallet w = getWalletForWalletName(walletname); if (w == null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } if (minconf < 0 || maxconf < 0) { JSONRPCError.CONFIRMATIONS_TOO_LOW.raiseRpcException(); } NetworkParameters networkParams = this.controller.getModel().getNetworkParameters(); int mostCommonChainHeight = this.controller.getMultiBitService().getPeerGroup().getMostCommonChainHeight(); boolean skipAddresses = addresses.length == 0; // Parse the list of addresses // If CoinSpark, convert to BTC. Set<String> setOfAddresses = new HashSet<String>(); for (String address : addresses) { address = address.trim(); if (address.length() == 0) { continue; // ignore empty string } String btcAddress = null; String csAddress = null; if (address.startsWith("s")) { csAddress = address; btcAddress = CSMiscUtils.getBitcoinAddressFromCoinSparkAddress(address); if (btcAddress == null) { // Invalid CoinSpark address, so throw exception JSONRPCError.COINSPARK_ADDRESS_INVALID.raiseRpcException(csAddress); } } else { btcAddress = address; } boolean b = CSMiscUtils.validateBitcoinAddress(btcAddress, this.controller); if (b) { setOfAddresses.add(btcAddress); // convenience to add coinspark address for lookup // if (csAddress != null) setOfAddresses.add(csAddress); } else { if (csAddress != null) { // Invalid Bitcoin address from decoded CoinSpark address so throw exception. JSONRPCError.COINSPARK_ADDRESS_INVALID .raiseRpcException(csAddress + " --> decoded btc address " + btcAddress); } else { // Invalid Bitcoin address JSONRPCError.BITCOIN_ADDRESS_INVALID.raiseRpcException(btcAddress); } } } // If the set of addresses is empty, list of addresses probably whitespace etc. // Let's treat as skipping addresses. if (setOfAddresses.size() == 0) { skipAddresses = true; } ArrayList<JSONRPCUnspentTransactionOutput> resultList = new ArrayList<>(); Map<CSTransactionOutput, Map<Integer, CSBalance>> map = w.CS.getAllAssetTxOuts(); // Set<CSTransactionOutput> keys = map.keySet(); Iterator it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); CSTransactionOutput cstxout = (CSTransactionOutput) entry.getKey(); // Only process if txout belongs to our wallet and is unspent Transaction tx = cstxout.getParentTransaction(); TransactionOutput txout = tx.getOutput(cstxout.getIndex()); if (!txout.isAvailableForSpending() || !txout.isMine(w)) { continue; } // If confidence is not building, don't list it as it is pending, dead or unknown. TransactionConfidence.ConfidenceType confidenceType = tx.getConfidence().getConfidenceType(); if (confidenceType == TransactionConfidence.ConfidenceType.UNKNOWN || confidenceType == TransactionConfidence.ConfidenceType.DEAD) { continue; } int numConfirmations = 0; // If confidence is PENDING, this will be zero if (confidenceType == TransactionConfidence.ConfidenceType.BUILDING) { // getAppearedAtChainHeight() will throw illegalstate exception if confidence is not building int txAppearedAtChainHeight = tx.getConfidence().getAppearedAtChainHeight(); numConfirmations = mostCommonChainHeight - txAppearedAtChainHeight + 1; // if same, then it means 1 confirmation } // Only process if number of confirmations is within range. if (minconf == 0 || maxconf == 0) { // Unconfirmed transactions are okay, so do nothing. } else if (numConfirmations < minconf || numConfirmations > maxconf) { // Skip if outside of range continue; } // Only process if the BTC address for this tx is in the list of addresses String btcAddress = txout.getScriptPubKey().getToAddress(networkParams).toString(); if (!skipAddresses && !setOfAddresses.contains(btcAddress)) { continue; } // Get the bitcoin and asset balances on this utxo Map<Integer, CSBalance> balances = (Map<Integer, CSBalance>) entry.getValue(); boolean hasAssets = false; ArrayList<JSONRPCBalance> balancesList = new ArrayList<>(); for (Map.Entry<Integer, CSBalance> balanceEntry : balances.entrySet()) { Integer assetID = balanceEntry.getKey(); CSBalance balance = balanceEntry.getValue(); BigInteger qty = balance.getQty(); boolean isSelectable = DefaultCoinSelector.isSelectable(tx); // log.info(">>>> assetID = " + assetID + " , qty = " + qty); // Handle Bitcoin specially if (assetID == 0) { JSONRPCBalance bal = null; // if (isSelectable) { // bal = createBitcoinBalance(w, qty, null); // } else { bal = createBitcoinBalance(w, qty, null); // } balancesList.add(bal); continue; } // Other assets hasAssets = true; if (qty.compareTo(BigInteger.ZERO) > 0) { JSONRPCBalance bal = null; bal = createAssetBalance(w, assetID, qty, null); // if (isSelectable) { // bal = createAssetBalance(w, assetID, qty, qty); // } else { // bal = createAssetBalance(w, assetID, qty, BigInteger.ZERO); // } balancesList.add(bal); } } JSONRPCBalance[] balancesArray = balancesList.toArray(new JSONRPCBalance[0]); String scriptPubKeyHexString = Utils.bytesToHexString(txout.getScriptBytes()); // Build the object to return JSONRPCUnspentTransactionOutput utxo = new JSONRPCUnspentTransactionOutput(); utxo.setTxid(tx.getHashAsString()); utxo.setVout((long) cstxout.getIndex()); utxo.setScriptPubKey(scriptPubKeyHexString); utxo.setAmounts(balancesArray); //new JSONRPCBalance[0]); utxo.setConfirmations((long) numConfirmations); utxo.setBitcoin_address(btcAddress); if (hasAssets) { String sparkAddress = null; // First let's see if we have stored the recipient in our map and use it instead // of generating a new one from bitcoin address try { String spk = SparkBitMapDB.INSTANCE.getSendCoinSparkAddressForTxid(tx.getHashAsString()); String btc = CSMiscUtils.getBitcoinAddressFromCoinSparkAddress(spk); if (btc.equals(btcAddress)) { sparkAddress = spk; } } catch (Exception e) { } if (sparkAddress == null) { sparkAddress = CSMiscUtils.convertBitcoinAddressToCoinSparkAddress(btcAddress); } utxo.setCoinspark_address(sparkAddress); } utxo.setAmounts(balancesArray); resultList.add(utxo); } JSONRPCUnspentTransactionOutput[] resultArray = resultList.toArray(new JSONRPCUnspentTransactionOutput[0]); return resultArray; }
From source file:com.flexive.core.storage.genericSQL.GenericTreeStorageSpreaded.java
/** * {@inheritDoc}/* w ww .ja v a 2 s . co m*/ */ @Override public void checkTree(Connection con, FxTreeMode mode) throws FxApplicationException { PreparedStatement stmt = null; try { // 1 - ID, 2 - LFT, 3 - RGT, 4 - CHILDCOUNT, 5 - DEPTH, 6 - PARENT final String sql = "SELECT t.id, t.LFT, t.RGT, t.CHILDCOUNT, t.DEPTH, t.PARENT " + "FROM " + getTable(mode) + " t"; stmt = con.prepareStatement(sql); stmt.setFetchSize(10000); final ResultSet rs = stmt.executeQuery(); // collect nodes, build lookup tables final Map<Long, CheckedNodeInfo> nodeMap = Maps.newHashMap(); // node ID -> node info final Multimap<Long, CheckedNodeInfo> childMap = HashMultimap.create(); // node ID -> children final Multimap<BigInteger, CheckedNodeInfo> leftNodeInfos = HashMultimap.create(1000, 1); final Multimap<BigInteger, CheckedNodeInfo> rightNodeInfos = HashMultimap.create(1000, 1); while (rs.next()) { final CheckedNodeInfo info = new CheckedNodeInfo(rs.getLong(1), rs.getLong(6), getNodeBounds(rs, 2), getNodeBounds(rs, 3), rs.getInt(4), rs.getInt(5)); nodeMap.put(info.id, info); childMap.put(info.parentId, info); leftNodeInfos.put(info.left, info); rightNodeInfos.put(info.right, info); } // process all nodes for (CheckedNodeInfo node : nodeMap.values()) { // check node boundaries if (node.left.compareTo(node.right) > 0) { throw new FxTreeException(LOG, "ex.tree.check.failed", mode, "#" + node.id + ": left boundary greater than right."); } // check node bounds of children BigInteger min = MAX_RIGHT; BigInteger max = BigInteger.ZERO; final Collection<CheckedNodeInfo> children = childMap.get(node.id); for (CheckedNodeInfo child : children) { if (child.left.compareTo(min) < 0) { min = child.left; } if (child.right.compareTo(max) > 0) { max = child.right; } } if (max.compareTo(node.right) > 0) { throw new FxTreeException(LOG, "ex.tree.check.failed", mode, "#" + node.id + " out of bounds (right)"); } if (min.compareTo(node.left) < 0) { throw new FxTreeException(LOG, "ex.tree.check.failed", mode, "#" + node.id + " out of bounds (left)"); } // Check stored child count if (node.directChildCount != children.size()) { throw new FxTreeException(LOG, "ex.tree.check.failed", mode, "#" + node.id + " invalid direct child count [" + node.directChildCount + "!=" + children.size() + "]"); } // Check depth if (node.id != FxTreeNode.ROOT_NODE && node.depth != nodeMap.get(node.parentId).depth + 1) { throw new FxTreeException(LOG, "ex.tree.check.failed", mode, "#" + node.id + " invalid depth: " + node.depth + ", parent depth=" + nodeMap.get(node.parentId).depth); } } checkUniqueBounds(mode, leftNodeInfos, "left"); checkUniqueBounds(mode, rightNodeInfos, "right"); if (LOG.isDebugEnabled()) LOG.debug( "Successfully checked [" + childMap.size() + "] tree nodes in mode [" + mode.name() + "]!"); } catch (SQLException e) { throw new FxTreeException(LOG, e, "ex.tree.check.failed", mode, e.getMessage()); } finally { Database.closeObjects(GenericTreeStorageSpreaded.class, stmt); } }
From source file:com.google.bitcoin.core.Wallet.java
private void receive(Transaction tx, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException { // Runs in a peer thread. checkState(lock.isHeldByCurrentThread()); BigInteger prevBalance = getBalance(); Sha256Hash txHash = tx.getHash();/*from w w w . j a v a 2 s .co m*/ boolean bestChain = blockType == BlockChain.NewBlockType.BEST_CHAIN; boolean sideChain = blockType == BlockChain.NewBlockType.SIDE_CHAIN; BigInteger valueSentFromMe = tx.getValueSentFromMe(this); BigInteger valueSentToMe = tx.getValueSentToMe(this); BigInteger valueDifference = valueSentToMe.subtract(valueSentFromMe); log.info("!!!! receive START " + tx.getHashAsString()); log.info("Received tx{} for {} BTC: {} [{}] in block {}", sideChain ? " on a side chain" : "", bitcoinValueToFriendlyString(valueDifference), tx.getHashAsString(), relativityOffset, block != null ? block.getHeader().getHash() : "(unit test)"); /* CSPK-mike START */ // Looking for CoinSpark assets in the transaction if (bestChain) { int blockHeight = 0; if (block != null) { blockHeight = block.getHeight(); CS.log.info("New tx " + tx.getHash().toString() + " in block " + blockHeight); } log.info("!!!! receive HIT!!! " + tx.getHashAsString()); CSTransactionAssets txAssets = new CSTransactionAssets(tx); txAssets.updateAssetBalances(this, blockHeight, CS.getInputAssetBalances(tx)); /* Look for payment reference and post CSEvent if found */ final int FBHCHAIN_START_BLOCK = 312500; // July 26th 2014 // optimise, only check from period when assets were first being created if (blockHeight > FBHCHAIN_START_BLOCK) { log.info("!!!! Extracting CoinSpark payment reference from a transaction..."); byte[] txnMetaData = null; //int metadataOutput=0; //int count=0; for (TransactionOutput output : tx.getOutputs()) { // TRANSACTION_PAYMENT_REFERENCE_DETECTED byte[] scriptBytes = output.getScriptBytes(); if (!CoinSparkBase.scriptIsRegular(scriptBytes)) { txnMetaData = CoinSparkBase.scriptToMetadata(scriptBytes); break; } } if (txnMetaData != null) { CoinSparkPaymentRef paymentRef = new CoinSparkPaymentRef(); if (paymentRef.decode(txnMetaData)) { log.info("!!!! Found Payment Ref: " + paymentRef.toString()); HashMap<String, Long> map = new HashMap<String, Long>(); map.put(tx.getHashAsString(), paymentRef.getRef()); CSEventBus.INSTANCE.postAsyncEvent(CSEventType.TRANSACTION_PAYMENT_REFERENCE_RECEIVED, map); } } } } /* CSPK-mike END */ // If the transaction is being replayed no need to add it to the wallet again. Transaction diagnosticTx = tx; if (spent.containsKey(txHash)) { diagnosticTx = spent.get(txHash); } if (unspent.containsKey(txHash)) { diagnosticTx = unspent.get(txHash); } if (dead.containsKey(txHash)) { diagnosticTx = dead.get(txHash); } boolean isReplay = ((spent.containsKey(txHash) || unspent.containsKey(txHash) || dead.containsKey(txHash)) && bestChain) && diagnosticTx.getConfidence().getConfidenceType() == ConfidenceType.BUILDING && (diagnosticTx.getConfidence().getAppearedAtChainHeight() > lastBlockSeenHeight); if (isReplay) { log.debug("Replay diagnostic for tx = " + txHash); log.debug(" spent.containsKey(txHash) = " + spent.containsKey(txHash)); log.debug(" unspent.containsKey(txHash) = " + unspent.containsKey(txHash)); log.debug(" dead.containsKey(txHash) = " + dead.containsKey(txHash)); log.debug(" diagnosticTx.getConfidence().getConfidenceType() = " + diagnosticTx.getConfidence().getConfidenceType()); if (diagnosticTx.getConfidence().getConfidenceType() == ConfidenceType.BUILDING) { log.debug(" diagnosticTx.getConfidence().getAppearedAtChainHeight() = " + diagnosticTx.getConfidence().getAppearedAtChainHeight()); } log.debug(" lastBlockSeenHeight = " + lastBlockSeenHeight); log.debug(" bestChain = " + bestChain); // We know the tx appears in the chain in the future (compared to // now) and it is not a reorg so can ignore it. // This happens on replay. log.debug("Received a tx '" + txHash.toString() + "' which is a replay so ignoring."); return; } onWalletChangedSuppressions++; // If this transaction is already in the wallet we may need to move it into a different pool. At the very // least we need to ensure we're manipulating the canonical object rather than a duplicate. { Transaction tmp = transactions.get(tx.getHash()); if (tmp != null) tx = tmp; } boolean wasPending = pending.remove(txHash) != null; if (wasPending) log.info(" <-pending"); if (bestChain) { if (wasPending) { // Was pending and is now confirmed. Disconnect the outputs in case we spent any already: they will be // re-connected by processTxFromBestChain below. for (TransactionOutput output : tx.getOutputs()) { final TransactionInput spentBy = output.getSpentBy(); if (spentBy != null) spentBy.disconnect(); } } processTxFromBestChain(tx, wasPending); } else { checkState(sideChain); // Transactions that appear in a side chain will have that appearance recorded below - we assume that // some miners are also trying to include the transaction into the current best chain too, so let's treat // it as pending, except we don't need to do any risk analysis on it. if (wasPending) { // Just put it back in without touching the connections or confidence. addWalletTransaction(Pool.PENDING, tx); log.info(" ->pending"); } else { // Ignore the case where a tx appears on a side chain at the same time as the best chain (this is // quite normal and expected). Sha256Hash hash = tx.getHash(); if (!unspent.containsKey(hash) && !spent.containsKey(hash)) { // Otherwise put it (possibly back) into pending. // Committing it updates the spent flags and inserts into the pool as well. commitTx(tx); } } } if (block != null) { // Mark the tx as appearing in this block so we can find it later after a re-org. This also tells the tx // confidence object about the block and sets its work done/depth appropriately. tx.setBlockAppearance(block, bestChain, relativityOffset); if (bestChain) { // Don't notify this tx of work done in notifyNewBestBlock which will be called immediately after // this method has been called by BlockChain for all relevant transactions. Otherwise we'd double // count. ignoreNextNewBlock.add(txHash); } } onWalletChangedSuppressions--; // Side chains don't affect confidence. if (bestChain) { // notifyNewBestBlock will be invoked next and will then call maybeQueueOnWalletChanged for us. confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.TYPE); } else { maybeQueueOnWalletChanged(); } // Inform anyone interested that we have received or sent coins but only if: // - This is not due to a re-org. // - The coins appeared on the best chain. // - We did in fact receive some new money. // - We have not already informed the user about the coins when we received the tx broadcast, or for our // own spends. If users want to know when a broadcast tx becomes confirmed, they need to use tx confidence // listeners. if (!insideReorg && bestChain) { BigInteger newBalance = getBalance(); // This is slow. log.info("Balance is now: " + bitcoinValueToFriendlyString(newBalance)); if (!wasPending) { int diff = valueDifference.compareTo(BigInteger.ZERO); // We pick one callback based on the value difference, though a tx can of course both send and receive // coins from the wallet. if (diff > 0) { queueOnCoinsReceived(tx, prevBalance, newBalance); } else if (diff < 0) { queueOnCoinsSent(tx, prevBalance, newBalance); } } checkBalanceFuturesLocked(newBalance); } informConfidenceListenersIfNotReorganizing(); checkState(isConsistent()); //saveNow(); }
From source file:com.sdcs.courierbooking.service.UserServiceImpl.java
@Override public JSONObject christmasSales(String selectedItem, String senderName, String senderPhone, String recieverName, String recieverAddress, String recieverPhone, String pincode, String surpriceNametoController, String surpriceDatetoController, String surpriceTimetoController, String photo, String totalAmount, String cod) { // TODO Auto-generated method stub String online = "online_payment"; String cash = "cod_payment"; JSONObject responceJson = new JSONObject(); String response = userDao.christmasSales(selectedItem, senderName, senderPhone, recieverName, recieverAddress, recieverPhone, pincode, surpriceNametoController, surpriceDatetoController, surpriceTimetoController, photo, totalAmount, cod); if (response != null) { responceJson.put("tracking_number", response); responceJson.put("totalamount", totalAmount); responceJson.put("cod", cod); responceJson.put("status", true); if (cod != cash) { Date date = new Date(); String strHomeaddrss = recieverAddress; String referenceNo = "00" + response + date.getTime(); responceJson.put("account_id", SdcsPaymentGatewayConstants.ACCOUNT_ID); responceJson.put("address", recieverAddress); responceJson.put("amount", totalAmount); //couriersObject.put("amount", "13.0"); responceJson.put("channel", SdcsPaymentGatewayConstants.CHANNEL); responceJson.put("city", "Bangalore"); responceJson.put("country", SdcsPaymentGatewayConstants.COUNTRY); responceJson.put("currency", SdcsPaymentGatewayConstants.CURRENCY); responceJson.put("description", "Make payment for new courier"); responceJson.put("email", "sdcs.info24@gmail.com"); responceJson.put("mode", SdcsPaymentGatewayConstants.MODE); responceJson.put("name", senderName); responceJson.put("page_id", "2197"); responceJson.put("phone", senderPhone); responceJson.put("postal_code", "000000"); responceJson.put("reference_no", referenceNo); responceJson.put("return_url", SdcsPaymentGatewayConstants.RETURN_URL); responceJson.put("state", "Karnataka"); String md5HashData = SdcsPaymentGatewayConstants.SECRET_KEY + "|" + SdcsPaymentGatewayConstants.ACCOUNT_ID + "|" + strHomeaddrss + "|" + totalAmount //+ "|" + "13.0" + "|" + SdcsPaymentGatewayConstants.CHANNEL + "|" + "Bangalore" + "|" + SdcsPaymentGatewayConstants.COUNTRY + "|" + SdcsPaymentGatewayConstants.CURRENCY + "|" + "Make payment for new courier" + "|" + "sdcs.info24@gmail.com" + "|" + SdcsPaymentGatewayConstants.MODE + "|" + senderName + "|" + "2197" + "|" + senderPhone + "|" + "000000" + "|" + referenceNo + "|" + SdcsPaymentGatewayConstants.RETURN_URL + "|" + "Karnataka"; System.out.println("Values Before Hashing:" + md5HashData); SdcsPersistantValues.setPersistantValues(senderName, "sdcs.info24@gmail.com", senderPhone, response + "", "SANTA"); responceJson.put("hash_values", md5HashData); String hasedValue;// w w w . j a v a 2s .c om try { hasedValue = SdcsHashProvider.generateMd5Hash(md5HashData); responceJson.put("secure_hash", hasedValue); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (cod != online) { String strSmsText = "Dear%20" + senderName + ",your%20santaclause%20booking%20has%20been%20confirmed%20and%20your%20reference%20number%20is%20" + response + ".%20Your%20order%20will%20be%20delivered%20soon.Thank%20you.%20"; SdcsSMSComponent.sendSms(senderPhone, strSmsText); String strSmsTexta = "A%20new%20santaclause%20booking%20done%20done%20from%20" + senderName + ".%20Reference%20id%20is%20" + response + ".Contact%20number%20is%20" + senderPhone + ""; SdcsSMSComponent.sendSms("9535337626", strSmsTexta); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); String body = "<div>" + "<h4 style='color:navy'>Dear admin.,<h4><br><br>" + "<p>A new Santa claus booking from the following details</p>" + "<table style='border:1px solid blue;border-collapse: collapse;'>" + "<tr style='border:1px solid blue'>" + "<th style='border:1px solid blue;color:red;'>" + "Date" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Item" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Oreder Id" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Sender Name" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Sender Contact Number" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Reciever Name" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Reciever Address" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Reciever Contact Number" + "</th>" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Surprice Delivery Name" + "</th>" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Surprice Delivery Date" + "</th>" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Surprice Delivery time" + "</th>" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Photo" + "</th>" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Payment Mode" + "</th>" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Total Amount" + "</th>" + "</tr>" + "<tr>" + "<td style='border:1px solid blue;color:blue;'>" + dateFormat.format(date) + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + selectedItem + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + response + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + senderName + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + senderPhone + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + recieverName + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + recieverAddress + " " + pincode + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + recieverPhone + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + surpriceNametoController + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + surpriceDatetoController + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + surpriceTimetoController + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + photo + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + cod + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + totalAmount + "</td>" + "</tr>" + "</table>" + "<br>" + "<p>Thank you.</p>" + "</div>"; SdcsEmailComponent.sendMail("sdcs2me@gmail.com", "SANTA CLAUS BOOKING", body, BigInteger.ZERO); } } else { responceJson.put("status", false); } return responceJson; }
From source file:org.apache.pig.test.TestBuiltin.java
@Test public void testAVGFinal() throws Exception { String[] avgTypes = { "AVGFinal", "DoubleAvgFinal", "LongAvgFinal", "IntAvgFinal", "FloatAvgFinal", "BigDecimalAvgFinal", "BigIntegerAvgFinal" }; String[] avgIntermediateTypes = { "AVGIntermediate", "DoubleAvgIntermediate", "LongAvgIntermediate", "IntAvgIntermediate", "FloatAvgIntermediate", "BigDecimalAvgIntermediate", "BigIntegerAvgIntermediate" }; for (int k = 0; k < avgTypes.length; k++) { EvalFunc<?> avg = evalFuncMap.get(avgTypes[k]); Tuple tup = inputMap.get(getInputType(avgTypes[k])); // To test AVGFinal, AVGIntermediate should first be called and // the output of AVGIntermediate should be supplied as input to // AVGFinal. To simulate this, we will call Intermediate twice // on the above tuple and collect the outputs and pass it to // Final. // get the right "Intermediate" EvalFunc EvalFunc<?> avgIntermediate = evalFuncMap.get(avgIntermediateTypes[k]); // The tuple we got above has a bag with input // values. Input to the Intermediate.exec() however comes // from the map which would put each value and a count of // 1 in a tuple and send it down. So lets create a bag with // tuples that have two fields - the value and a count 1. // The input has 10 values - lets put the first five of them // in the input to the first call of AVGIntermediate and the // remaining five in the second call. DataBag bg = (DataBag) tup.get(0); DataBag bg1 = bagFactory.newDefaultBag(); DataBag bg2 = bagFactory.newDefaultBag(); int i = 0; for (Tuple t : bg) { Tuple newTuple = tupleFactory.newTuple(2); newTuple.set(0, t.get(0));// w ww.j a v a 2 s .c om if (t.get(0) == null) { if (getInputType(avgTypes[k]) == "BigDecimal") { newTuple.set(1, BigDecimal.ZERO); } else if (getInputType(avgTypes[k]) == "BigInteger") { newTuple.set(1, BigInteger.ZERO); } else { newTuple.set(1, new Long(0)); } } else { if (getInputType(avgTypes[k]) == "BigDecimal") { newTuple.set(1, BigDecimal.ONE); } else if (getInputType(avgTypes[k]) == "BigInteger") { newTuple.set(1, BigInteger.ONE); } else { newTuple.set(1, new Long(1)); } } if (i < 5) { bg1.add(newTuple); } else { bg2.add(newTuple); } i++; } Tuple intermediateInput1 = tupleFactory.newTuple(); intermediateInput1.append(bg1); Object output1 = avgIntermediate.exec(intermediateInput1); Tuple intermediateInput2 = tupleFactory.newTuple(); intermediateInput2.append(bg2); Object output2 = avgIntermediate.exec(intermediateInput2); DataBag bag = Util.createBag(new Tuple[] { (Tuple) output1, (Tuple) output2 }); Tuple finalTuple = TupleFactory.getInstance().newTuple(1); finalTuple.set(0, bag); Object output = avg.exec(finalTuple); String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k]) + " ( (output) " + output + " == " + getExpected(avgTypes[k]) + " (expected) )]"; if (getInputType(avgTypes[k]) == "BigDecimal" || getInputType(avgTypes[k]) == "BigInteger") { assertEquals(msg, ((BigDecimal) getExpected(avgTypes[k])).toPlainString(), ((BigDecimal) output).toPlainString()); } else { assertEquals(msg, (Double) getExpected(avgTypes[k]), (Double) output, 0.00001); } } }
From source file:com.google.bitcoin.core.Wallet.java
/** * Handle when a transaction becomes newly active on the best chain, either due to receiving a new block or a * re-org. Places the tx into the right pool, handles coinbase transactions, handles double-spends and so on. *///from ww w .j a v a2s.com private void processTxFromBestChain(Transaction tx, boolean forceAddToPool) throws VerificationException { checkState(lock.isHeldByCurrentThread()); checkState(!pending.containsKey(tx.getHash())); // This TX may spend our existing outputs even though it was not pending. This can happen in unit // tests, if keys are moved between wallets, if we're catching up to the chain given only a set of keys, // or if a dead coinbase transaction has moved back onto the main chain. boolean isDeadCoinbase = tx.isCoinBase() && dead.containsKey(tx.getHash()); if (isDeadCoinbase) { // There is a dead coinbase tx being received on the best chain. A coinbase tx is made dead when it moves // to a side chain but it can be switched back on a reorg and 'resurrected' back to spent or unspent. // So take it out of the dead pool. log.info(" coinbase tx {} <-dead: confidence {}", tx.getHashAsString(), tx.getConfidence().getConfidenceType().name()); dead.remove(tx.getHash()); } // Update tx and other unspent/pending transactions by connecting inputs/outputs. updateForSpends(tx, true); // Now make sure it ends up in the right pool. Also, handle the case where this TX is double-spending // against our pending transactions. Note that a tx may double spend our pending transactions and also send // us money/spend our money. boolean hasOutputsToMe = tx.getValueSentToMe(this, true).compareTo(BigInteger.ZERO) > 0; if (hasOutputsToMe) { // Needs to go into either unspent or spent (if the outputs were already spent by a pending tx). if (tx.isEveryOwnedOutputSpent(this)) { log.info(" tx {} ->spent (by pending)", tx.getHashAsString()); addWalletTransaction(Pool.SPENT, tx); } else { log.info(" tx {} ->unspent", tx.getHashAsString()); addWalletTransaction(Pool.UNSPENT, tx); } } else if (tx.getValueSentFromMe(this).compareTo(BigInteger.ZERO) > 0) { // Didn't send us any money, but did spend some. Keep it around for record keeping purposes. log.info(" tx {} ->spent", tx.getHashAsString()); addWalletTransaction(Pool.SPENT, tx); } else if (forceAddToPool) { // Was manually added to pending, so we should keep it to notify the user of confidence information log.info(" tx {} ->spent (manually added)", tx.getHashAsString()); addWalletTransaction(Pool.SPENT, tx); } checkForDoubleSpendAgainstPending(tx, true); }
From source file:org.opendaylight.netvirt.vpnmanager.VpnUtil.java
static void setupSubnetMacIntoVpnInstance(DataBroker dataBroker, IMdsalApiManager mdsalManager, String vpnName, String subnetVpnName, String srcMacAddress, BigInteger dpnId, WriteTransaction writeTx, int addOrRemove) { long vpnId = getVpnId(dataBroker, vpnName); long subnetVpnId = VpnConstants.INVALID_ID; if (subnetVpnName != null) { subnetVpnId = getVpnId(dataBroker, subnetVpnName); }/*from w ww. java2 s .c om*/ if (dpnId.equals(BigInteger.ZERO)) { /* Apply the MAC on all DPNs in a VPN */ List<BigInteger> dpIds = getDpnsOnVpn(dataBroker, vpnName); if (dpIds == null || dpIds.isEmpty()) { return; } for (BigInteger dpId : dpIds) { addGwMacIntoTx(mdsalManager, srcMacAddress, writeTx, addOrRemove, vpnId, dpId, subnetVpnId); } } else { addGwMacIntoTx(mdsalManager, srcMacAddress, writeTx, addOrRemove, vpnId, dpnId, subnetVpnId); } }
From source file:com.sdcs.courierbooking.service.UserServiceImpl.java
@Override public String registerRestaurant(RestaurantRegistration restaurantRegistration) { JSONObject register = new JSONObject(); RestaurantRegistration registration_of_hotels = userDao.registerHotels(restaurantRegistration); if (registration_of_hotels != null) { try {/*from w w w . jav a 2s .co m*/ String strEmail = restaurantRegistration.getEmailId(); String strname = restaurantRegistration.getName(); String mailBody = "<b>Dear " + strname + ",</b>" + "<br>" + "<b><i> Thank you for being a part of SDCS.</i></b>" + "<br>" + "<b> Your password is:" + restaurantRegistration.getPassword() + "<b>" + "<br>" + "Thanks" + "<br>" + "SDCS Team" + "<br>" + "info@sdcs.me"; SdcsEmailComponent.sendMail(strEmail, "Welcome To SDCS", mailBody, BigInteger.ZERO); } catch (Exception e) { } register.put("result", true); register.put("RegisterId", restaurantRegistration.getUserId()); register.put("type", "1"); } else { register.put("result", false); } return register.toString(); }