List of usage examples for java.lang Long longValue
@HotSpotIntrinsicCandidate public long longValue()
From source file:org.zht.framework.zhtdao.hibernate.impl.HibernateBaseDaoImpl.java
@Override public Long findCountByHQL(String hql) throws DaoException { if (hql == null || hql.length() == 0) { return null; }//from www . j a va 2s . c o m Long count = (Long) this.getCurrentSession().createQuery(hql).uniqueResult(); return count != null ? count.longValue() : 0L; }
From source file:com.oodlemud.appengine.counter.service.ShardedCounterServiceImpl.java
@Override public Counter decrement(final String counterName, final long amount) { // /////////// // Precondition Checks Preconditions.checkNotNull(counterName); Preconditions.checkArgument(!StringUtils.isBlank(counterName)); // /////////// // CounterData Status Checks CounterData counterData = getOrCreateCounterData(counterName); // Find how many shards are in this counter. final int currentNumShards = counterData.getNumShards(); long totalAmountDecremented = 0L; // Try a random shard at first -- this will generally work, but if it // fails, then the code below it will kick-in, which is less // efficient since it scans through all of the shards and will generally // bias towards the lower-numbered shards since the counter starts at 0. // An improvement to reduce this bias would be to pick a random shard, // then scan up and down from there. // Choose the shard randomly from the available shards. final int randomShardNum = generator.nextInt(currentNumShards); Key<CounterShardData> randomCounterShardDataKey = CounterShardData.key(counterName, randomShardNum); DecrementShardWork decrementShardTask = new DecrementShardWork(counterName, randomCounterShardDataKey, amount);//from www. ja v a2 s. c o m Long lAmountDecrementedInTx = ObjectifyService.ofy().transactNew(decrementShardTask); long amountDecrementedInTx = lAmountDecrementedInTx == null ? 0L : lAmountDecrementedInTx.longValue(); totalAmountDecremented = amountDecrementedInTx; long amountLeftToDecrement = amount - amountDecrementedInTx; if (amountLeftToDecrement > 0) { // Try to decrement an amount from one shard at a time in a serial // fashion so that two shards aren't decremented at the // same time. for (int i = 0; i < counterData.getNumShards(); i++) { final Key<CounterShardData> sequentialCounterShardDataKey = CounterShardData.key(counterName, i); if (sequentialCounterShardDataKey.equals(randomCounterShardDataKey)) { // This shard has already been decremented, so don't try // again, but keep trying other shards. continue; } // Try to decrement amountLeftToDecrement decrementShardTask = new DecrementShardWork(counterName, sequentialCounterShardDataKey, amountLeftToDecrement); lAmountDecrementedInTx = ObjectifyService.ofy().transactNew(decrementShardTask); amountDecrementedInTx = lAmountDecrementedInTx == null ? 0L : lAmountDecrementedInTx.longValue(); totalAmountDecremented += amountDecrementedInTx; amountLeftToDecrement -= amountDecrementedInTx; } } // ///////////////// // Increment this counter in memcache atomically, with retry until it // succeeds (with some governor). If this fails, it's ok // because memcache is merely a cache of the actual count data, and will // eventually become accurate when the cache is reloaded. // ///////////////// incrementMemcacheAtomic(counterName, (totalAmountDecremented * -1L)); // return #getCount because this will either return the memcache value // or get the actual count from the Datastore, which will do the same // thing. return getCounter(counterName); }
From source file:com.gst.accounting.journalentry.service.JournalEntryWritePlatformServiceJpaRepositoryImpl.java
@Override public void revertShareAccountJournalEntries(final ArrayList<Long> transactionIds, final Date transactionDate) { for (Long shareTransactionId : transactionIds) { String transactionId = AccountingProcessorHelper.SHARE_TRANSACTION_IDENTIFIER + shareTransactionId.longValue(); List<JournalEntry> journalEntries = this.glJournalEntryRepository.findJournalEntries(transactionId, PortfolioProductType.SHARES.getValue()); if (journalEntries == null || journalEntries.isEmpty()) continue; final Long officeId = journalEntries.get(0).getOffice().getId(); final String reversalTransactionId = generateTransactionId(officeId); for (final JournalEntry journalEntry : journalEntries) { JournalEntry reversalJournalEntry; String reversalComment = "Reversal entry for Journal Entry with id :" + journalEntry.getId() + " and transaction Id " + journalEntry.getTransactionId(); if (journalEntry.isDebitEntry()) { reversalJournalEntry = JournalEntry.createNew(journalEntry.getOffice(), journalEntry.getPaymentDetails(), journalEntry.getGlAccount(), journalEntry.getCurrencyCode(), reversalTransactionId, Boolean.FALSE, transactionDate, JournalEntryType.CREDIT, journalEntry.getAmount(), reversalComment, journalEntry.getEntityType(), journalEntry.getEntityId(), journalEntry.getReferenceNumber(), journalEntry.getLoanTransaction(), journalEntry.getSavingsTransaction(), journalEntry.getClientTransaction(), journalEntry.getShareTransactionId()); } else { reversalJournalEntry = JournalEntry.createNew(journalEntry.getOffice(), journalEntry.getPaymentDetails(), journalEntry.getGlAccount(), journalEntry.getCurrencyCode(), reversalTransactionId, Boolean.FALSE, transactionDate, JournalEntryType.DEBIT, journalEntry.getAmount(), reversalComment, journalEntry.getEntityType(), journalEntry.getEntityId(), journalEntry.getReferenceNumber(), journalEntry.getLoanTransaction(), journalEntry.getSavingsTransaction(), journalEntry.getClientTransaction(), journalEntry.getShareTransactionId()); }// w w w . j a va 2 s. c o m // save the reversal entry this.glJournalEntryRepository.save(reversalJournalEntry); journalEntry.setReversalJournalEntry(reversalJournalEntry); journalEntry.setReversed(true); // save the updated journal entry this.glJournalEntryRepository.save(journalEntry); } } }
From source file:org.duniter.core.client.service.bma.BlockchainRemoteServiceImpl.java
@Override public long getLastUD(Peer peer) { // get block number with UD String blocksWithUdResponse = executeRequest(peer, URL_BLOCK_WITH_UD, String.class); int[] blocksWithUD = getBlockNumbersFromJson(blocksWithUdResponse); // If no result (this could happen when no UD has been send if (blocksWithUD != null && blocksWithUD.length > 0) { int index = blocksWithUD.length - 1; while (index >= 0) { try { // Get the UD from the last block with UD String path = String.format(URL_BLOCK, blocksWithUD[index]); String json = executeRequest(peer, path, String.class); Long lastUD = getDividendFromBlockJson(json); // Check not null (should never append) if (lastUD == null) { throw new TechnicalException("Unable to get last UD from server"); }//from w w w .j a v a 2s . co m return lastUD.longValue(); } catch (HttpNotFoundException e) { index--; // Can occur something (observed in Duniter 0.50.0) } } } // get the first UD from currency parameter BlockchainParameters parameter = getParameters(peer); return parameter.getUd0(); }
From source file:org.sakaiproject.signup.tool.jsf.organizer.action.EditMeeting.java
private List<SignupMeeting> prepareModify(SignupMeeting userModifiedMeeting) throws Exception { List<SignupMeeting> upTodateOrginMeetings = null; List<SignupMeeting> newlyModifyMeetings = new ArrayList<SignupMeeting>(); Long recurrenceId = userModifiedMeeting.getRecurrenceId(); if (recurrenceId != null && recurrenceId.longValue() > 0 && !isConvertToNoRecurrent()) { /* only update the future recurring meeting now now today */ upTodateOrginMeetings = signupMeetingService.getRecurringSignupMeetings(siteId, userId, recurrenceId, new Date()); retrieveRecurrenceData(upTodateOrginMeetings); } else {/*from w w w. j a va2s . c o m*/ SignupMeeting upTodateOrginMeeting = reloadMeeting(userModifiedMeeting); upTodateOrginMeetings = new ArrayList<SignupMeeting>(); upTodateOrginMeetings.add(upTodateOrginMeeting); } /* * Since recurring meetings are identical by title, location, etc. only * the corresponding one to original one will be checked here. */ /* * If someone has changed it before you,it should be caught by versionId * since meetings are saved as a bulk. */ SignupMeeting upToDateMatchOne = getCorrespondingMeeting(upTodateOrginMeetings, userModifiedMeeting); checkPreCondition(upToDateMatchOne, upTodateOrginMeetings); Calendar calendar = Calendar.getInstance(); int recurNum = 0; //initialize to-be-removed TS list for advanced user-defined cases this.toBedeletedTSList = new ArrayList<SignupTimeslot>(); for (SignupMeeting upTodateOrginMeeting : upTodateOrginMeetings) { SignupMeeting newlyModifyMeeting = upTodateOrginMeeting; /* * set event starting time for calendar due to multiple-recurring * meetings */ long startTimeChangeDiff = userModifiedMeeting.getStartTime().getTime() - getOriginalMeetingCopy().getStartTime().getTime(); calendar.setTimeInMillis(upTodateOrginMeeting.getStartTime().getTime() + startTimeChangeDiff); /* pass user changes */ passModifiedValues(userModifiedMeeting, calendar, newlyModifyMeeting, recurNum); recurNum++; newlyModifyMeetings.add(newlyModifyMeeting); } return newlyModifyMeetings; }
From source file:org.squale.squalecommon.enterpriselayer.facade.quality.MeasureFacade.java
/** * Creation d'une mesure de type Bubble pour un projet * /*from w w w.j a v a 2 s . c o m*/ * @param pProjectId Id du projet * @param pAuditId Id de l'audit * @throws JrafEnterpriseException en cas de pb Hibernate * @return chart Scatterplot de l'Audit * @throws JrafEnterpriseException si pb Hibernate */ public static Object[] getProjectBubble(Long pProjectId, Long pAuditId) throws JrafEnterpriseException { // Rcupration des valeurs int i = 0; Collection measures = new ArrayList(0); MeasureDAOImpl measureDAO = MeasureDAOImpl.getInstance(); // Session Hibernate ISession session = null; Object[] result = null; try { // rcupration d'une session session = PERSISTENTPROVIDER.getSession(); // On rcupre la configuration du scatterplot pour ce projet et cet audit AuditDisplayConfBO auditConf = AuditDisplayConfDAOImpl.getInstance().findConfigurationWhere(session, pProjectId, pAuditId, "bubble"); if (null != auditConf) { BubbleConfBO bubble = (BubbleConfBO) auditConf.getDisplayConf(); String[] tre = { bubble.getXTre(), bubble.getYTre() }; // rcupration des mesures distinctes rattaches l'audit et au projet measures = MeasureDAOImpl.getInstance().findDistinct(session, pProjectId.longValue(), pAuditId.longValue(), tre); // recuperation des 2 tableaux evgs, vgs contenant les mesures double[] xMeasures = new double[measures.size()]; double[] yMeasures = new double[measures.size()]; double[] total = new double[measures.size()]; Iterator it = measures.iterator(); // Constantes pour la rcuprations des valeurs dans le tableau des rsultats remonts de la base final int VG_ID = 0; final int EVG_ID = 1; final int TOTAL_ID = 2; while (it.hasNext()) { Object[] res = (Object[]) it.next(); // on ajoute ses valeurs Integer vg = (Integer) res[VG_ID]; yMeasures[i] = vg.doubleValue(); Integer evg = (Integer) res[EVG_ID]; xMeasures[i] = evg.doubleValue(); Integer tt = (Integer) res[TOTAL_ID]; total[i] = tt.doubleValue(); i++; } // Positions des axes Long horizontal = new Long(bubble.getHorizontalAxisPos()); Long vertical = new Long(bubble.getVerticalAxisPos()); // construction des paramtres de la srie String displayedXTre = bubble.getXTre().substring(bubble.getXTre().lastIndexOf(".") + 1); String displayedYTre = bubble.getYTre().substring(bubble.getYTre().lastIndexOf(".") + 1); String measuresKinds = "(" + displayedXTre + "," + displayedYTre + ",total)"; result = new Object[] { horizontal, vertical, measuresKinds, yMeasures, xMeasures, total, yMeasures, xMeasures, total, tre }; } } catch (Exception e) { FacadeHelper.convertException(e, MeasureFacade.class.getName() + ".getMeasures"); } finally { FacadeHelper.closeSession(session, MeasureFacade.class.getName() + ".getMeasures"); } return result; }
From source file:de.saly.elasticsearch.mailsource.ParallelPollingIMAPMailSource.java
@SuppressWarnings({ "rawtypes", "unchecked" }) protected void fetch(final Folder folder) throws MessagingException, IOException { if ((folder.getType() & Folder.HOLDS_MESSAGES) == 0) { logger.warn("Folder {} cannot hold messages", folder.getFullName()); return;//w ww . j ava 2 s . c o m } final int messageCount = folder.getMessageCount(); final UIDFolder uidfolder = (UIDFolder) folder; final long servervalidity = uidfolder.getUIDValidity(); final RiverState riverState = stateManager.getRiverState(folder); final Long localvalidity = riverState.getUidValidity(); logger.info("Fetch mails from folder {} ({})", folder.getURLName().toString(), messageCount); logger.debug("Server uid validity: {}, Local uid validity: {}", servervalidity, localvalidity); if (localvalidity == null || localvalidity.longValue() != servervalidity) { logger.debug("UIDValidity fail, full resync " + localvalidity + "!=" + servervalidity); if (localvalidity != null) { mailDestination.clearDataForFolder(folder.getFullName()); } final ProcessResult result = process(messageCount, 1, folder.getFullName()); riverState.setLastCount(result.getProcessedCount()); if (result.getProcessedCount() > 0) { riverState.setLastIndexed(new Date()); } if (result.getProcessedCount() > 0) { riverState.setLastTook(result.getTook()); } riverState.setLastSchedule(new Date()); if (result.getProcessedCount() > 0 && result.getHighestUid() > 0) { riverState.setLastUid(result.getHighestUid()); } riverState.setUidValidity(servervalidity); stateManager.setRiverState(riverState); logger.info("Initiailly processed {} mails for folder {}", result.getProcessedCount(), folder.getFullName()); logger.debug("Processed result {}", result.toString()); } else { if (messageCount == 0) { logger.debug("Folder {} is empty", folder.getFullName()); } else { if (withFlagSync) { // detect flag change final Message[] flagMessages = folder.getMessages(); folder.fetch(flagMessages, IMAPUtils.FETCH_PROFILE_FLAGS_UID); for (final Message message : flagMessages) { try { final long uid = ((UIDFolder) message.getFolder()).getUID(message); final String id = uid + "::" + message.getFolder().getURLName(); final int storedHashcode = mailDestination.getFlaghashcode(id); if (storedHashcode == -1) { // New mail which is not indexed yet continue; } final int flagHashcode = message.getFlags().hashCode(); if (flagHashcode != storedHashcode) { // flags change for this message, must update mailDestination.onMessage(message); if (logger.isDebugEnabled()) { logger.debug("Update " + id + " because of flag change"); } } } catch (final Exception e) { logger.error("Error detecting flagchanges for message " + ((MimeMessage) message).getMessageID(), e); stateManager.onError("Error detecting flagchanges", message, e); } } } final long highestUID = riverState.getLastUid(); // this uid is // already // processed logger.debug("highestUID: {}", highestUID); final Message[] msgsnew = uidfolder.getMessagesByUID(highestUID, UIDFolder.LASTUID); // msgnew.size is always >= 1 if (highestUID > 0 && uidfolder.getUID(msgsnew[0]) <= highestUID) { // msgsnew = (Message[]) ArrayUtils.remove(msgsnew, 0); } if (msgsnew.length > 0) { logger.info("{} new messages in folder {}", msgsnew.length, folder.getFullName()); final int start = msgsnew[0].getMessageNumber(); final ProcessResult result = process(messageCount, start, folder.getFullName()); riverState.setLastCount(result.getProcessedCount()); if (result.getProcessedCount() > 0) { riverState.setLastIndexed(new Date()); } if (result.getProcessedCount() > 0) { riverState.setLastTook(result.getTook()); } riverState.setLastSchedule(new Date()); if (result.getProcessedCount() > 0 && result.getHighestUid() > 0) { riverState.setLastUid(result.getHighestUid()); } riverState.setUidValidity(servervalidity); stateManager.setRiverState(riverState); logger.info("Not initiailly processed {} mails for folder {}", result.getProcessedCount(), folder.getFullName()); logger.debug("Processed result {}", result.toString()); } else { logger.debug("no new messages"); } } // check for expunged/deleted messages final Set<Long> serverMailSet = new HashSet<Long>(); final long oldmailUid = riverState.getLastUid(); logger.debug("oldmailuid {}", oldmailUid); final Message[] msgsold = uidfolder.getMessagesByUID(1, oldmailUid); folder.fetch(msgsold, IMAPUtils.FETCH_PROFILE_UID); for (final Message m : msgsold) { try { final long uid = uidfolder.getUID(m); serverMailSet.add(uid); } catch (final Exception e) { stateManager.onError("Unable to handle old message ", m, e); logger.error("Unable to handle old message due to {}", e, e.toString()); IMAPUtils.open(folder); } } final Set localMailSet = new HashSet( mailDestination.getCurrentlyStoredMessageUids(folder.getFullName(), false)); logger.debug("Check now " + localMailSet.size() + " server mails for expunge"); localMailSet.removeAll(serverMailSet); // localMailSet has now the ones that are not on server logger.info( localMailSet.size() + " messages were locally deleted, because they are expunged on server."); mailDestination.onMessageDeletes(localMailSet, folder.getFullName(), false); } }
From source file:com.fengduo.bee.web.controller.order.OrderController.java
private Result orderInfos(Long itemId, Long orderId, Long subId) { if (Argument.isNotPositive(itemId) || Argument.isNotPositive(orderId) || Argument.isNotPositive(subId)) { return Result.failed("???"); }/*from w w w. jav a 2 s .c o m*/ Long userId = getCurrentUserId(); Item item = itemService.getItemById(itemId); if (item == null) { return Result.failed("?"); } UserSub sub = orderService.getUserSubById(subId); if (sub == null) { return Result.failed("?"); } // orderIdsubId ? // ?? // ??? if (sub.getUserId().longValue() != userId.longValue()) { return Result.failed("??"); } PayOrder order = orderService.getOrderById(orderId); if (order == null) { return Result.failed("??"); } if (order.getUserId().longValue() != userId.longValue()) { return Result.failed("??"); } if (!order.isInValidPayTime()) { return Result.failed("3"); } if ((order.getStatus() != OrderStatusEnum.NON_PAY.getValue()) && (order.getStatus() != OrderStatusEnum.FAIL_PAY.getValue())) { return Result.failed("??"); } Map<String, Object> model = new HashMap<String, Object>(); model.put("item", item); model.put("sub", sub); model.put("order", order); return Result.success(model); }
From source file:com.magnet.android.mms.controller.RequestPrimitiveTest.java
@SmallTest public void testSingleListLongPostParam() throws JSONException { ControllerHandler handler = new ControllerHandler(); String methodName = "postLongs"; JMethod method = new JMethod(); JMeta metaInfo = new JMeta(methodName, API_METHOD_POST + methodName, POST); method.setMetaInfo(metaInfo);/*from w ww. j ava2 s . c o m*/ method.addParam("param0", PLAIN, List.class, Long.class, "", false); List<Long> values = new ArrayList<Long>(); values.add(3456L); values.add(1L); values.add(-999L); String uriString = handler.buildUri(method, new Object[] { values }); String bodyString = handler.buildRequestBodyString(method, new Object[] { values }); String expected = API_METHOD_POST + methodName; logger.log(Level.INFO, "uriString=" + uriString); logger.log(Level.INFO, "bodyString=" + bodyString); assertEquals(expected, uriString); JSONArray jarray = new JSONArray(bodyString); int idx = 0; for (Long value : values) { assertEquals(jarray.getLong(idx), value.longValue()); idx++; } }
From source file:javax.faces.webapp.UIComponentTag.java
private String getOrCreateUniqueId(FacesContext context) { String id = getId();//from w ww. j a va2 s . co m if (id != null) { return id; } else { //we've been calling //return context.getViewRoot().createUniqueId(); - don't want that anymore Long currentCounter = (Long) context.getExternalContext().getRequestMap().get(UNIQUE_ID_COUNTER_ATTR); long lCurrentCounter = 0; if (currentCounter != null) { lCurrentCounter = currentCounter.longValue(); } StringBuffer retValue = new StringBuffer(UIViewRoot.UNIQUE_ID_PREFIX); retValue.append("Jsp"); retValue.append(lCurrentCounter); lCurrentCounter++; context.getExternalContext().getRequestMap().put(UNIQUE_ID_COUNTER_ATTR, new Long(lCurrentCounter)); ExternalContext extCtx = FacesContext.getCurrentInstance().getExternalContext(); return extCtx.encodeNamespace(retValue.toString()); } }