List of usage examples for java.math BigInteger longValue
public long longValue()
From source file:io.instacount.appengine.counter.service.ShardedCounterServiceImpl.java
/** * Increment the memcache version of the named-counter by {@code amount} (positive or negative) in an atomic * fashion. Use memcache as a Semaphore/Mutex, and retry up to 10 times if other threads are attempting to update * memcache at the same time. If nothing is in Memcache when this function is called, then do nothing because only * #getCounter should "put" a value to memcache. Additionally, if this operation fails, the cache will be * re-populated after a configurable amount of time, so the count will eventually become correct. * * @param counterName/*from w w w.j av a 2 s. c o m*/ * @param amount * @return The new count of this counter as reflected by memcache */ @VisibleForTesting protected Optional<Long> incrementMemcacheAtomic(final String counterName, final long amount) { Preconditions.checkNotNull(counterName); // Get the cache counter at a current point in time. String memCacheKey = this.assembleCounterKeyforMemcache(counterName); for (int currentRetry = 0; currentRetry < NUM_RETRIES_LIMIT; currentRetry++) { try { final IdentifiableValue identifiableCounter = memcacheService.getIdentifiable(memCacheKey); // See Javadoc about a null identifiableCounter. If it's null, then the named counter doesn't exist in // memcache. if (identifiableCounter == null || (identifiableCounter != null && identifiableCounter.getValue() == null)) { final String msg = "No identifiableCounter was found in Memcache. Unable to Atomically increment for CounterName '%s'. Memcache will be populated on the next called to getCounter()!"; logger.log(Level.FINEST, String.format(msg, counterName)); // This will return an absent value. Only #getCounter should "put" a value to memcache. break; } // If we get here, the count exists in memcache, so it can be atomically incremented/decremented. final BigInteger cachedCounterAmount = (BigInteger) identifiableCounter.getValue(); final long newMemcacheAmount = cachedCounterAmount.longValue() + amount; logger.log(Level.FINEST, String.format("Just before Atomic Increment of %s, Memcache has value: %s", amount, identifiableCounter.getValue())); if (memcacheService.putIfUntouched(counterName, identifiableCounter, BigInteger.valueOf(newMemcacheAmount), config.getDefaultCounterCountExpiration())) { logger.log(Level.FINEST, String.format("MemcacheService.putIfUntouched SUCCESS! with value: %s", newMemcacheAmount)); // If we get here, the put succeeded... return Optional.of(new Long(newMemcacheAmount)); } else { logger.log(Level.WARNING, String.format( "Unable to update memcache counter atomically. Retrying %s more times...", (NUM_RETRIES_LIMIT - currentRetry))); continue; } } catch (MemcacheServiceException mse) { // Check and post-decrement the numRetries counter in one step if ((currentRetry + 1) < NUM_RETRIES_LIMIT) { logger.log(Level.WARNING, String.format( "Unable to update memcache counter atomically. Retrying %s more times...", (NUM_RETRIES_LIMIT - currentRetry))); // Keep trying... continue; } else { // Evict the counter here, and let the next call to getCounter populate memcache final String logMessage = "Unable to update memcache counter atomically, with no more allowed retries. Evicting counter named '%s' from the cache!"; logger.log(Level.SEVERE, String.format(logMessage, (NUM_RETRIES_LIMIT - currentRetry)), mse); this.memcacheSafeDelete(memCacheKey); break; } } } // The increment did not work... return Optional.absent(); }
From source file:ja.ohac.wallet.ui.send.RequestWalletBalanceTask.java
public void requestWalletBalance(final Address... addresses) { backgroundHandler.post(new Runnable() { @Override//from w w w . j a va 2 s .c om public void run() { final StringBuilder url = new StringBuilder(Constants.BITEASY_API_URL); url.append("unspent-outputs"); url.append("?per_page=MAX"); for (final Address address : addresses) url.append("&address[]=").append(address.toString()); log.debug("trying to request wallet balance from {}", url); HttpURLConnection connection = null; Reader reader = null; try { connection = (HttpURLConnection) new URL(url.toString()).openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(false); connection.setRequestMethod("GET"); if (userAgent != null) connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Charsets.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); final JSONObject json = new JSONObject(content.toString()); final int status = json.getInt("status"); if (status != 200) throw new IOException("api status " + status + " when fetching unspent outputs"); final JSONObject jsonData = json.getJSONObject("data"); final JSONObject jsonPagination = jsonData.getJSONObject("pagination"); if (!"false".equals(jsonPagination.getString("next_page"))) throw new IllegalStateException("result set too big"); final JSONArray jsonOutputs = jsonData.getJSONArray("outputs"); final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>( jsonOutputs.length()); for (int i = 0; i < jsonOutputs.length(); i++) { final JSONObject jsonOutput = jsonOutputs.getJSONObject(i); if (jsonOutput.getInt("is_spent") != 0) throw new IllegalStateException("UXTO not spent"); final Sha256Hash uxtoHash = new Sha256Hash(jsonOutput.getString("transaction_hash")); final int uxtoIndex = jsonOutput.getInt("transaction_index"); final byte[] uxtoScriptBytes = BaseEncoding.base16().lowerCase() .decode(jsonOutput.getString("script_pub_key")); final BigInteger uxtoValue = new BigInteger(jsonOutput.getString("value")); Transaction tx = transactions.get(uxtoHash); if (tx == null) { tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash); tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING); transactions.put(uxtoHash, tx); } if (tx.getOutputs().size() > uxtoIndex) throw new IllegalStateException("cannot reach index " + uxtoIndex + ", tx already has " + tx.getOutputs().size() + " outputs"); // fill with dummies while (tx.getOutputs().size() < uxtoIndex) tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx, Coin.NEGATIVE_SATOSHI, new byte[] {})); // add the real output final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx, Coin.valueOf(uxtoValue.longValue()), uxtoScriptBytes); tx.addOutput(output); } log.info("fetched unspent outputs from {}", url); onResult(transactions.values()); } else { final String responseMessage = connection.getResponseMessage(); log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url); onFail(R.string.error_http, responseCode, responseMessage); } } catch (final JSONException x) { log.info("problem parsing json from " + url, x); onFail(R.string.error_parse, x.getMessage()); } catch (final IOException x) { log.info("problem querying unspent outputs from " + url, x); onFail(R.string.error_io, x.getMessage()); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } } }); }
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 w w w. j a va 2 s .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.eclipse.ecr.opencmis.impl.server.NuxeoCmisService.java
@Override public ObjectList query(String repositoryId, String statement, Boolean searchAllVersions, Boolean includeAllowableActions, IncludeRelationships includeRelationships, String renditionFilter, BigInteger maxItems, BigInteger skipCount, ExtensionsData extension) { long skip = skipCount == null ? 0 : skipCount.longValue(); if (skip < 0) { skip = 0;/*from ww w . j av a 2 s . c o m*/ } long max = maxItems == null ? -1 : maxItems.longValue(); if (max <= 0) { max = DEFAULT_QUERY_SIZE; } long numItems; List<ObjectData> list; IterableQueryResult res = null; try { Map<String, PropertyDefinition<?>> typeInfo = new HashMap<String, PropertyDefinition<?>>(); res = coreSession.queryAndFetch(statement, CMISQLQueryMaker.TYPE, this, typeInfo); // convert from Nuxeo to CMIS format list = new ArrayList<ObjectData>(); if (skip > 0) { res.skipTo(skip); } for (Map<String, Serializable> map : res) { ObjectDataImpl od = new ObjectDataImpl(); // properties (kept in list form) PropertiesImpl properties = new PropertiesImpl(); for (Entry<String, Serializable> en : map.entrySet()) { String queryName = en.getKey(); PropertyDefinition<?> pd = typeInfo.get(queryName); if (pd == null) { throw new NullPointerException("Cannot get " + queryName); } PropertyData<?> p = createPropertyData(pd, en.getValue(), queryName); properties.addProperty(p); } od.setProperties(properties); // optional stuff if (Boolean.TRUE.equals(includeAllowableActions)) { // od.setAllowableActions(allowableActions); } if (includeRelationships != null && includeRelationships != IncludeRelationships.NONE) { // od.setRelationships(relationships); } if (renditionFilter != null && renditionFilter.length() > 0) { // od.setRenditions(renditions); } list.add(od); if (list.size() >= max) { break; } } numItems = res.size(); } catch (ClientException e) { throw new CmisRuntimeException(e.getMessage(), e); } finally { if (res != null) { res.close(); } } ObjectListImpl objList = new ObjectListImpl(); objList.setObjects(list); objList.setNumItems(BigInteger.valueOf(numItems)); objList.setHasMoreItems(Boolean.valueOf(numItems > skip + list.size())); return objList; }
From source file:com.thoughtworks.go.server.persistence.MaterialRepository.java
private Long findLastBuiltModificationId(final Pipeline pipeline, final MaterialInstance materialInstance) { BigInteger result = (BigInteger) getHibernateTemplate().execute((HibernateCallback) session -> { String sql = "SELECT fromRevisionId " + " FROM pipelineMaterialRevisions pmr " + " INNER JOIN pipelines p on p.id = pmr.pipelineId " + " WHERE materialId = ? " + " AND p.name = ? " + " AND pipelineId < ? " + " ORDER BY pmr.id DESC" + " LIMIT 1"; SQLQuery query = session.createSQLQuery(sql); query.setLong(0, materialInstance.getId()); query.setString(1, pipeline.getName()); query.setLong(2, pipeline.getId()); return query.uniqueResult(); });//w ww . ja v a 2 s . com return result == null ? null : result.longValue(); }
From source file:org.apache.juddi.validation.ValidateReplication.java
public void validateGetChangeRecords(String requestingNode, HighWaterMarkVectorType changesAlreadySeen, BigInteger responseLimitCount, HighWaterMarkVectorType responseLimitVector, ReplicationConfiguration FetchEdges, WebServiceContext ctx) throws DispositionReportFaultMessage { //TODO/*from www. j ava 2 s . c o m*/ if (requestingNode == null || requestingNode.trim().equalsIgnoreCase("")) { //requestingNode: The requestingNode element provides the identity of the calling node. //This is the unique key for the calling node and SHOULD be specified within the Replication Configuration Structure. throw new FatalErrorException(new ErrorMessage("errors.replication.nodeNotSpecified")); } //if (!ContainsNode(requestingNode, FetchEdges)) { // throw new FatalErrorException(new ErrorMessage("errors.replication.unknownNode")); //} if (changesAlreadySeen != null) { // changesAlreadySeen: The changesAlreadySeen element, if present, indicates changes from each //node that the requestor has successfully processed, and thus which should not be resent, if possible. //no validation needed? } if (responseLimitCount != null && responseLimitVector != null) { throw new FatalErrorException(new ErrorMessage("errors.replication.bothLimitsSpecified")); } if (responseLimitCount != null) { //can't be 0 since 0 is banned as being a change record id if (responseLimitCount.longValue() <= 0) { throw new FatalErrorException( new ErrorMessage("errors.replication.negativeLimit", responseLimitCount.toString())); } } if (responseLimitVector != null) { for (int i = 0; i < responseLimitVector.getHighWaterMark().size(); i++) { if (responseLimitVector.getHighWaterMark().get(i).getOriginatingUSN() == null || responseLimitVector.getHighWaterMark().get(i).getOriginatingUSN() <= 0) { throw new FatalErrorException(new ErrorMessage("errors.replication.limitVectorNull")); } if (responseLimitVector.getHighWaterMark().get(i).getNodeID() == null || responseLimitVector.getHighWaterMark().get(i).getNodeID().trim().equalsIgnoreCase("")) { throw new FatalErrorException(new ErrorMessage("errors.replication.limitVectorNoNode")); } } } /** * responseLimitCount or responseLimitVector: A caller MAY place * an upper bound on the number of change records he wishes to * receive in response to this message by either providing a * integer responseLimitCount, or, using responseLimitVector, * indicating for each node in the graph the first change * originating there that he does not wish to be returned. * */ }
From source file:org.multibit.viewsystem.swing.action.SendAssetConfirmAction.java
/** * Complete the transaction to work out the fee) and then show the send bitcoin confirm dialog. *///from ww w.j a v a 2 s . c o m @Override public void actionPerformed(ActionEvent e) { if (abort()) { return; } // SendAssetConfirmDialog sendAssetConfirmDialog = null; AssetValidationErrorDialog validationErrorDialog = null; try { String sendAddress = dataProvider.getAddress(); String sendAmount = Utils.bitcoinValueToPlainString(BitcoinModel.COINSPARK_SEND_MINIMUM_AMOUNT); String sendMessage = null; boolean canSendMessage = false; final int assetId = dataProvider.getAssetId(); String assetAmount = dataProvider.getAssetAmount(); boolean isSenderPays = dataProvider.isSenderPays(); /* Is there a payment charge? If yes, the asset amount will change */ CSAsset asset = bitcoinController.getModel().getActiveWallet().CS.getAsset(assetId); CoinSparkGenesis genesis = asset.getGenesis(); BigInteger assetAmountRawUnits = CSMiscUtils.getRawUnitsFromDisplayString(asset, assetAmount); // Was there any rounding, which the user did not see because they clicked on send first, // without losing focus to any other widget which corrects field? String typedAmount = dataProvider.getAssetAmountText(); BigDecimal bd1 = new BigDecimal(typedAmount); BigDecimal bd2 = new BigDecimal(assetAmount); bd1 = bd1.stripTrailingZeros(); bd2 = bd2.stripTrailingZeros(); if (bd1.equals(bd2) == false) { String displayUnit = CSMiscUtils.getFormattedDisplayStringForRawUnits(asset, BigInteger.ONE); String s = "The smallest transactable unit is " + displayUnit + ", so we have rounded the sum down.\nPlease confirm the final amount and click 'Send' again."; JOptionPane.showMessageDialog(mainFrame, s); return; } // End rounding check/warning long desiredRawUnits = assetAmountRawUnits.longValue(); short chargeBasisPoints = genesis.getChargeBasisPoints(); long rawFlatChargeAmount = genesis.getChargeFlat(); boolean chargeExists = (rawFlatChargeAmount > 0 || chargeBasisPoints > 0); if (chargeExists) { if (isSenderPays) { long x = genesis.calcGross(desiredRawUnits); assetAmountRawUnits = new BigInteger(String.valueOf(x)); } else { // We don't have to do anything if recipient pays, just send gross amount. // calcNet() returns what the recipient will receive, but it's not what we send. // long x = genesis.calcNet(desiredRawUnits); // assetAmountRawUnits = new BigInteger(String.valueOf(x)); } } // Todo: Allow invalid assets to be sent even if spendable balance is 0 //if (CSMiscUtils.canSendInvalidAsset(bitcoinController) final AssetValidator validator = new AssetValidator(super.bitcoinController); if (validator.validate(sendAddress, sendAmount, assetId, assetAmountRawUnits.toString())) { /* CoinSpark START */ CoinSparkPaymentRef paymentRef = null; // We have already validated that the coinspark address and underlying bitcoin are good // and that the transfer flag is set on the coinspark address. We just want the actual // underlying bitcoin address to send assets to, which is used to create SendRequest object. CoinSparkAddress csa = CSMiscUtils.decodeCoinSparkAddress(sendAddress); String btcAddress = CSMiscUtils.getBitcoinAddressStringFromCoinSparkAddress(csa); sendAddress = btcAddress; // Does a payment ref exist? int flags = csa.getAddressFlags(); if ((flags & CoinSparkAddress.COINSPARK_ADDRESS_FLAG_PAYMENT_REFS) > 0) { paymentRef = csa.getPaymentRef(); log.debug(">>>> CoinSpark address has payment refs flag set: " + paymentRef.toString()); } // Messages - can send message and BTC to CoinSpark address, without any assets. sendMessage = dataProvider.getMessage(); canSendMessage = (flags & CoinSparkAddress.COINSPARK_ADDRESS_FLAG_TEXT_MESSAGES) > 0; /* CoinSpark END */ // Create a SendRequest. Address sendAddressObject; sendAddressObject = new Address(bitcoinController.getModel().getNetworkParameters(), sendAddress); //SendRequest sendRequest = SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount)); //public static SendRequest to(Address destination,BigInteger value,int assetID, BigInteger assetValue,int split) { //BigInteger assetAmountRawUnits = new BigInteger(assetAmount); BigInteger bitcoinAmountSatoshis = Utils.toNanoCoins(sendAmount); final SendRequest sendRequest = SendRequest.to(sendAddressObject, bitcoinAmountSatoshis, assetId, assetAmountRawUnits, 1); sendRequest.ensureMinRequiredFee = true; sendRequest.fee = BigInteger.ZERO; sendRequest.feePerKb = BitcoinModel.SEND_FEE_PER_KB_DEFAULT; // Note - Request is populated with the AES key in the SendBitcoinNowAction after the user has entered it on the SendBitcoinConfirm form. // Send with payment ref - if it exists and is not 0 which SparkBit treats semantically as null if (paymentRef != null && paymentRef.getRef() != 0) { sendRequest.setPaymentRef(paymentRef); } // Send a message if the address will take it and message is not empty boolean willSendMessage = false; if (canSendMessage) { boolean isEmptyMessage = false; if (sendMessage == null || sendMessage.isEmpty() || sendMessage.trim().length() == 0) { isEmptyMessage = true; } if (!isEmptyMessage) { willSendMessage = true; //int numParts = 1; CoinSparkMessagePart[] parts = { CSMiscUtils.createPlainTextCoinSparkMessagePart(sendMessage) }; String[] serverURLs = CSMiscUtils.getMessageDeliveryServersArray(bitcoinController); sendRequest.setMessage(parts, serverURLs); log.debug(">>>> Messaging servers = " + ArrayUtils.toString(serverURLs)); log.debug(">>>> parts[0] = " + parts[0]); log.debug(">>>> parts[0].fileName = " + parts[0].fileName); log.debug(">>>> parts[0].mimeType = " + parts[0].mimeType); log.debug(">>>> parts[0].content = " + new String(parts[0].content, "UTF-8")); //String message = "Hello, the time is now..." + DateTime.now().toString(); // parts[2].fileName = imagePath; // parts[2].mimeType = "image/png"; // byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath)); // parts[2].content = imageBytes; } } // // When sending a message, show a modal dialog. // CompleteTX now occurs in background thread so UI does not block // when "Send" is clicked with widget updates frozen. // // Show dialog with indeterminate progress bar final JDialog dialog = CSMiscUtils.createModalMessageDialogWithIndeterminateProgress(mainFrame, "SparkBit", "Contacting message delivery servers..."); // Dialog is made visible after futures have been set up ListeningExecutorService service = MoreExecutors .listeningDecorator(Executors.newSingleThreadExecutor()); //newFixedThreadPool(10)); ListenableFuture<Boolean> future = service.submit(new Callable<Boolean>() { public Boolean call() throws Exception { try { // Complete it (which works out the fee) but do not sign it yet. log.debug("Just about to complete the tx (and calculate the fee)..."); bitcoinController.getModel().getActiveWallet().completeTx(sendRequest, false); log.debug("The fee after completing the transaction was " + sendRequest.fee); } catch (Exception e) { throw e; } return true; } }); final BigInteger myAssetAmountRawUnits = assetAmountRawUnits; Futures.addCallback(future, new FutureCallback<Boolean>() { public void onSuccess(Boolean b) { // There is enough money. SwingUtilities.invokeLater(new Runnable() { @Override public void run() { dialog.dispose(); SendAssetConfirmDialog mySendAssetConfirmDialog = new SendAssetConfirmDialog( bitcoinController, mainFrame, sendRequest, assetId, myAssetAmountRawUnits, validator); mySendAssetConfirmDialog.setVisible(true); } }); } public void onFailure(Throwable thrown) { final String failureReason = thrown.getMessage(); final boolean isCSException = thrown instanceof org.coinspark.core.CSExceptions.CannotEncode; final boolean isInsufficientMoney = thrown instanceof com.google.bitcoin.core.InsufficientMoneyException; // There is not enough money. // TODO setup validation parameters accordingly so that it displays ok. SwingUtilities.invokeLater(new Runnable() { @Override public void run() { dialog.dispose(); if (isCSException) { JOptionPane .showMessageDialog(mainFrame, "SparkBit is unable to proceed with this transaction:\n\n" + failureReason, "SparkBit Error", JOptionPane.ERROR_MESSAGE); } else if (isInsufficientMoney) { // Try to show a human friendly message, need to pass the missing satoshis from failure reason. try { String numberOnly = failureReason.replaceAll("[^0-9]", ""); BigInteger needed = new BigInteger(numberOnly); JOptionPane.showMessageDialog(mainFrame, "SparkBit is unable to proceed with this transaction.\n\nInsufficient money in wallet, require " + Utils.bitcoinValueToFriendlyString(needed) + " BTC more.", "SparkBit Error", JOptionPane.ERROR_MESSAGE); } catch (NumberFormatException e) { AssetValidationErrorDialog myValidationErrorDialog = new AssetValidationErrorDialog( bitcoinController, mainFrame, sendRequest, true, validator); myValidationErrorDialog.setVisible(true); } } else { AssetValidationErrorDialog myValidationErrorDialog = new AssetValidationErrorDialog( bitcoinController, mainFrame, sendRequest, true, validator); myValidationErrorDialog.setVisible(true); } } }); } }); // Show message server dialog only if we are going to send if (willSendMessage) { dialog.setVisible(true); } /* // Complete it (which works out the fee) but do not sign it yet. log.debug("Just about to complete the tx (and calculate the fee)..."); boolean completedOk; try { bitcoinController.getModel().getActiveWallet().completeTx(sendRequest, false); completedOk = true; log.debug("The fee after completing the transaction was " + sendRequest.fee); } catch (InsufficientMoneyException ime) { completedOk = false; } if (completedOk) { // There is enough money. sendAssetConfirmDialog = new SendAssetConfirmDialog(super.bitcoinController, mainFrame, sendRequest, assetId, assetAmountRawUnits, validator); sendAssetConfirmDialog.setVisible(true); } else { // There is not enough money. // TODO setup validation parameters accordingly so that it displays ok. validationErrorDialog = new AssetValidationErrorDialog(super.bitcoinController, mainFrame, sendRequest, true, validator); validationErrorDialog.setVisible(true); } */ } else { validationErrorDialog = new AssetValidationErrorDialog(super.bitcoinController, mainFrame, null, false, validator); validationErrorDialog.setVisible(true); } } catch (WrongNetworkException e1) { logMessage(e1); } catch (AddressFormatException e1) { logMessage(e1); } catch (KeyCrypterException e1) { logMessage(e1); } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(mainFrame, "Please enter a valid amount."); } catch (Exception e1) { logMessage(e1); } }
From source file:service.actions.OrderSearch.java
private Long getLong(Object value) { if (value == null) { return null; } else {//from www .j a va 2 s.c o m if (value instanceof Long) { return (Long) value; } else if (value instanceof BigInteger) { BigInteger bi = (BigInteger) value; return bi.longValue(); } else if (value instanceof Integer) { Integer i = (Integer) value; return i.longValue(); } } return null; }
From source file:org.nuxeo.ecm.core.opencmis.impl.server.NuxeoCmisService.java
@Override public ObjectList query(String repositoryId, String statement, Boolean searchAllVersions, Boolean includeAllowableActions, IncludeRelationships includeRelationships, String renditionFilter, BigInteger maxItems, BigInteger skipCount, ExtensionsData extension) { long skip = skipCount == null ? 0 : skipCount.longValue(); if (skip < 0) { skip = 0;//from ww w. j a v a2 s . c o m } long max = maxItems == null ? -1 : maxItems.longValue(); if (max <= 0) { max = DEFAULT_QUERY_SIZE; } long numItems; List<ObjectData> list; IterableQueryResult res = null; try { Map<String, PropertyDefinition<?>> typeInfo = new HashMap<String, PropertyDefinition<?>>(); // searchAllVersions defaults to false, spec 2.2.6.1.1 res = queryAndFetch(statement, Boolean.TRUE.equals(searchAllVersions), typeInfo); // convert from Nuxeo to CMIS format list = new ArrayList<ObjectData>(); if (skip > 0) { res.skipTo(skip); } for (Map<String, Serializable> map : res) { ObjectDataImpl od = makeObjectData(map, typeInfo); // optional stuff String id = od.getId(); if (id != null) { // null if JOIN in original query DocumentModel doc = null; if (Boolean.TRUE.equals(includeAllowableActions)) { doc = getDocumentModel(id); AllowableActions allowableActions = NuxeoObjectData.getAllowableActions(doc, false); od.setAllowableActions(allowableActions); } if (includeRelationships != null && includeRelationships != IncludeRelationships.NONE) { // TODO get relationships using a JOIN // added to the original query List<ObjectData> relationships = NuxeoObjectData.getRelationships(id, includeRelationships, this); od.setRelationships(relationships); } if (NuxeoObjectData.needsRenditions(renditionFilter)) { if (doc == null) { doc = getDocumentModel(id); } List<RenditionData> renditions = NuxeoObjectData.getRenditions(doc, renditionFilter, null, null, callContext); od.setRenditions(renditions); } } list.add(od); if (list.size() >= max) { break; } } numItems = res.size(); } catch (ClientException e) { throw new CmisRuntimeException(e.getMessage(), e); } finally { if (res != null) { res.close(); } } ObjectListImpl objList = new ObjectListImpl(); objList.setObjects(list); objList.setNumItems(BigInteger.valueOf(numItems)); objList.setHasMoreItems(Boolean.valueOf(numItems > skip + list.size())); return objList; }
From source file:edu.pitt.apollo.db.ApolloDbUtils.java
public void addRunIdToSimulationGroups(List<BigInteger> simulationGroupIds, BigInteger runId) throws ApolloDatabaseException, Md5UtilsException { String query = "INSERT IGNORE INTO simulation_group_definition (simulation_group_id, run_id) VALUES (?,?)"; try (Connection conn = datasource.getConnection()) { PreparedStatement pstmt = conn.prepareStatement(query); for (BigInteger simGroupId : simulationGroupIds) { pstmt.setLong(1, simGroupId.longValue()); pstmt.setLong(2, runId.longValue()); pstmt.execute();/*from ww w. j a v a2s. c om*/ } } catch (SQLException ex) { throw new ApolloDatabaseException( "SQLException adding run IDs to simulation group: " + ex.getMessage()); } }