List of usage examples for java.lang Number longValue
public abstract long longValue();
From source file:com.itelis.worker.dev.template.service.JRXmlDataSource.java
protected Object convertNumber(Number number, Class valueClass) throws JRException { Number value = null;/* ww w . j a v a 2 s . c om*/ if (valueClass.equals(Byte.class)) { value = new Byte(number.byteValue()); } else if (valueClass.equals(Short.class)) { value = new Short(number.shortValue()); } else if (valueClass.equals(Integer.class)) { value = new Integer(number.intValue()); } else if (valueClass.equals(Long.class)) { value = new Long(number.longValue()); } else if (valueClass.equals(Float.class)) { value = new Float(number.floatValue()); } else if (valueClass.equals(Double.class)) { value = new Double(number.doubleValue()); } else if (valueClass.equals(BigInteger.class)) { value = BigInteger.valueOf(number.longValue()); } else if (valueClass.equals(BigDecimal.class)) { value = new BigDecimal(Double.toString(number.doubleValue())); } else { throw new JRException("Unknown number class " + valueClass.getName()); } return value; }
From source file:Unsigned.java
/** * Parse a binary number into a Number object. If up to 8 bits are parsed, * returns a Byte. If more than 8 and up to 16 bits are parsed, return a * Short. If more than 16 and up to 32 bits are parsed, return an Integer. * If more than 32 and up to 64 bits are parsed, return a Long. * //from w ww .j ava2 s .c om * @param text * a binary number * @param parsePosition * position to start parsing from * @return return an integer form of Number object if parse is successful; * <CODE>null</CODE> otherwise * * @since 1.0 */ public Number parse(String text, ParsePosition parsePosition) { boolean skipWhitespace = true; int startIndex, bits; // remove whitespace StringCharacterIterator iter = new StringCharacterIterator(text, parsePosition.getIndex()); for (char c = iter.current(); c != CharacterIterator.DONE; c = iter.next()) { if (skipWhitespace && Character.isWhitespace(c)) { // skip whitespace continue; } } parsePosition.setIndex(iter.getIndex()); startIndex = parsePosition.getIndex(); Number result = (Number) parseObject(text, parsePosition); if (result == null) { return (result); } bits = parsePosition.getIndex() - startIndex; if (bits <= 8) { result = new Byte(result.byteValue()); } else if (bits <= 16) { result = new Short(result.shortValue()); } else if (bits <= 32) { result = new Integer(result.intValue()); } else if (bits <= 64) { result = new Long(result.longValue()); } return (result); }
From source file:it.drwolf.ridire.index.cwb.CWBCollocatesExtractor.java
public String extractCollocates(boolean calculateSize) { try {/*from w ww. j a va2s . c o m*/ this.dropDB(); if (!this.userTx.isActive()) { this.userTx.begin(); } this.entityManager.joinTransaction(); String createDBQuery = "CREATE TABLE `" + CWBCollocatesExtractor.COLLOCATE_DB_PREFIX + this.conversationId + "` (`text_id` varchar(40) DEFAULT NULL,`beginPosition` int(11) DEFAULT NULL,`endPosition` int(11) DEFAULT NULL,`refnumber` bigint(20) NOT NULL,`dist` smallint(6) NOT NULL,`word` varchar(40) NOT NULL "; if (this.isIncludeLemmas()) { createDBQuery += ", `lemma` varchar(40) NOT NULL "; } if (this.isIncludePos()) { createDBQuery += ", `pos` varchar(40) NOT NULL "; } createDBQuery += ") ENGINE=MyISAM DEFAULT CHARSET=utf8"; this.entityManager.createNativeQuery(createDBQuery).executeUpdate(); this.entityManager.flush(); this.entityManager.clear(); this.userTx.commit(); File tmpTabulate = this.tabulate(); if (!this.userTx.isActive()) { this.userTx.begin(); } this.entityManager.joinTransaction(); this.entityManager.createNativeQuery("LOAD DATA LOCAL INFILE '" + tmpTabulate.getAbsolutePath() + "' INTO TABLE " + CWBCollocatesExtractor.COLLOCATE_DB_PREFIX + this.conversationId) .executeUpdate(); if (calculateSize) { if (this.getCollocationBasedOn().equals(CWBCollocatesExtractor.BASED_ON_LEMMA)) { this.resultsSize = ((Number) this.entityManager .createNativeQuery("select count(distinct(lemma)) from " + CWBCollocatesExtractor.COLLOCATE_DB_PREFIX + this.conversationId) .getSingleResult()).intValue(); } else if (this.getCollocationBasedOn().equals(CWBCollocatesExtractor.BASED_ON_POS)) { this.resultsSize = ((Number) this.entityManager .createNativeQuery("select count(distinct(pos)) from " + CWBCollocatesExtractor.COLLOCATE_DB_PREFIX + this.conversationId) .getSingleResult()).intValue(); } else { this.resultsSize = ((Number) this.entityManager .createNativeQuery("select count(distinct(word)) from " + CWBCollocatesExtractor.COLLOCATE_DB_PREFIX + this.conversationId) .getSingleResult()).intValue(); } } long r1 = ((Number) this.entityManager.createNativeQuery( "select count(*) from " + CWBCollocatesExtractor.COLLOCATE_DB_PREFIX + this.conversationId + " where dist between -" + this.getDistanceLeft() + " and " + this.getDistanceRight()) .getSingleResult()).longValue(); this.entityManager.flush(); this.entityManager.clear(); this.userTx.commit(); String collBasedOn = "word"; String freqTable = "freq_"; if (this.getCollocationBasedOn().equals(CWBCollocatesExtractor.BASED_ON_LEMMA)) { collBasedOn = "lemma"; freqTable += "lemma_"; } else if (this.getCollocationBasedOn().equals(CWBCollocatesExtractor.BASED_ON_POS)) { collBasedOn = "pos"; freqTable += "easypos_"; } else { freqTable += "forma_"; } if (this.getFunctionalMetadatum() >= 0) { FunctionalMetadatum fm = this.entityManager.find(FunctionalMetadatum.class, this.getFunctionalMetadatum()); freqTable += fm.getDescription().trim().replaceAll("\\s", "_"); } else if (this.getSemanticMetadatum() >= 0) { SemanticMetadatum sm = this.entityManager.find(SemanticMetadatum.class, this.getSemanticMetadatum()); freqTable += sm.getDescription().trim().replaceAll("\\s", "_"); } else { freqTable += "all"; } long n = this.corpusSizeParams.getCorpusSize(freqTable.substring(5)).longValue(); String nativeQuery = "select %1$s.%2$s, count(%1$s.%2$s) as observed,(" + r1 + " * (%3$s.freq) / " + n + ") as expected,"; String significance = " sign(COUNT(%1$s.%2$s) - (" + r1 + " * (%3$s.freq) / " + n + ")) * 2 * ( IF(COUNT(%1$s.%2$s) > 0, COUNT(%1$s.%2$s) * log(COUNT(%1$s.%2$s) / (" + r1 + " * (%3$s.freq) / " + n + ")), 0) + IF((" + r1 + " - COUNT(%1$s.%2$s)) > 0, (" + r1 + " - COUNT(%1$s.%2$s)) * log((" + r1 + " - COUNT(%1$s.%2$s)) / (" + r1 + " * (" + n + " - (%3$s.freq)) / " + n + ")), 0) + IF((CAST(%3$s.freq AS SIGNED) - COUNT(%1$s.%2$s)) > 0, " + "(CAST(%3$s.freq AS SIGNED) - COUNT(%1$s.%2$s)) * log((CAST(%3$s.freq AS SIGNED) - COUNT(%1$s.%2$s)) / (" + (n - r1) + " * (%3$s.freq) / " + n + ")), 0) + " + "IF((" + (n - r1) + " - (CAST(%3$s.freq AS SIGNED) - COUNT(%1$s.%2$s))) > 0, (" + (n - r1) + " - (CAST(%3$s.freq AS SIGNED) - COUNT(%1$s.%2$s))) * log((" + (n - r1) + " - (CAST(%3$s.freq AS SIGNED) - COUNT(%1$s.%2$s))) / (" + (n - r1) + " * (" + n + " - (%3$s.freq)) / " + n + ")), 0) ) as significance, "; if (this.getScore().equals(CWBCollocatesExtractor.MI_SCORE)) { significance = "log2(COUNT(%1$s.%2$s)/(" + r1 + " * (%3$s.freq) / " + n + ")) as significance, "; } else if (this.getScore().equals(CWBCollocatesExtractor.T_SCORE)) { significance = "(COUNT(%1$s.%2$s) - (" + r1 + " * (%3$s.freq) / " + n + "))/sqrt(COUNT(%1$s.%2$s)) as significance, "; } else if (this.getScore().equals(CWBCollocatesExtractor.LOGDICE_SCORE)) { String subquery = "SELECT COUNT(DISTINCT refnumber) from %1$s WHERE dist between -" + this.getDistanceLeft() + " and " + this.getDistanceRight(); if (!this.userTx.isActive()) { this.userTx.begin(); } subquery = String.format(subquery, CWBCollocatesExtractor.COLLOCATE_DB_PREFIX + this.conversationId); this.entityManager.joinTransaction(); Number diceNodeF = (Number) this.entityManager.createNativeQuery(subquery).getSingleResult(); this.entityManager.flush(); this.entityManager.clear(); this.userTx.commit(); String pCollNodeE = "(COUNT(DISTINCT refnumber) / " + diceNodeF.longValue() + ")"; String pNodeColl = "(COUNT(%1$s.%2$s) / (%3$s.freq))"; significance = "2 / ((1 / " + pCollNodeE + ") + (1 / " + pNodeColl + ")) as significance, "; } nativeQuery += significance; nativeQuery += " %3$s.freq, " + "count(distinct(text_id)) as text_id_count " + "from %1$s, %3$s where %1$s.%2$s = %3$s.item "; if (this.isIncludePos() && this.getFilterOnPoS() != null && this.getFilterOnPoS().length() > 0 && !this.getFilterOnPoS().equals("Tutti")) { nativeQuery += " and %1$s.pos='" + this.getFilterOnPoS().trim() + "'"; } nativeQuery += " and dist between -" + this.getDistanceLeft() + " and " + this.getDistanceRight() + " and %3$s.freq >= " + this.getFreqMinColl() + " group by %1$s.%2$s having observed >= " + this.getFreqMinNC() + " order by significance desc LIMIT " + this.getFirstResult() + ", " + this.getPageSize(); nativeQuery = String.format(nativeQuery, CWBCollocatesExtractor.COLLOCATE_DB_PREFIX + this.conversationId, collBasedOn, freqTable); System.out.println(nativeQuery); if (!this.userTx.isActive()) { this.userTx.begin(); } this.entityManager.joinTransaction(); List<Object[]> res = this.entityManager.createNativeQuery(nativeQuery).getResultList(); this.entityManager.flush(); this.entityManager.clear(); this.userTx.commit(); this.cwbCollocateResults = new ArrayList<CWBCollocateResult>(); for (Object[] r : res) { CWBCollocateResult cwbCollocateResult = new CWBCollocateResult(r[0] + "", ((Number) r[4]).longValue(), ((Number) r[2]).doubleValue(), ((Number) r[1]).longValue(), ((Number) r[5]).longValue(), ((Number) r[3]).doubleValue(), this.getScore()); this.cwbCollocateResults.add(cwbCollocateResult); } } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NotSupportedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RollbackException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (HeuristicMixedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (HeuristicRollbackException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "OK"; }
From source file:org.polymap.kaps.ui.MyNumberValidator.java
public Object transform2Model(Object fieldValue) throws Exception { if (fieldValue == null) { return null; } else if (fieldValue instanceof String) { if (((String) fieldValue).isEmpty()) { return null; }//from ww w. j av a 2 s .co m ParsePosition pp = new ParsePosition(0); Number result = nf.parse((String) fieldValue, pp); if (pp.getErrorIndex() > -1 || pp.getIndex() < ((String) fieldValue).length()) { throw new ParseException("field value: " + fieldValue + " for targetClass " + targetClass.getName(), pp.getErrorIndex()); } log.debug("value: " + fieldValue + " -> " + result.doubleValue()); // XXX check max digits if (Float.class.isAssignableFrom(targetClass)) { return Float.valueOf(result.floatValue()); } else if (Double.class.isAssignableFrom(targetClass)) { return Double.valueOf(result.doubleValue()); } else if (Integer.class.isAssignableFrom(targetClass)) { return Integer.valueOf(result.intValue()); } else if (Long.class.isAssignableFrom(targetClass)) { return Long.valueOf(result.longValue()); } else { throw new RuntimeException("Unsupported target type: " + targetClass); } } else { throw new RuntimeException("Unhandled field value type: " + fieldValue); } }
From source file:cc.aileron.accessor.TypeConvertorImpl.java
/** * default constractor/*from w w w. j a v a 2 s. co m*/ */ @Inject public TypeConvertorImpl() { map.put(Boolean.TYPE, new C() { @Override public Boolean convert(final java.lang.Number number) { return number.intValue() != 0; } }); map.put(Byte.TYPE, new C() { @Override public Byte convert(final java.lang.Number number) { return number.byteValue(); } }); map.put(Short.TYPE, new C() { @Override public Short convert(final java.lang.Number number) { return number.shortValue(); } }); map.put(Integer.TYPE, new C() { @Override public Integer convert(final java.lang.Number number) { return number.intValue(); } }); map.put(Long.TYPE, new C() { @Override public Long convert(final java.lang.Number number) { return number.longValue(); } }); map.put(Float.TYPE, new C() { @Override public Float convert(final java.lang.Number number) { return number.floatValue(); } }); map.put(Double.TYPE, new C() { @Override public Double convert(final java.lang.Number number) { return number.doubleValue(); } }); }
From source file:org.springframework.jdbc.core.JdbcTemplate.java
public long queryForLong(String sql) throws DataAccessException { Number number = (Number) queryForObject(sql, Number.class); return (number != null ? number.longValue() : 0); }
From source file:org.opencms.db.jpa.CmsSubscriptionDriver.java
/** * @see org.opencms.db.I_CmsSubscriptionDriver#markResourceAsVisitedBy(org.opencms.db.CmsDbContext, java.lang.String, org.opencms.file.CmsResource, org.opencms.file.CmsUser) *//*from w w w . ja v a2s . co m*/ public void markResourceAsVisitedBy(CmsDbContext dbc, String poolName, CmsResource resource, CmsUser user) throws CmsDataAccessException { boolean entryExists = false; CmsVisitEntryFilter filter = CmsVisitEntryFilter.ALL.filterResource(resource.getStructureId()) .filterUser(user.getId()); // delete existing visited entry for the resource if (readVisits(dbc, OpenCms.getSubscriptionManager().getPoolName(), filter).size() > 0) { entryExists = true; deleteVisits(dbc, OpenCms.getSubscriptionManager().getPoolName(), filter); } CmsVisitEntry entry = new CmsVisitEntry(user.getId(), System.currentTimeMillis(), resource.getStructureId()); addVisit(dbc, poolName, entry); if (!entryExists) { // new entry, check if maximum number of stored visited resources is exceeded int count = 0; try { Query q = m_sqlManager.createQuery(dbc, dbc.currentProject(), C_VISITED_USER_COUNT_1); q.setParameter(1, user.getId().toString()); count = ((Number) q.getSingleResult()).intValue(); int maxCount = OpenCms.getSubscriptionManager().getMaxVisitedCount(); if (count > maxCount) { // delete old visited entries q = m_sqlManager.createQuery(dbc, dbc.currentProject(), C_VISITED_USER_DELETE_GETDATE_2); q.setParameter(1, user.getId().toString()); q.setMaxResults(count - maxCount); @SuppressWarnings("unchecked") List<Number> res = q.getResultList(); long deleteDate = 0; for (Number n : res) { // get last date of result set deleteDate = n.longValue(); } if (deleteDate > 0) { filter = CmsVisitEntryFilter.ALL.filterUser(user.getId()).filterTo(deleteDate); deleteVisits(dbc, OpenCms.getSubscriptionManager().getPoolName(), filter); } } } catch (PersistenceException e) { throw new CmsDbSqlException( Messages.get().container(Messages.ERR_GENERIC_SQL_1, C_VISITED_USER_DELETE_GETDATE_2), e); } } }
From source file:com.haulmont.cuba.gui.export.ExcelExporter.java
protected void formatValueCell(HSSFCell cell, @Nullable Object cellValue, @Nullable MetaPropertyPath metaPropertyPath, int sizersIndex, int notificationRequired, int level, @Nullable Integer groupChildCount) { if (cellValue == null) { return;//from w w w . j a v a2 s .c om } String childCountValue = ""; if (groupChildCount != null) { childCountValue = " (" + groupChildCount + ")"; } if (cellValue instanceof IdProxy) { cellValue = ((IdProxy) cellValue).get(); } if (cellValue instanceof Number) { Number n = (Number) cellValue; final Datatype datatype = Datatypes.getNN(n.getClass()); String str; if (sizersIndex == 0) { str = createSpaceString(level) + datatype.format(n); cell.setCellValue(str); } else { try { str = datatype.format(n); Number result = (Number) datatype.parse(str); if (result != null) { if (n instanceof Integer || n instanceof Long || n instanceof Byte || n instanceof Short) { cell.setCellValue(result.longValue()); cell.setCellStyle(integerFormatCellStyle); } else { cell.setCellValue(result.doubleValue()); cell.setCellStyle(doubleFormatCellStyle); } } } catch (ParseException e) { throw new RuntimeException("Unable to parse numeric value", e); } cell.setCellType(CellType.NUMERIC); } if (sizers[sizersIndex].isNotificationRequired(notificationRequired)) { sizers[sizersIndex].notifyCellValue(str, stdFont); } } else if (cellValue instanceof Date) { Class javaClass = null; boolean supportTimezones = false; TimeZone timeZone = userSessionSource.getUserSession().getTimeZone(); if (metaPropertyPath != null) { MetaProperty metaProperty = metaPropertyPath.getMetaProperty(); if (metaProperty.getRange().isDatatype()) { javaClass = metaProperty.getRange().asDatatype().getJavaClass(); } Boolean ignoreUserTimeZone = metadataTools.getMetaAnnotationValue(metaProperty, IgnoreUserTimeZone.class); supportTimezones = timeZone != null && Objects.equals(Date.class, javaClass) && !Boolean.TRUE.equals(ignoreUserTimeZone); } Date date = (Date) cellValue; if (supportTimezones) { TimeZone currentTimeZone = LocaleUtil.getUserTimeZone(); try { LocaleUtil.setUserTimeZone(timeZone); cell.setCellValue(date); } finally { if (Objects.equals(currentTimeZone, TimeZone.getDefault())) { LocaleUtil.resetUserTimeZone(); } else { LocaleUtil.setUserTimeZone(currentTimeZone); } } } else { cell.setCellValue(date); } if (Objects.equals(java.sql.Time.class, javaClass)) { cell.setCellStyle(timeFormatCellStyle); } else if (Objects.equals(java.sql.Date.class, javaClass)) { cell.setCellStyle(dateFormatCellStyle); } else { cell.setCellStyle(dateTimeFormatCellStyle); } if (sizers[sizersIndex].isNotificationRequired(notificationRequired)) { String str = Datatypes.getNN(Date.class).format(date); sizers[sizersIndex].notifyCellValue(str, stdFont); } } else if (cellValue instanceof Boolean) { String str = ""; if (sizersIndex == 0) { str += createSpaceString(level); } str += ((Boolean) cellValue) ? trueStr : falseStr; cell.setCellValue(new HSSFRichTextString(str)); if (sizers[sizersIndex].isNotificationRequired(notificationRequired)) { sizers[sizersIndex].notifyCellValue(str, stdFont); } } else if (cellValue instanceof EnumClass) { String nameKey = cellValue.getClass().getSimpleName() + "." + cellValue.toString(); final String message = sizersIndex == 0 ? createSpaceString(level) + messages.getMessage(cellValue.getClass(), nameKey) : messages.getMessage(cellValue.getClass(), nameKey); cell.setCellValue(message + childCountValue); if (sizers[sizersIndex].isNotificationRequired(notificationRequired)) { sizers[sizersIndex].notifyCellValue(message, stdFont); } } else if (cellValue instanceof Entity) { Entity entityVal = (Entity) cellValue; String instanceName = entityVal.getInstanceName(); String str = sizersIndex == 0 ? createSpaceString(level) + instanceName : instanceName; str = str + childCountValue; cell.setCellValue(new HSSFRichTextString(str)); if (sizers[sizersIndex].isNotificationRequired(notificationRequired)) { sizers[sizersIndex].notifyCellValue(str, stdFont); } } else if (cellValue instanceof Collection) { String str = ""; cell.setCellValue(new HSSFRichTextString(str)); if (sizers[sizersIndex].isNotificationRequired(notificationRequired)) { sizers[sizersIndex].notifyCellValue(str, stdFont); } } else { String strValue = cellValue == null ? "" : cellValue.toString(); String str = sizersIndex == 0 ? createSpaceString(level) + strValue : strValue; str = str + childCountValue; cell.setCellValue(new HSSFRichTextString(str)); if (sizers[sizersIndex].isNotificationRequired(notificationRequired)) { sizers[sizersIndex].notifyCellValue(str, stdFont); } } }
From source file:org.springframework.jdbc.core.JdbcTemplate.java
public long queryForLong(String sql, final Object[] args) throws DataAccessException { Number number = (Number) queryForObject(sql, args, Number.class); return (number != null ? number.longValue() : 0); }
From source file:vteaexploration.plottools.panels.XYChartPanel.java
private double getRangeofData(ArrayList alVolumes, int x) { ListIterator litr = alVolumes.listIterator(); ArrayList<Number> al = new ArrayList<Number>(); Number low = 0;//w w w . j ava2 s . c om Number high = 0; Number test; while (litr.hasNext()) { try { MicroObjectModel volume = (MicroObjectModel) litr.next(); Number Corrected = processPosition(x, volume); al.add(Corrected); if (Corrected.floatValue() < low.floatValue()) { low = Corrected; } if (Corrected.floatValue() > high.floatValue()) { high = Corrected; } } catch (NullPointerException e) { } } return high.longValue() - low.longValue(); }