List of usage examples for java.lang Long longValue
@HotSpotIntrinsicCandidate public long longValue()
From source file:com.ottogroup.bi.spqr.operator.esper.EsperOperator.java
/** * Callback invoked by ESPER for nay result * @param eventMap//from w ww . j a va2 s.c o m */ public void update(Map<String, Object> eventMap) { @SuppressWarnings("unchecked") Map<String, Object> body = eventMap; Long timestamp = (Long) eventMap.get(SPQR_EVENT_TIMESTAMP_FIELD); if (body != null) { try { byte[] messageBody = mapper.writeValueAsBytes(body); if (messageBody != null && messageBody.length > 0) { result = new StreamingDataMessage[] { new StreamingDataMessage(messageBody, (timestamp != null ? timestamp.longValue() : System.currentTimeMillis())) }; this.waitStrategy.release(); } } catch (IOException e) { logger.error("Failed to parse ESPER result to JSON representation. Error: " + e.getMessage(), e); } } }
From source file:com.qpark.eip.core.model.analysis.AnalysisDao.java
/** * Check if the {@link EnterpriseType} with given name and modelVersion * exists./*w w w. j av a 2s . co m*/ * * @param name * the name of the {@link EnterpriseType}. * @param modelVersion * the version of the model. * @return <code>true</code> if exists, else <code>false</code>. */ @Transactional(value = EipModelAnalysisPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED) public boolean existsEnterprise(final String name, final String modelVersion) { boolean value = false; final CriteriaBuilder cb = this.em.getCriteriaBuilder(); final CriteriaQuery<Long> q = cb.createQuery(Long.class); final Root<EnterpriseType> f = q.from(EnterpriseType.class); q.select(f.<Long>get(EnterpriseType_.hjid)); q.where(cb.equal(f.<String>get(EnterpriseType_.name), name), cb.equal(f.<String>get(EnterpriseType_.modelVersion), modelVersion)); final TypedQuery<Long> typedQuery = this.em.createQuery(q); try { final Long l = typedQuery.getSingleResult(); if (l != null && l.longValue() != 0) { value = true; } } catch (final Exception e) { value = false; } return value; }
From source file:org.apache.manifoldcf.crawler.connectors.webcrawler.CookieManager.java
/** Read cookies from database, uncached. *@param sessionKey is the session key.//from w w w .j a va2s. c o m *@return the login cookies object. */ protected LoginCookies readCookiesUncached(String sessionKey) throws ManifoldCFException { ArrayList list = new ArrayList(); list.add(sessionKey); IResultSet result = performQuery( "SELECT * FROM " + getTableName() + " WHERE " + keyField + "=? ORDER BY " + ordinalField + " ASC", list, null, null); DynamicCookieSet dcs = new DynamicCookieSet(); int i = 0; while (i < result.getRowCount()) { IResultRow row = result.getRow(i++); String name = (String) row.getValue(nameField); String value = (String) row.getValue(valueField); BasicClientCookie2 c = new BasicClientCookie2(name, value); String domain = (String) row.getValue(domainField); if (domain != null && domain.length() > 0) c.setDomain(domain); //c.setDomainAttributeSpecified(stringToBoolean((String)row.getValue(domainSpecifiedField))); String path = (String) row.getValue(pathField); if (path != null && path.length() > 0) c.setPath(path); //c.setPathAttributeSpecified(stringToBoolean((String)row.getValue(pathSpecifiedField))); Long version = (Long) row.getValue(versionField); if (version != null) c.setVersion((int) version.longValue()); //c.setVersionAttributeSpecified(stringToBoolean((String)row.getValue(versionSpecifiedField))); String comment = (String) row.getValue(commentField); if (comment != null) c.setComment(comment); c.setSecure(stringToBoolean((String) row.getValue(secureField))); Long expirationDate = (Long) row.getValue(expirationDateField); if (expirationDate != null) c.setExpiryDate(new Date(expirationDate.longValue())); c.setDiscard(stringToBoolean((String) row.getValue(discardField))); String commentURL = (String) row.getValue(commentURLField); if (commentURL != null && commentURL.length() > 0) c.setCommentURL(commentURL); String ports = (String) row.getValue(portField); // Ports are comma-separated if (ports != null && ports.length() > 0) c.setPorts(stringToPorts(ports)); //c.setPortAttributeBlank(stringToBoolean((String)row.getValue(portBlankField))); //c.setPortAttributeSpecified(stringToBoolean((String)row.getValue(portSpecifiedField))); dcs.addCookie(c); } return dcs; }
From source file:com.gs.obevo.db.impl.core.changeauditdao.SameSchemaDeployExecutionDao.java
private void init(Connection conn, PhysicalSchema physicalSchema) { DbChangeTypeBehavior tableChangeType = (DbChangeTypeBehavior) changeTypeBehaviorRegistry .getChangeTypeBehavior(ChangeType.TABLE_STR); if (!isDaoInitialized(physicalSchema)) { // create main table jdbc.execute(conn, get5_3TableSql(physicalSchema)); tableChangeType.applyGrants(conn, physicalSchema, deployExecutionTableName, Lists.immutable.with(new Permission("artifactTable", Lists.immutable.with(new Grant(Lists.immutable.with("SELECT"), Multimaps.immutable.list.with(GrantTargetType.PUBLIC, "PUBLIC")))))); // create attr table jdbc.execute(conn, get5_2AttrTableSql(physicalSchema)); tableChangeType.applyGrants(conn, physicalSchema, deployExecutionAttributeTableName, Lists.immutable.with(new Permission("artifactTable", Lists.immutable.with(new Grant(Lists.immutable.with("SELECT"), Multimaps.immutable.list.with(GrantTargetType.PUBLIC, "PUBLIC")))))); } else {/*from w w w .jav a 2s . c o m*/ DaTable executionTable = this.dbMetadataManager.getTableInfo(physicalSchema.getPhysicalName(), deployExecutionTableName, new DaSchemaInfoLevel().setRetrieveTables(true).setRetrieveTableColumns(true)); if (executionTable.getColumn(productVersionColName) == null) { // add the column if missing jdbc.execute(conn, String.format("ALTER TABLE %s ADD %s %s %s", deployExecutionTableName, productVersionColName, "VARCHAR(255)", platform.getNullMarkerForCreateTable())); backfillProductVersionColumn(conn); } if (executionTable.getColumn(dbSchemaColName) == null) { // add the column if missing jdbc.execute(conn, String.format("ALTER TABLE %s ADD %s %s %s", deployExecutionTableName, dbSchemaColName, "VARCHAR(255)", platform.getNullMarkerForCreateTable())); // let's now try to backfill the column, but it's tricky as we may be missing some information backfillDbSchemaColumn(conn); } } Long maxId = getMaxId(conn, physicalSchema); nextIdBySchema.get(physicalSchema).setValue(maxId != null ? maxId.longValue() + 1 : 1); }
From source file:com.examples.with.different.packagename.testcarver.DateTimeConverter.java
/** * Convert the input object into a Date object of the * specified type.//from w w w.j a va 2 s .co m * <p> * This method handles conversions between the following * types: * <ul> * <li><code>java.util.Date</code></li> * <li><code>java.util.Calendar</code></li> * <li><code>java.sql.Date</code></li> * <li><code>java.sql.Time</code></li> * <li><code>java.sql.Timestamp</code></li> * </ul> * * It also handles conversion from a <code>String</code> to * any of the above types. * <p> * * For <code>String</code> conversion, if the converter has been configured * with one or more patterns (using <code>setPatterns()</code>), then * the conversion is attempted with each of the specified patterns. * Otherwise the default <code>DateFormat</code> for the default locale * (and <i>style</i> if configured) will be used. * * @param targetType Data type to which this value should be converted. * @param value The input value to be converted. * @return The converted value. * @throws Exception if conversion cannot be performed successfully */ protected Object convertToType(Class targetType, Object value) throws Exception { Class sourceType = value.getClass(); // Handle java.sql.Timestamp if (value instanceof java.sql.Timestamp) { // ---------------------- JDK 1.3 Fix ---------------------- // N.B. Prior to JDK 1.4 the Timestamp's getTime() method // didn't include the milliseconds. The following code // ensures it works consistently accross JDK versions java.sql.Timestamp timestamp = (java.sql.Timestamp) value; long timeInMillis = ((timestamp.getTime() / 1000) * 1000); timeInMillis += timestamp.getNanos() / 1000000; // ---------------------- JDK 1.3 Fix ---------------------- return toDate(targetType, timeInMillis); } // Handle Date (includes java.sql.Date & java.sql.Time) if (value instanceof Date) { Date date = (Date) value; return toDate(targetType, date.getTime()); } // Handle Calendar if (value instanceof Calendar) { Calendar calendar = (Calendar) value; return toDate(targetType, calendar.getTime().getTime()); } // Handle Long if (value instanceof Long) { Long longObj = (Long) value; return toDate(targetType, longObj.longValue()); } // Convert all other types to String & handle String stringValue = value.toString().trim(); if (stringValue.length() == 0) { return handleMissing(targetType); } // Parse the Date/Time if (useLocaleFormat) { Calendar calendar = null; if (patterns != null && patterns.length > 0) { calendar = parse(sourceType, targetType, stringValue); } else { DateFormat format = getFormat(locale, timeZone); calendar = parse(sourceType, targetType, stringValue, format); } if (Calendar.class.isAssignableFrom(targetType)) { return calendar; } else { return toDate(targetType, calendar.getTime().getTime()); } } // Default String conversion return toDate(targetType, stringValue); }
From source file:hu.netmind.beankeeper.cache.impl.MinimalResultsCache.java
/** * Add an entry to the cache./* w w w . j a va 2 s. c om*/ * @param stmt The statement source of result. * @param limits The limits of result. * @param result The SearchResult object. */ public void addEntry(QueryStatement stmt, Limits limits, SearchResult result) { // Check whether entry was modified in the same transaction. Only // those results are cached, which are global. if (stmt.getTimeControl().isApplyTransaction()) return; // Rep String rep = getRepresentation(stmt, limits); if (logger.isDebugEnabled()) logger.debug("adding to cache: " + rep + ", entries: " + entriesByExpiration.size()); if ((rep == null) || ("".equals(rep))) return; // First, determine how many entries to free. By default, all expired // entries are freed, but if there is not enough memory, entries // can be forced to be removed. int forceFreeResultsCount = 0; // By default none are forced long freeMem = Runtime.getRuntime().freeMemory(); long totalMem = Runtime.getRuntime().totalMemory(); if ((freeMem < MIN_FREE_BYTES) || (100.0 * freeMem / totalMem > MIN_FREE_RATE)) { if (logger.isDebugEnabled()) logger.debug("not enough memory to cache, free: " + freeMem + ", total: " + totalMem); // Not enough memory, set force free count forceFreeResultsCount = result.getResult().size() * FREE_RATE + 1; } // Free entries long currentTime = System.currentTimeMillis(); long lastExpiration = currentTime; while (((forceFreeResultsCount > 0) || (lastExpiration < currentTime)) && (entriesByExpiration.size() > 0)) { // Get top entry CacheEntry entry = null; synchronized (cacheMutex) { entry = (CacheEntry) entriesByExpiration.first(); } // Set indicators lastExpiration = entry.expiration; forceFreeResultsCount -= entry.result.getResult().size(); // Free it removeEntry(entry); } if (logger.isDebugEnabled()) logger.debug("cache entries after free: " + entriesByExpiration.size()); // Create new entry CacheEntry entry = new CacheEntry(); entry.representation = rep; entry.result = result; entry.accessCount = 0; entry.firstAccess = currentTime; entry.lastAccess = currentTime; entry.expiration = currentTime + EXPIRATION_INTERVAL; entry.tables = stmt.computeTables(); entry.startSerial = stmt.getTimeControl().getSerial().longValue(); // Add new entry to cache synchronized (cacheMutex) { // Determine whether entry is current (all table // modifications are previous to entry) Iterator tableIterator = entry.tables.iterator(); while (tableIterator.hasNext()) { String tableName = (String) tableIterator.next(); Long lastModificationSerial = (Long) serialsByTables.get(tableName); if (lastModificationSerial == null) lastModificationSerial = startSerial; if (lastModificationSerial.longValue() > entry.startSerial) return; // Table is newer than query, so query is historical } // Add to maps entriesByExpiration.add(entry); entriesByRepresentation.put(entry.representation, entry); // Add to table indexed map tableIterator = entry.tables.iterator(); while (tableIterator.hasNext()) { String tableName = (String) tableIterator.next(); Set tableEntries = (Set) entriesByTables.get(tableName); if (tableEntries == null) { tableEntries = new HashSet(); entriesByTables.put(tableName, tableEntries); } tableEntries.add(entry); } // Add to management bean synchronized (cache) { cache.setResultCount(cache.getResultCount() + 1); cache.setObjectCount(cache.getObjectCount() + entry.result.getResult().size()); } } }
From source file:helma.objectmodel.db.Transactor.java
/** * Get a db connection that was previously registered with this transactor thread. * @param src the db source//from ww w . ja va2 s .c o m * @return the connection */ public Connection getConnection(DbSource src) { Connection con = (Connection) sqlConnections.get(src); Long tested = (Long) testedConnections.get(src); long now = System.currentTimeMillis(); if (con != null && (tested == null || now - tested.longValue() > 60000)) { // Check if the connection is still alive by executing a simple statement. try { Statement stmt = con.createStatement(); stmt.execute("SELECT 1"); stmt.close(); testedConnections.put(src, new Long(now)); } catch (SQLException sx) { try { con.close(); } catch (SQLException ignore) { /* nothing to do */} return null; } } return con; }
From source file:com.xavax.json.JSON.java
/** * Get the long field with the specified name. If the field is missing * or null, return the specified default value. * * @param key the name of the field./*from w ww . j a v a 2 s. com*/ * @param defaultValue the value to return if the field is null. * @return the long field with the specified name. */ public long getLong(final String key, final long defaultValue) { final Long value = getLong(key); return value == null ? defaultValue : value.longValue(); }
From source file:de.fhg.fokus.odp.middleware.unittest.xTestCKANGateway.java
/** * Test get rating count./*from w w w .ja va 2 s . c o m*/ */ @Test public void testGetRatingCount() { log.fine("########### GET RATING COUNT ###########"); String dataSetId = DATASET_NAME; // dataSetId = "berlinwahl_2011_vorlaeufig"; Long count = ckanGW.getRatingCount(dataSetId); log.fine("count: " + count); assertEquals(count.longValue(), 1L); }
From source file:com.github.gerbsen.math.Frequency.java
/** * Adds 1 to the frequency count for v./* w w w. j a va 2s. c o m*/ * <p> * If other objects have already been added to this Frequency, v must * be comparable to those that have already been added. * </p> * * @param v the value to add. * @throws IllegalArgumentException if <code>v</code> is not comparable with previous entries */ public void addValue(Comparable<?> v) { Comparable<?> obj = v; if (v instanceof Integer) { obj = Long.valueOf(((Integer) v).longValue()); } try { Long count = freqTable.get(obj); if (count == null) { freqTable.put(obj, Long.valueOf(1)); } else { freqTable.put(obj, Long.valueOf(count.longValue() + 1)); } } catch (ClassCastException ex) { //TreeMap will throw ClassCastException if v is not comparable throw new MathIllegalArgumentException(LocalizedFormats.INSTANCES_NOT_COMPARABLE_TO_EXISTING_VALUES, v.getClass().getName()); } }