List of usage examples for java.math BigInteger compareTo
public int compareTo(BigInteger val)
From source file:org.n52.wps.server.request.InputHandler.java
private IData parseBoundingBox(BoundingBoxType bbt) throws ExceptionReport { final BigInteger dim = bbt.getDimensions(); final double[] lower, upper; if (dim != null && (dim.compareTo(INT_MAX) > 0 || dim.compareTo(INT_MIN) < 0)) { throw new ExceptionReport( String.format("Unsupported BoundingBox dimension %s. Has to be betweeen %s and %s!", dim, INT_MIN, INT_MAX), ExceptionReport.INVALID_PARAMETER_VALUE); }/* w w w . j av a 2 s .com*/ try { lower = parseCoordinate(bbt.getLowerCorner()); } catch (NumberFormatException e) { throw new ExceptionReport("Invalid lower corner", ExceptionReport.INVALID_PARAMETER_VALUE, e); } try { upper = parseCoordinate(bbt.getUpperCorner()); } catch (NumberFormatException e) { throw new ExceptionReport("Invalid upper corner", ExceptionReport.INVALID_PARAMETER_VALUE, e); } if (upper.length != lower.length) { throw new ExceptionReport( String.format("Mismatching BoundingBox dimensions: %s vs %s!", upper.length, lower.length), ExceptionReport.INVALID_PARAMETER_VALUE); } if (dim != null && lower.length != dim.intValue()) { throw new ExceptionReport( String.format("Mismatching BoundingBox dimensions: %s vs %s!", dim.intValue(), lower.length), ExceptionReport.INVALID_PARAMETER_VALUE); } return new BoundingBoxData(lower, upper, bbt.getCrs()); }
From source file:piuk.blockchain.android.ui.SendCoinsFragment.java
@Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { final SendCoinsActivity activity = (SendCoinsActivity) getActivity(); final View view = inflater.inflate(R.layout.send_coins_fragment, container); final MyRemoteWallet wallet = application.getRemoteWallet(); if (wallet == null) return view; BigInteger available = null;//from ww w. j av a 2s .c o m if (application.isInP2PFallbackMode()) { try { available = application.bitcoinjWallet.getBalance(BalanceType.ESTIMATED); } catch (Exception e) { e.printStackTrace(); } } else { available = wallet.getBalance(); } receivingAddressView = (AutoCompleteTextView) view.findViewById(R.id.send_coins_receiving_address); feeContainerView = view.findViewById(R.id.send_coins_fee_container); sendCoinsFromContainer = view.findViewById(R.id.send_coins_from_container); sendCoinsFromSpinner = (Spinner) view.findViewById(R.id.send_coins_from_spinner); feeAmountView = (CurrencyAmountView) view.findViewById(R.id.send_coins_fee); sendTypeDescriptionContainer = view.findViewById(R.id.send_type_description_container); sendTypeDescription = (TextView) view.findViewById(R.id.send_type_description); sendTypeDescriptionIcon = (ImageView) view.findViewById(R.id.send_type_description_icon); { //Construct the from drop down list String[] activeAddresses = wallet.getActiveAddresses(); Map<String, String> labelMap = wallet.getLabelMap(); List<Pair<String, String>> pairs = new ArrayList<Pair<String, String>>(); for (String address : activeAddresses) { String label = labelMap.get(address); if (label == null || label.length() == 0) { label = "No Label"; } BigInteger balance = wallet.getBalance(address); if (balance.compareTo(BigInteger.ZERO) > 0) { label += " (" + WalletUtils.formatValue(balance) + " BTC)"; pairs.add(new Pair<String, String>(address, label)); } } pairs.add(0, new Pair<String, String>("Any Address", "Any Address")); sendCoinsFromSpinner.setAdapter(new SpinAdapter(activity, android.R.layout.simple_list_item_1, pairs)); } feeAmountView.setAmount(wallet.getBaseFee()); StringPairAdapter adapter = new StringPairAdapter(this.getLabelList()); receivingAddressView.setAdapter(adapter); receivingAddressView.addTextChangedListener(textWatcher); receivingAddressView.setOnTouchListener(new RightDrawableOnTouchListener(receivingAddressView) { @Override public boolean onDrawableTouch(final MotionEvent event) { activity.showQRReader(activity.new QrCodeDelagate() { @Override public void didReadQRCode(String data) { activity.handleScanURI(data); } }); return true; } }); receivingAddressErrorView = view.findViewById(R.id.send_coins_receiving_address_error); availableViewContainer = view.findViewById(R.id.send_coins_available_container); availableView = (CurrencyAmountView) view.findViewById(R.id.send_coins_available); availableView.setAmount(available); amountView = (CurrencyAmountView) view.findViewById(R.id.send_coins_amount); amountView.setListener(listener); amountView.setContextButton(R.drawable.ic_input_calculator, new OnClickListener() { public void onClick(final View v) { final FragmentTransaction ft = getFragmentManager().beginTransaction(); final Fragment prev = getFragmentManager().findFragmentByTag(AmountCalculatorFragment.FRAGMENT_TAG); if (prev != null) ft.remove(prev); ft.addToBackStack(null); final DialogFragment newFragment = new AmountCalculatorFragment( new AmountCalculatorFragment.Listener() { public void use(final BigInteger amount) { amountView.setAmount(amount); } }); newFragment.show(ft, AmountCalculatorFragment.FRAGMENT_TAG); } }); viewGo = (Button) view.findViewById(R.id.send_coins_go); viewGo.setOnClickListener(new OnClickListener() { final SendProgress progress = new SendProgress() { public void onSend(final Transaction tx, final String message) { handler.post(new Runnable() { public void run() { state = State.SENT; activity.longToast(message); Intent intent = activity.getIntent(); intent.putExtra("tx", tx.getHash()); activity.setResult(Activity.RESULT_OK, intent); activity.finish(); updateView(); } }); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } application.doMultiAddr(true); } public void onError(final String message) { handler.post(new Runnable() { public void run() { System.out.println("On Error"); if (message != null) activity.longToast(message); state = State.INPUT; updateView(); } }); } public void onProgress(final String message) { handler.post(new Runnable() { public void run() { state = State.SENDING; updateView(); } }); } public boolean onReady(Transaction tx, BigInteger fee, FeePolicy feePolicy, long priority) { boolean containsOutputLessThanThreshold = false; for (TransactionOutput output : tx.getOutputs()) { if (output.getValue().compareTo(Constants.FEE_THRESHOLD_MIN) < 0) { containsOutputLessThanThreshold = true; break; } } if (feePolicy != FeePolicy.FeeNever && fee.compareTo(BigInteger.ZERO) == 0) { if (tx.bitcoinSerialize().length > 1024 || containsOutputLessThanThreshold) { makeTransaction(FeePolicy.FeeForce); return false; } else if (priority < 97600000L) { handler.post(new Runnable() { public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage(R.string.ask_for_fee).setCancelable(false); AlertDialog alert = builder.create(); alert.setButton(AlertDialog.BUTTON_NEUTRAL, getString(R.string.continue_without_fee), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { makeTransaction(FeePolicy.FeeNever); dialog.dismiss(); } }); alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.add_fee), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { makeTransaction(FeePolicy.FeeForce); dialog.dismiss(); } }); alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); alert.show(); } }); handler.post(new Runnable() { public void run() { state = State.INPUT; updateView(); } }); return false; } } return true; } public ECKey onPrivateKeyMissing(final String address) { handler.post(new Runnable() { public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage(getString(R.string.ask_for_private_key, address)) .setCancelable(false) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { activity.scanPrivateKeyAddress = address; activity.showQRReader(activity.new QrCodeDelagate() { @Override public void didReadQRCode(String data) throws Exception { activity.handleScanPrivateKey(data); } }); } }) .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { synchronized (activity.temporaryPrivateKeys) { activity.temporaryPrivateKeys.notify(); } dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } }); try { synchronized (activity.temporaryPrivateKeys) { activity.temporaryPrivateKeys.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } return activity.temporaryPrivateKeys.get(address); } }; public void send(Address receivingAddress, BigInteger fee, FeePolicy feePolicy) { if (application.getRemoteWallet() == null) return; if (sendType != null && !sendType.equals(SendCoinsActivity.SendTypeQuickSend) && application.isInP2PFallbackMode()) { activity.longToast(R.string.only_quick_supported); return; } String[] from; if (sendType != null && sendType.equals(SendCoinsActivity.SendTypeCustomSend)) { Pair<String, String> selected = (Pair<String, String>) sendCoinsFromSpinner.getSelectedItem(); if (selected.first.equals("Any Address")) { from = wallet.getActiveAddresses(); } else { from = new String[] { selected.first.toString() }; } } else { from = wallet.getActiveAddresses(); } final BigInteger amount; if (sendType != null && sendType.equals(SendCoinsActivity.SendTypeSharedSend)) { BigDecimal amountDecimal = BigDecimal.valueOf(amountView.getAmount().doubleValue()); //Add the fee amount = amountDecimal.add(amountDecimal.divide(BigDecimal.valueOf(100)) .multiply(BigDecimal.valueOf(wallet.getSharedFee()))).toBigInteger(); } else { amount = amountView.getAmount(); } final WalletApplication application = (WalletApplication) getActivity().getApplication(); if (application.isInP2PFallbackMode()) { final long blockchainLag = System.currentTimeMillis() - service.blockChain.getChainHead().getHeader().getTime().getTime(); final boolean blockchainUptodate = blockchainLag < Constants.BLOCKCHAIN_UPTODATE_THRESHOLD_MS; if (!blockchainUptodate) { activity.longToast(R.string.blockchain_not_upto_date); return; } // create spend final SendRequest sendRequest = SendRequest.to(receivingAddress, amountView.getAmount()); sendRequest.fee = fee; new Thread(new Runnable() { public void run() { final Transaction transaction = application.bitcoinjWallet .sendCoinsOffline(sendRequest); handler.post(new Runnable() { public void run() { if (transaction != null) { state = State.SENDING; updateView(); service.broadcastTransaction(transaction); state = State.SENT; activity.longToast(R.string.wallet_transactions_fragment_tab_sent); Intent intent = activity.getIntent(); intent.putExtra("tx", transaction.getHash()); activity.setResult(Activity.RESULT_OK, intent); activity.finish(); updateView(); EventListeners.invokeOnTransactionsChanged(); } else { state = State.INPUT; updateView(); activity.longToast(R.string.send_coins_error_msg); } } }); } }).start(); } else { application.getRemoteWallet().sendCoinsAsync(from, receivingAddress.toString(), amount, feePolicy, fee, progress); } } public void makeTransaction(FeePolicy feePolicy) { if (application.getRemoteWallet() == null) return; try { MyRemoteWallet wallet = application.getRemoteWallet(); BigInteger baseFee = wallet.getBaseFee(); BigInteger fee = null; if (feePolicy == FeePolicy.FeeForce) { fee = baseFee; } else if (sendType != null && sendType.equals(SendCoinsActivity.SendTypeCustomSend)) { feePolicy = FeePolicy.FeeOnlyIfNeeded; fee = feeAmountView.getAmount(); } else { fee = (wallet.getFeePolicy() == 1) ? baseFee : BigInteger.ZERO; } final BigInteger finalFee = fee; final FeePolicy finalFeePolicy = feePolicy; if (sendType != null && sendType.equals(SendCoinsActivity.SendTypeSharedSend)) { new Thread(new Runnable() { @Override public void run() { try { final String addressString = MyRemoteWallet .generateSharedAddress(getToAddress()); handler.post(new Runnable() { @Override public void run() { try { send(new Address(Constants.NETWORK_PARAMETERS, addressString), finalFee, finalFeePolicy); } catch (Exception e) { e.printStackTrace(); Toast.makeText(application, e.getLocalizedMessage(), Toast.LENGTH_LONG).show(); } } }); } catch (final Exception e) { handler.post(new Runnable() { @Override public void run() { e.printStackTrace(); Toast.makeText(application, e.getLocalizedMessage(), Toast.LENGTH_LONG) .show(); } }); } } }).start(); } else { String addressString = getToAddress(); Address receivingAddress = new Address(Constants.NETWORK_PARAMETERS, addressString); send(receivingAddress, fee, feePolicy); } } catch (Exception e) { e.printStackTrace(); } } public void onClick(final View v) { if (application.getRemoteWallet() == null) return; MyRemoteWallet remoteWallet = application.getRemoteWallet(); if (remoteWallet.isDoubleEncrypted() == false) { makeTransaction(FeePolicy.FeeOnlyIfNeeded); } else { if (remoteWallet.temporySecondPassword == null) { RequestPasswordDialog.show(getFragmentManager(), new SuccessCallback() { public void onSuccess() { makeTransaction(FeePolicy.FeeOnlyIfNeeded); } public void onFail() { Toast.makeText(application, R.string.send_no_password_error, Toast.LENGTH_LONG) .show(); } }, RequestPasswordDialog.PasswordTypeSecond); } else { makeTransaction(FeePolicy.FeeOnlyIfNeeded); } } } }); viewCancel = (Button) view.findViewById(R.id.send_coins_cancel); viewCancel.setOnClickListener(new OnClickListener() { public void onClick(final View v) { activity.setResult(Activity.RESULT_CANCELED); activity.finish(); } }); activity.setOnChangedSendTypeListener(new OnChangedSendTypeListener() { @Override public void onChangedSendType(String type) { sendType = type; feeContainerView.setVisibility(View.GONE); sendCoinsFromContainer.setVisibility(View.GONE); availableViewContainer.setVisibility(View.VISIBLE); sendTypeDescriptionContainer.setVisibility(View.GONE); if (type.equals(SendCoinsActivity.SendTypeCustomSend)) { feeContainerView.setVisibility(View.VISIBLE); sendCoinsFromContainer.setVisibility(View.VISIBLE); availableViewContainer.setVisibility(View.GONE); } else if (type.equals(SendCoinsActivity.SendTypeSharedSend)) { sendTypeDescriptionContainer.setVisibility(View.VISIBLE); sendTypeDescription .setText(getString(R.string.shared_send_description, wallet.getSharedFee() + "%")); sendTypeDescriptionIcon.setImageResource(R.drawable.ic_icon_shared); } } }); updateView(); return view; }
From source file:ja.ohac.wallet.ui.SendCoinsFragment.java
private void handleGo() { state = State.PREPARATION;/*from w w w . ja v a 2 s . c om*/ updateView(); // create spend final BigInteger amount = amountCalculatorLink.getAmount(); final SendRequest sendRequest = SendRequest.to(validatedAddress.address, amount); sendRequest.changeAddress = WalletUtils.pickOldestKey(wallet).toAddress(Constants.NETWORK_PARAMETERS); sendRequest.emptyWallet = amount.equals(wallet.getBalance(BalanceType.AVAILABLE)); //Emptying a wallet with less than 2 DOGE can't be possible due to min fee 2 DOGE of such a tx. if (amount.compareTo(BigInteger.valueOf(200000000)) < 0 && sendRequest.emptyWallet) { AlertDialog.Builder bld = new AlertDialog.Builder(activity); bld.setTitle(R.string.send_coins_error_msg); bld.setMessage(R.string.send_coins_error_desc); bld.setNeutralButton(activity.getResources().getString(android.R.string.ok), null); bld.setCancelable(false); bld.create().show(); state = State.FAILED; updateView(); return; } new SendCoinsOfflineTask(wallet, backgroundHandler) { @Override protected void onSuccess(final Transaction transaction) { sentTransaction = transaction; state = State.SENDING; updateView(); sentTransaction.getConfidence().addEventListener(sentTransactionConfidenceListener); if (bluetoothAdapter != null && bluetoothAdapter.isEnabled() && bluetoothMac != null && bluetoothEnableView.isChecked()) { new SendBluetoothTask(bluetoothAdapter, backgroundHandler) { @Override protected void onResult(final boolean ack) { bluetoothAck = ack; if (state == State.SENDING) state = State.SENT; updateView(); } }.send(bluetoothMac, transaction); // send asynchronously } application.broadcastTransaction(sentTransaction); final Intent result = new Intent(); BitcoinIntegration.transactionHashToResult(result, sentTransaction.getHashAsString()); activity.setResult(Activity.RESULT_OK, result); } @Override protected void onFailure() { state = State.FAILED; activity.runOnUiThread(new Runnable() { @Override public void run() { updateView(); AlertDialog.Builder bld = new AlertDialog.Builder(activity); bld.setTitle(R.string.send_coins_error_msg); bld.setMessage(R.string.send_coins_error_desc); bld.setNeutralButton(activity.getResources().getString(android.R.string.ok), null); bld.setCancelable(false); bld.create().show(); } }); } }.sendCoinsOffline(sendRequest); // send asynchronously }
From source file:com.ephesoft.dcma.tablefinder.share.DataTableService.java
/** * Sorts table columns list on the basis of their column header start coordinates. * /*from w w w.j a va 2 s . c om*/ * @param tableColumnList {@link List}<{@link TableColumnVO}> * @param colHeaderInfoMap {@link List}<{@link String}, {@link DataCarrier}> */ private void sortTableColumns(final List<TableColumnVO> tableColumnList, final Map<String, DataCarrier> colHeaderInfoMap) { LOGGER.info("Sorting table columns based on their table headers."); if (CollectionUtils.isNotEmpty(tableColumnList) && null != colHeaderInfoMap && !colHeaderInfoMap.isEmpty()) { Collections.sort(tableColumnList, new Comparator<TableColumnVO>() { @Override public int compare(final TableColumnVO object1, final TableColumnVO object2) { int comparison; if (null == object1 || null == object2) { comparison = TableExtractionConstants.EQUAL_COMPARISON; } else { final String headerMapColumnNameForObject1 = object1.getColumnName(); final String headerMapColumnNameForObject2 = object2.getColumnName(); final DataCarrier colHeaderInfoObject1 = colHeaderInfoMap .get(headerMapColumnNameForObject1); final DataCarrier colHeaderInfoObject2 = colHeaderInfoMap .get(headerMapColumnNameForObject2); if (null == colHeaderInfoObject1 || null == colHeaderInfoObject2) { comparison = TableExtractionConstants.EQUAL_COMPARISON; } else { // Getting coordinates of spans of two table columns. final Coordinates object1SpanHeaderCoordinates = colHeaderInfoObject1.getCoordinates(); final Coordinates object2SpanHeaderCoordinates = colHeaderInfoObject2.getCoordinates(); if (null == object1SpanHeaderCoordinates || null == object2SpanHeaderCoordinates) { comparison = TableExtractionConstants.EQUAL_COMPARISON; } else { // Comparing start coordinates of headers of two input table columns. final BigInteger startCoordinateHeader1 = object1SpanHeaderCoordinates.getX0(); final BigInteger startCoordinateHeader2 = object2SpanHeaderCoordinates.getX0(); if (null == startCoordinateHeader1 && null == startCoordinateHeader2) { comparison = TableExtractionConstants.EQUAL_COMPARISON; } else if (null == startCoordinateHeader1) { comparison = TableExtractionConstants.LESS_COMPARISON; } else if (null == startCoordinateHeader2) { comparison = TableExtractionConstants.GREATER_COMPARISON; } else { comparison = startCoordinateHeader1.compareTo(startCoordinateHeader2); } } } } return comparison; } }); } }
From source file:org.openspaces.admin.internal.pu.DefaultProcessingUnit.java
@Override public boolean waitFor(QuiesceState desiredState, long timeout, TimeUnit timeUnit) { if (!isManaged()) { throw new AdminException("No managing GSM to execute quiesce"); }/*from www. j a v a 2s .c o m*/ long interval = 1000; long expiration; // checking long overflow to set the expiration time properly BigInteger sum = BigInteger.valueOf(0); sum = sum.add(BigInteger.valueOf(System.currentTimeMillis())) .add(BigInteger.valueOf(timeUnit.toMillis(timeout))); if (sum.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) expiration = Long.MAX_VALUE; else expiration = sum.longValue(); for (;;) { QuiesceDetails currentDetails = getQuiesceDetails(); if (instancesReachedQuiesceState(desiredState, currentDetails)) { return true; } try { Thread.sleep(interval); if (System.currentTimeMillis() >= expiration) { return false; } } catch (InterruptedException e) { return false; } } }
From source file:org.estatio.api.Api.java
@ActionSemantics(Of.IDEMPOTENT) public void putLeasePostalAddress(@Named("partyReference") final String partyReference, @Named("agreementRoleType") final String agreementRoleType, @Named("leaseReference") @Optional final String leaseReference, @Named("address1") @Optional final String address1, @Named("address2") @Optional final String address2, @Named("address3") @Optional final String address3, @Named("postalCode") @Optional final String postalCode, @Named("city") @Optional final String city, @Named("stateCode") @Optional final String stateCode, @Named("countryCode") @Optional final String countryCode, @Named("isInvoiceAddress") @Optional final BigInteger isInvoiceAddress) { if (address1 != null && partyReference != null && leaseReference != null) { final Lease lease = fetchLease(leaseReference); final Party party = fetchParty(partyReference); final AgreementRoleCommunicationChannelType agreementRoleCommunicationChannelType = agreementRoleCommunicationChannelTypes .findByTitle(//w ww . j a va 2 s . com isInvoiceAddress.compareTo(BigInteger.ZERO) == 0 ? LeaseConstants.ARCCT_INVOICE_ADDRESS : LeaseConstants.ARCCT_ADMINISTRATION_ADDRESS); if (agreementRoleCommunicationChannelType == null) throw new ApplicationException(String.format("AgreementRoleCommunicationChannelType not found.")); PostalAddress address = (PostalAddress) postalAddresses.findByAddress(party, address1, postalCode, city, fetchCountry(countryCode)); if (address == null) { address = communicationChannels.newPostal(party, CommunicationChannelType.POSTAL_ADDRESS, address1, address2, null, postalCode, city, fetchState(stateCode, false), fetchCountry(countryCode, false)); } final AgreementRoleType art = agreementRoleTypes .findByTitle(StringUtils.capitalize(agreementRoleType.toLowerCase())); if (art == null) throw new ApplicationException(String.format("AgreementRoleType %s not found.", agreementRoleType)); final AgreementRole role = lease.findRole(party, art, clockService.now()); if (role == null) throw new ApplicationException( String.format("Role for %s, %s not found.", partyReference, agreementRoleType)); role.addCommunicationChannel(agreementRoleCommunicationChannelType, address); } }
From source file:com.flexive.core.storage.genericSQL.GenericTreeStorageSpreaded.java
/** * Helper function to create a new node. * * @param con an open and valid connection * @param seq reference to a sequencer * @param ce reference to the content engine * @param mode Live or Edit mode * @param parentNodeId the parent node (1=root) * @param name the name of the new node (only informative value) * @param label label for Caption property (only used if new reference is created) * @param position the position within the childs (0 based, Integer.MAX_VALUE may be used to * append to the end) * @param reference a reference to an existing content (must exist!) * @param data the optional data * @param nodeId the id to use or create a new one if < 0 * @param activateContent change the step of contents that have no live step to live in the max version? * @return the used or created node id//from ww w . ja v a2 s. c om * @throws FxTreeException if the function fails */ private long _createNode(Connection con, SequencerEngine seq, ContentEngine ce, FxTreeMode mode, long parentNodeId, String name, FxString label, int position, FxPK reference, String data, long nodeId, boolean activateContent) throws FxApplicationException { // acquire exclusive lock for parent node acquireLocksForUpdate(con, mode, Arrays.asList(parentNodeId)); // makeSpace(con, seq/*irrelevant*/, mode, parentNodeId, position/*irrelevant*/, 1); FxTreeNodeInfoSpreaded parentNode = (FxTreeNodeInfoSpreaded) getTreeNodeInfo(con, mode, parentNodeId); BigInteger boundaries[] = getBoundaries(con, parentNode, position); BigInteger leftBoundary = boundaries[0]; //== left border BigInteger rightBoundary = boundaries[1]; //== right border // Node has to be inserted between the left and right boundary and needs 2 slots for its left and right border BigInteger spacing = rightBoundary.subtract(leftBoundary).subtract(TWO); // Compute spacing for left,inner and right part spacing = spacing.divide(THREE); // We need at least 2 open slots (for the left and right boundary of the new node) //if the spacing is <= 0 we need more space if (spacing.compareTo(BigInteger.ZERO) <= 0/*less than*/) { throw new FxTreeException("ex.tree.create.noSpace", parentNodeId); } // try to use space more efficiently for flat structures, otherwise the first node of a folder // will get a third of the subtree space, the second one ninth, and so on. // Maxspacing indicates the number of nodes (*2) we expect to put in this node before space reorg spacing = spacing.compareTo(DEFAULT_NODE_SPACING) > 0 ? DEFAULT_NODE_SPACING : spacing; // final BigInteger left = leftBoundary.add(spacing).add(BigInteger.ONE); // don't add gap to left boundary (doesn't seem to have any benefits since that space is lost // unless the tree is reorganized anyway final BigInteger left = leftBoundary.add(BigInteger.ONE); final BigInteger right = left.add(spacing).add(BigInteger.ONE); NodeCreateInfo nci = getNodeCreateInfo(mode, seq, ce, nodeId, name, label, reference, activateContent); // Create the node PreparedStatement ps = null; try { ps = con.prepareStatement("INSERT INTO " + getTable(mode) + " (ID,PARENT,DEPTH,DIRTY,REF,LFT,RGT," + "CHILDCOUNT,NAME,MODIFIED_AT,TEMPLATE) VALUES " + "(" + nci.id + "," + parentNodeId + "," + (parentNode.getDepth() + 1) + ",?," + nci.reference.getId() + ",?,?,0,?," + StorageManager.getTimestampFunction() + ",?)"); ps.setBoolean(1, mode != FxTreeMode.Live); setNodeBounds(ps, 2, left); setNodeBounds(ps, 3, right); ps.setString(4, FxFormatUtils.escapeTreePath(nci.name)); if (StringUtils.isEmpty(data)) { ps.setNull(5, java.sql.Types.VARCHAR); } else { ps.setString(6, data); } ps.executeUpdate(); ps.close(); //update the parents childcount ps = con.prepareStatement( "UPDATE " + getTable(mode) + " SET CHILDCOUNT=CHILDCOUNT+1 WHERE ID=" + parentNodeId); ps.executeUpdate(); } catch (SQLException e) { throw new FxTreeException(LOG, e, "ex.db.sqlError", e.getMessage()); } finally { try { if (ps != null) ps.close(); } catch (Throwable t) { /*ignore*/ } } return nci.id; }
From source file:com.ephesoft.dcma.tablefinder.share.TableRowFinderUtility.java
/** * Method to check if span is valid with respect to the column header specified by admin. * // ww w . jav a 2 s .c o m * @param valueCoordinates {@link Coordinates} * @param headerSpan {@link Coordinates} * @param isFirstPage {@link Boolean} * @return boolean */ private static boolean isValidCoordinatesWithColumnHeader(final Coordinates valueCoordinates, final Coordinates headerSpanHocrCoordinates, final Boolean isFirstPage) { LOGGER.info("Entering method isValidCoordinatesWithColumnHeader."); boolean isValid = false; if (null != headerSpanHocrCoordinates && null != valueCoordinates) { final BigInteger outputSpanX0 = valueCoordinates.getX0(); final BigInteger outputSpanX1 = valueCoordinates.getX1(); final BigInteger outputSpanY0 = valueCoordinates.getY0(); final BigInteger headerSpanX0 = headerSpanHocrCoordinates.getX0(); final BigInteger headerSpanX1 = headerSpanHocrCoordinates.getX1(); final BigInteger headerSpanY1 = headerSpanHocrCoordinates.getY1(); LOGGER.info("Value Coordinates: X0=", outputSpanX0, ", X1=", outputSpanX1, ", Y0=", outputSpanY0); LOGGER.info("Column Header Coordinates: X0=", headerSpanX0, ", X1=", headerSpanX1, ", Y1=", headerSpanY1); if (outputSpanX0 != null && outputSpanX0 != null && outputSpanY0 != null && headerSpanX0 != null && headerSpanX1 != null && headerSpanY1 != null) { if (((outputSpanX0.compareTo(headerSpanX0) == 1 && outputSpanX0.compareTo(headerSpanX1) == -1) || (outputSpanX1.compareTo(headerSpanX0) == 1 && outputSpanX1.compareTo(headerSpanX1) == -1) || (outputSpanX0.compareTo(headerSpanX0) == -1 && outputSpanX1.compareTo(headerSpanX1) == 1) || outputSpanX0.compareTo(headerSpanX0) == 0 || outputSpanX1.compareTo(headerSpanX1) == 0)) { if (null != isFirstPage && isFirstPage) { if (outputSpanY0.compareTo(headerSpanY1) == 1) { isValid = true; } } else { isValid = true; } } } LOGGER.info("Is span valid with column header : ", isValid); } LOGGER.info("Exiting method isValidCoordinatesWithColumnHeader."); return isValid; }
From source file:com.bitsofproof.supernode.core.CachedBlockStore.java
private void lockedStoreBlock(Blk b) throws ValidationException { CachedBlock cached = cachedBlocks.get(b.getHash()); if (cached != null) { return;/*from w w w .j a va 2s . com*/ } log.trace("Start storing block " + b.getHash()); // find previous block CachedBlock cachedPrevious = cachedBlocks.get(b.getPreviousHash()); if (cachedPrevious == null) { throw new ValidationException("Does not connect to a known block " + b.getHash()); } Blk prev = null; prev = retrieveBlockHeader(cachedPrevious); if (b.getCreateTime() > (System.currentTimeMillis() / 1000) * 2 * 60 * 60 || b.getCreateTime() <= getMedianTimePast(cachedPrevious)) { throw new ValidationException("Block timestamp out of bounds " + b.getHash()); } boolean checkV2BlockCoinBase = false; if (chain.isProduction()) { if (enforceV2Block || isSuperMajority(2, cachedPrevious, 950, 1000)) { if (!enforceV2Block) { log.trace("Majority for V2 blocks reached, enforcing"); } enforceV2Block = true; if (b.getVersion() < 2) { throw new ValidationException("Rejecting version 1 block " + b.getHash()); } } checkV2BlockCoinBase = b.getVersion() >= 2 && isSuperMajority(2, cachedPrevious, 750, 1000); } Head head; CachedHead cachedPreviousHead = cachedHeads.get(prev.getHeadId()); Head previousHead = retrieveHead(cachedPreviousHead); if (previousHead.getLeaf().equals(prev.getHash())) { // continuing head = previousHead; head.setLeaf(b.getHash()); head.setHeight(head.getHeight() + 1); head.setChainWork(prev.getChainWork() + Difficulty.getDifficulty(b.getDifficultyTarget(), chain)); head = updateHead(head); } else { // branching head = new Head(); head.setPreviousId(prev.getHeadId()); head.setPreviousHeight(prev.getHeight()); head.setLeaf(b.getHash()); head.setHeight(prev.getHeight() + 1); head.setChainWork(prev.getChainWork() + Difficulty.getDifficulty(b.getDifficultyTarget(), chain)); insertHead(head); } b.setHeadId(head.getId()); b.setHeight(head.getHeight()); b.setChainWork(head.getChainWork()); if (b.getHeight() >= chain.getDifficultyReviewBlocks() && b.getHeight() % chain.getDifficultyReviewBlocks() == 0) { long periodLength = computePeriodLength(cachedPrevious, prev.getCreateTime(), chain.getDifficultyReviewBlocks()); long next = Difficulty.getNextTarget(periodLength, prev.getDifficultyTarget(), chain); if (chain.isProduction() && next != b.getDifficultyTarget()) { throw new ValidationException( "Difficulty does not match expectation " + b.getHash() + " " + b.toWireDump()); } } else { if (chain.isProduction() && b.getDifficultyTarget() != prev.getDifficultyTarget()) { throw new ValidationException("Illegal attempt to change difficulty " + b.getHash()); } } b.checkHash(); if (chain.isProduction() && checkPoints.containsKey(b.getHeight())) { if (!checkPoints.get(b.getHeight()).equals(b.getHash())) { throw new ValidationException("Checkpoint missed"); } } BigInteger hashAsInteger = new Hash(b.getHash()).toBigInteger(); if (chain.isProduction() && hashAsInteger.compareTo(Difficulty.getTarget(b.getDifficultyTarget())) > 0) { throw new ValidationException( "Insufficuent proof of work for current difficulty " + b.getHash() + " " + b.toWireDump()); } b.parseTransactions(); if (b.getTransactions().isEmpty()) { throw new ValidationException("Block must have transactions " + b.getHash() + " " + b.toWireDump()); } for (Tx t : b.getTransactions()) { if (!isFinal(t, b)) { throw new ValidationException("Transactions in a block must be final"); } } b.checkMerkleRoot(); ImplementTxOutCacheDelta deltaUTXO = new ImplementTxOutCacheDelta(cachedUTXO); CachedBlock trunkBlock = cachedPrevious; List<CachedBlock> pathFromTrunkToPrev = new ArrayList<CachedBlock>(); while (!isOnTrunk(trunkBlock.getHash())) { pathFromTrunkToPrev.add(trunkBlock); trunkBlock = trunkBlock.getPrevious(); } Collections.reverse(pathFromTrunkToPrev); if (trunkBlock.getHeight() < (currentHead.getLast().getHeight() - FORCE_TRUNK)) { throw new ValidationException("Attempt to build on or create a branch too far back in history"); } if (currentHead.getLast() != cachedPrevious) { CachedBlock q = currentHead.getLast(); CachedBlock p = q.previous; while (!q.getHash().equals(trunkBlock.getHash())) { Blk block = retrieveBlock(q); backwardCache(block, deltaUTXO, false); q = p; p = q.previous; } for (CachedBlock block : pathFromTrunkToPrev) { forwardCache(retrieveBlock(block), deltaUTXO, false); } } final TransactionContext tcontext = new TransactionContext(); tcontext.block = b; tcontext.resolvedInputs = deltaUTXO; log.trace("resolving inputs for block " + b.getHash()); Set<String> txs = new HashSet<String>(); int numberOfOutputs = 0; for (Tx t : b.getTransactions()) { txs.add(t.getHash()); resolveInputs(tcontext.resolvedInputs, b.getHeight(), t); for (TxOut o : t.getOutputs()) { o.setHeight(b.getHeight()); tcontext.resolvedInputs.add(o); ++numberOfOutputs; } } if (!chain.isProduction() || b.getHeight() > lastCheckPoint || chain.checkBeforeCheckpoint()) { log.trace("validating block " + b.getHash()); // BIP30 if (currentHead.getLast() != cachedPrevious) { for (CachedBlock bl : pathFromTrunkToPrev) { Blk block = retrieveBlock(bl); for (Tx t : block.getTransactions()) { if (txs.contains(t.getHash())) { throw new ValidationException( "BIP30 violation: block contains spent tx " + t.getHash()); } } } } checkBIP30Compliance(txs, trunkBlock.height); List<Callable<TransactionValidationException>> callables = new ArrayList<Callable<TransactionValidationException>>(); for (final Tx t : b.getTransactions()) { if (tcontext.coinbase) { if (!isCoinBase(t)) { throw new ValidationException("The first transaction of a block must be coinbase"); } try { if (checkV2BlockCoinBase) { ScriptFormat.Reader reader = new ScriptFormat.Reader(t.getInputs().get(0).getScript()); int len = reader.readByte(); if (ScriptFormat.intValue(reader.readBytes(len)) != b.getHeight()) { throw new ValidationException("Block height mismatch in coinbase"); } } validateTransaction(tcontext, t); } catch (TransactionValidationException e) { throw new ValidationException(e.getMessage() + " " + t.toWireDump(), e); } tcontext.coinbase = false; } else { if (isCoinBase(t)) { throw new ValidationException("Only the first transaction of a block can be coinbase"); } callables.add(new Callable<TransactionValidationException>() { @Override public TransactionValidationException call() { try { validateTransaction(tcontext, t); } catch (TransactionValidationException e) { return e; } catch (Exception e) { return new TransactionValidationException(e, t); } return null; } }); } } try { for (Future<TransactionValidationException> e : transactionsProcessor.invokeAll(callables)) { try { if (e.get() != null) { throw new ValidationException(e.get().getMessage() + " " + e.get().getIn() + " " + e.get().getTx().toWireDump(), e.get()); } } catch (ExecutionException e1) { throw new ValidationException("corrupted transaction processor", e1); } } } catch (InterruptedException e1) { throw new ValidationException("interrupted", e1); } if (tcontext.nsigs > MAX_BLOCK_SIGOPS) { throw new ValidationException("too many signatures in this block "); } // block reward could actually be less... as in 0000000000004c78956f8643262f3622acf22486b120421f893c0553702ba7b5 if (tcontext.blkSumOutput.subtract(tcontext.blkSumInput).longValue() > chain .getRewardForHeight(b.getHeight())) { throw new ValidationException("Invalid block reward " + b.getHash() + " " + b.toWireDump()); } } // this is last loop before persist since modifying the entities. BloomFilter filter = BloomFilter.createOptimalFilter(Math.max(5 * numberOfOutputs, 500), 1.0e-8, 0, UpdateMode.none); for (Tx t : b.getTransactions()) { t.setBlock(b); List<ColoredCoin> inputCoins = new ArrayList<ColoredCoin>(); for (TxIn i : t.getInputs()) { if (!i.getSourceHash().equals(Hash.ZERO_HASH_STRING)) { filter.addOutpoint(i.getSourceHash(), i.getIx()); try { for (Token token : ScriptFormat.parse(i.getScript())) { if (token.data != null) { filter.add(token.data); } } } catch (Exception e) { // this is best effort } TxOut source = tcontext.resolvedInputs.get(i.getSourceHash(), i.getIx()); if (source.getId() == null) { i.setSource(source); } else { i.setSource(getSourceReference(source)); } ColoredCoin c = new ColoredCoin(); c.color = source.getColor(); c.value = source.getValue(); inputCoins.add(c); } } List<ColoredCoin> outputCoins = new ArrayList<ColoredCoin>(); for (TxOut o : t.getOutputs()) { ColoredCoin c = new ColoredCoin(); c.color = null; c.value = o.getValue(); outputCoins.add(c); } ColorRules.colorOutput(inputCoins, outputCoins); Iterator<ColoredCoin> i = outputCoins.iterator(); for (TxOut o : t.getOutputs()) { o.setColor(i.next().color); try { for (Token token : ScriptFormat.parse(o.getScript())) { if (token.data != null) { filter.add(token.data); } } } catch (Exception e) { // this is best effort } o.setTxHash(t.getHash()); o.setHeight(b.getHeight()); } } b.setFilterFunctions((int) filter.getHashFunctions()); b.setFilterMap(filter.getFilter()); log.trace("storing block " + b.getHash()); insertBlock(b); // modify transient caches only after persistent changes CachedBlock m = new CachedBlock(b.getHash(), b.getId(), cachedBlocks.get(b.getPreviousHash()), b.getCreateTime(), b.getHeight(), (int) b.getVersion(), b.getFilterMap(), b.getFilterFunctions()); cachedBlocks.put(b.getHash(), m); CachedHead usingHead = cachedHeads.get(head.getId()); if (usingHead == null) { cachedHeads.put(head.getId(), usingHead = new CachedHead()); usingHead.id = head.getId(); usingHead.previous = cachedHeads.get(head.getPreviousId()); usingHead.previousHeight = b.getHeight() - 1; } usingHead.setChainWork(b.getChainWork()); usingHead.setHeight(b.getHeight()); usingHead.getBlocks().add(m); final List<Blk> removedBlocks = new ArrayList<Blk>(); final List<Blk> addedBlocks = new ArrayList<Blk>(); if (ByteUtils.isLessThanUnsigned(currentHead.getChainWork(), usingHead.getChainWork())) { // we have a new trunk CachedBlock p = currentHead.getLast(); CachedBlock q = p.previous; while (!p.equals(trunkBlock)) { Blk block = retrieveBlock(p); backwardCache(block, cachedUTXO, true); removedBlocks.add(block); p = q; q = p.previous; } List<CachedBlock> pathToNewHead = new ArrayList<CachedBlock>(); p = m; q = p.previous; while (!q.equals(trunkBlock)) { pathToNewHead.add(q); p = q; q = p.previous; } Collections.reverse(pathToNewHead); for (CachedBlock cb : pathToNewHead) { Blk block = retrieveBlock(cb); forwardCache(block, cachedUTXO, true); addedBlocks.add(block); } forwardCache(b, cachedUTXO, true); addedBlocks.add(b); currentHead = usingHead; } else if (currentHead.getLast() == cachedPrevious) { forwardCache(b, cachedUTXO, true); addedBlocks.add(b); currentHead = usingHead; } usingHead.setLast(m); log.debug("stored block " + b.getHeight() + " " + b.getHash()); if (!removedBlocks.isEmpty() || !addedBlocks.isEmpty()) { for (TrunkListener l : trunkListener) { l.trunkUpdate(removedBlocks, addedBlocks); } } }
From source file:com.flexive.core.storage.genericSQL.GenericTreeStorageSpreaded.java
/** * {@inheritDoc}/*from ww w . j a v a 2s .com*/ */ @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); } }