code
stringlengths
73
34.1k
label
stringclasses
1 value
public final Object assemble(Serializable cached, Object owner) throws HibernateException { if (cached != null) { log.trace("assemble " + cached + " (" + cached.getClass() + "), owner is " + owner); } return cached; }
java
public LobbyStatus createGroupFinderLobby(int type, String uuid) { return client.sendRpcAndWait(SERVICE, "createGroupFinderLobby", type, uuid); }
java
public Object call(String uuid, GameMode mode, String procCall, JsonObject object) { return client.sendRpcAndWait(SERVICE, "call", uuid, mode.name(), procCall, object.toString()); }
java
@SuppressWarnings("unchecked") public List<T> run(final Object... iArgs) { final ODatabaseRecord database = ODatabaseRecordThreadLocal.INSTANCE.get(); if (database == null) throw new OQueryParsingException("No database configured"); setParameters(iArgs); return (List<T>) database.getStorage().command(this); }
java
public AddressbookQuery limitNumberOfResults(int limit) { if (limit > 0) { addLimit(WebDavSearch.NRESULTS, limit); } else { removeLimit(WebDavSearch.NRESULTS); } return this; }
java
public void close() { for (Entry<String, OResourcePool<String, DB>> pool : pools.entrySet()) { for (DB db : pool.getValue().getResources()) { pool.getValue().close(); try { OLogManager.instance().debug(this, "Closing pooled database '%s'...", db.getName()); ((ODatabasePooled) db).forceClose(); OLogManager.instance().debug(this, "OK", db.getName()); } catch (Exception e) { OLogManager.instance().debug(this, "Error: %d", e.toString()); } } } }
java
public static boolean isMultiValue(final Class<?> iType) { return (iType.isArray() || Collection.class.isAssignableFrom(iType) || Map.class.isAssignableFrom(iType)); }
java
public static int getSize(final Object iObject) { if (iObject == null) return 0; if (!isMultiValue(iObject)) return 0; if (iObject instanceof Collection<?>) return ((Collection<Object>) iObject).size(); if (iObject instanceof Map<?, ?>) return ((Map<?, Object>) iObject).size(); if (iObject.getClass().isArray()) return Array.getLength(iObject); return 0; }
java
public static boolean pauseCurrentThread(long iTime) { try { if (iTime <= 0) iTime = Long.MAX_VALUE; Thread.sleep(iTime); return true; } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } }
java
public Stream<String> containing(double lat, double lon) { return shapes.keySet().stream() // select if contains lat lon .filter(name -> shapes.get(name).contains(lat, lon)); }
java
public OQuery<T> setFetchPlan(final String fetchPlan) { OFetchHelper.checkFetchPlanValid(fetchPlan); if (fetchPlan != null && fetchPlan.length() == 0) this.fetchPlan = null; else this.fetchPlan = fetchPlan; return this; }
java
public static ITargetIdentifier field(final String fieldName) { return new ITargetIdentifier() { public IDependencyInjector of(final Object target) { return new FieldInjector(target, fieldName); } }; }
java
public static ITargetInjector with(final IInjectionStrategy strategy) { return new ITargetInjector() { public void bean(Object target) { strategy.inject(target); } }; }
java
public OQueryContextNative key(final Object iKey) { if (finalResult != null && finalResult.booleanValue()) return this; if (iKey == null) // ERROR: BREAK CHAIN return error(); if (currentValue != null && currentValue instanceof Map) currentValue = ((Map<Object, Object>) currentValue).get(iKey); return this; }
java
public synchronized RESPONSE_TYPE getValue(final RESOURCE_TYPE iResource, final long iTimeout) { if (OLogManager.instance().isDebugEnabled()) OLogManager.instance().debug( this, "Thread [" + Thread.currentThread().getId() + "] is waiting for the resource " + iResource + (iTimeout <= 0 ? " forever" : " until " + iTimeout + "ms")); synchronized (iResource) { try { iResource.wait(iTimeout); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new OLockException("Thread interrupted while waiting for resource '" + iResource + "'"); } } Object[] value = queue.remove(iResource); return (RESPONSE_TYPE) (value != null ? value[1] : null); }
java
public synchronized void setClassHandler(final OEntityManagerClassHandler iClassHandler) { for (Entry<String, Class<?>> entry : classHandler.getClassesEntrySet()) { iClassHandler.registerEntityClass(entry.getValue()); } this.classHandler = iClassHandler; }
java
@GET @Path("create") public Response createFromRedirect() { KeycloakPrincipal principal = (KeycloakPrincipal) sessionContext.getCallerPrincipal(); RefreshableKeycloakSecurityContext kcSecurityContext = (RefreshableKeycloakSecurityContext) principal.getKeycloakSecurityContext(); String refreshToken = kcSecurityContext.getRefreshToken(); Token token = create(refreshToken); try { String redirectTo = System.getProperty("secretstore.redirectTo"); if (null == redirectTo || redirectTo.isEmpty()) { return Response.ok("Redirect URL was not specified but token was created.").build(); } URI location; if (redirectTo.toLowerCase().startsWith("http")) { location = new URI(redirectTo); } else { URI uri = uriInfo.getAbsolutePath(); String newPath = redirectTo.replace("{tokenId}", token.getId().toString()); location = new URI( uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), newPath, uri.getQuery(), uri.getFragment() ); } return Response.seeOther(location).build(); } catch (URISyntaxException e) { e.printStackTrace(); return Response.ok("Could not redirect back to the original URL, but token was created.").build(); } }
java
@POST @Path("create") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response createFromBasicAuth() throws Exception { return doCreateFromBasicAuth(null); }
java
public OStorageConfiguration load() throws OSerializationException { final byte[] record = storage.readRecord(CONFIG_RID, null, false, null).buffer; if (record == null) throw new OStorageException("Cannot load database's configuration. The database seems to be corrupted."); fromStream(record); return this; }
java
public static <T> Option<T> some(T t) { return new Option.Some<T>(t); }
java
public static <T> Option<T> of(T t) { return t == null ? Option.<T>none() : some(t); }
java
public PropertyRequest addProperty(ElementDescriptor<?> property) { if (mProp == null) { mProp = new HashMap<ElementDescriptor<?>, Object>(16); } mProp.put(property, null); return this; }
java
public void setOption(Option option) { switch (option) { case ARRAY_ORDER_SIGNIFICANT: arrayComparator = new DefaultArrayNodeComparator(); break; case ARRAY_ORDER_INSIGNIFICANT: arrayComparator = new SetArrayNodeComparator(); break; case RETURN_PARENT_DIFFS: returnParentDiffs = true; break; case RETURN_LEAVES_ONLY: returnParentDiffs = false; break; } }
java
public List<JsonDelta> computeDiff(String node1, String node2) throws IOException { ObjectMapper mapper = new ObjectMapper(); return computeDiff(mapper.readTree(node1), mapper.readTree(node2)); }
java
public List<JsonDelta> computeDiff(JsonNode node1, JsonNode node2) { List<JsonDelta> list = new ArrayList<>(); computeDiff(list, new ArrayList<String>(), node1, node2); return list; }
java
public boolean computeDiff(List<JsonDelta> delta, List<String> context, JsonNode node1, JsonNode node2) { boolean ret = false; if (context.size() == 0 || filter.includeField(context)) { JsonComparator cmp = getComparator(context, node1, node2); if (cmp != null) { ret = cmp.compare(delta, context, node1, node2); } else { delta.add(new JsonDelta(toString(context), node1, node2)); ret = true; } } return ret; }
java
public JsonComparator getComparator(List<String> context, JsonNode node1, JsonNode node2) { if (node1 == null) { if (node2 == null) { return NODIFF_CMP; } else { return null; } } else if (node2 == null) { return null; } else { if (node1 instanceof NullNode) { if (node2 instanceof NullNode) { return NODIFF_CMP; } else { return null; } } else if (node2 instanceof NullNode) { return null; } // Nodes are not null, and they are not null node if (node1.isContainerNode() && node2.isContainerNode()) { if (node1 instanceof ObjectNode) { return objectComparator; } else if (node1 instanceof ArrayNode) { return arrayComparator; } } else if (node1.isValueNode() && node2.isValueNode()) { return valueComparator; } } return null; }
java
public LobbyStatus createGroupFinderLobby(long queueId, String uuid) { return client.sendRpcAndWait(SERVICE, "createGroupFinderLobby", queueId, uuid); }
java
boolean flush() { if (!dirty) return true; acquireExclusiveLock(); try { final long timer = OProfiler.getInstance().startChrono(); // FORCE THE WRITE OF THE BUFFER for (int i = 0; i < FORCE_RETRY; ++i) { try { buffer.force(); dirty = false; break; } catch (Exception e) { OLogManager.instance().debug(this, "Cannot write memory buffer to disk. Retrying (" + (i + 1) + "/" + FORCE_RETRY + ")..."); OMemoryWatchDog.freeMemory(FORCE_DELAY); } } if (dirty) OLogManager.instance().debug(this, "Cannot commit memory buffer to disk after %d retries", FORCE_RETRY); else OProfiler.getInstance().updateCounter("system.file.mmap.pagesCommitted", 1); OProfiler.getInstance().stopChrono("system.file.mmap.commitPages", timer); return !dirty; } finally { releaseExclusiveLock(); } }
java
void close() { acquireExclusiveLock(); try { if (buffer != null) { if (dirty) buffer.force(); if (sunClass != null) { // USE SUN JVM SPECIAL METHOD TO FREE RESOURCES try { final Method m = sunClass.getMethod("cleaner"); final Object cleaner = m.invoke(buffer); cleaner.getClass().getMethod("clean").invoke(cleaner); } catch (Exception e) { OLogManager.instance().error(this, "Error on calling Sun's MMap buffer clean", e); } } buffer = null; } counter = 0; file = null; } finally { releaseExclusiveLock(); } }
java
private Set<Comparable> prepareKeys(OIndex<?> index, Object keys) { final Class<?> targetType = index.getKeyTypes()[0].getDefaultJavaType(); return convertResult(keys, targetType); }
java
public void validate() throws OValidationException { if (ODatabaseRecordThreadLocal.INSTANCE.isDefined() && !getDatabase().isValidationEnabled()) return; checkForLoading(); checkForFields(); if (_clazz != null) { if (_clazz.isStrictMode()) { // CHECK IF ALL FIELDS ARE DEFINED for (String f : fieldNames()) { if (_clazz.getProperty(f) == null) throw new OValidationException("Found additional field '" + f + "'. It cannot be added because the schema class '" + _clazz.getName() + "' is defined as STRICT"); } } for (OProperty p : _clazz.properties()) { validateField(this, p); } } }
java
public <T> void set(ElementDescriptor<T> property, T value) { if (mSet == null) { mSet = new HashMap<ElementDescriptor<?>, Object>(16); } mSet.put(property, value); if (mRemove != null) { mRemove.remove(property); } }
java
public <T> void remove(ElementDescriptor<T> property) { if (mRemove == null) { mRemove = new HashMap<ElementDescriptor<?>, Object>(16); } mRemove.put(property, null); if (mSet != null) { mSet.remove(property); } }
java
public <T> void clear(ElementDescriptor<T> property) { if (mRemove != null) { mRemove.remove(property); } if (mSet != null) { mSet.remove(property); } }
java
public void updateRecord(final ORecordInternal<?> fresh) { if (!isEnabled() || fresh == null || fresh.isDirty() || fresh.getIdentity().isNew() || !fresh.getIdentity().isValid() || fresh.getIdentity().getClusterId() == excludedCluster) return; if (fresh.isPinned() == null || fresh.isPinned()) { underlying.lock(fresh.getIdentity()); try { final ORecordInternal<?> current = underlying.get(fresh.getIdentity()); if (current != null && current.getVersion() >= fresh.getVersion()) return; if (ODatabaseRecordThreadLocal.INSTANCE.isDefined() && !ODatabaseRecordThreadLocal.INSTANCE.get().isClosed()) // CACHE A COPY underlying.put((ORecordInternal<?>) fresh.flatCopy()); else { // CACHE THE DETACHED RECORD fresh.detach(); underlying.put(fresh); } } finally { underlying.unlock(fresh.getIdentity()); } } else underlying.remove(fresh.getIdentity()); }
java
public ColumnList addColumn(byte[] family, byte[] qualifier, byte[] value){ columns().add(new Column(family, qualifier, -1, value)); return this; }
java
public ColumnList addCounter(byte[] family, byte[] qualifier, long incr){ counters().add(new Counter(family, qualifier, incr)); return this; }
java
public Future<Map<Long, List<LeagueList>>> getLeagues(long... summoners) { return new ApiFuture<>(() -> handler.getLeagues(summoners)); }
java
public Future<Map<Long, List<LeagueItem>>> getLeagueEntries(long... summoners) { return new ApiFuture<>(() -> handler.getLeagueEntries(summoners)); }
java
public Future<List<LeagueList>> getLeagues(String teamId) { return new ApiFuture<>(() -> handler.getLeagues(teamId)); }
java
public Future<Map<String, List<LeagueList>>> getLeagues(String... teamIds) { return new ApiFuture<>(() -> handler.getLeagues(teamIds)); }
java
public Future<List<LeagueItem>> getLeagueEntries(String teamId) { return new ApiFuture<>(() -> handler.getLeagueEntries(teamId)); }
java
public Future<Map<String, List<LeagueItem>>> getLeagueEntries(String... teamIds) { return new ApiFuture<>(() -> handler.getLeagueEntries(teamIds)); }
java
public Future<MatchDetail> getMatch(long matchId, boolean includeTimeline) { return new ApiFuture<>(() -> handler.getMatch(matchId, includeTimeline)); }
java
public Future<List<MatchSummary>> getMatchHistory(long playerId, String[] championIds, QueueType... queueTypes) { return new ApiFuture<>(() -> handler.getMatchHistory(playerId, championIds, queueTypes)); }
java
public Future<RankedStats> getRankedStats(long summoner, Season season) { return new ApiFuture<>(() -> handler.getRankedStats(summoner, season)); }
java
public Future<List<PlayerStats>> getStatsSummary(long summoner, Season season) { return new ApiFuture<>(() -> handler.getStatsSummary(summoner, season)); }
java
public Future<Map<String, Summoner>> getSummoners(String... names) { return new ApiFuture<>(() -> handler.getSummoners(names)); }
java
public Future<Map<Integer, Summoner>> getSummoners(Integer... ids) { return new ApiFuture<>(() -> handler.getSummoners(ids)); }
java
public Future<Map<Integer, Set<MasteryPage>>> getMasteryPagesMultipleUsers(Integer... ids) { return new ApiFuture<>(() -> handler.getMasteryPagesMultipleUsers(ids)); }
java
public Future<Map<Integer, String>> getSummonerNames(Integer... ids) { return new ApiFuture<>(() -> handler.getSummonerNames(ids)); }
java
public Future<Map<Integer, Set<RunePage>>> getRunePagesMultipleUsers(int... ids) { return new ApiFuture<>(() -> handler.getRunePagesMultipleUsers(ids)); }
java
public Future<Map<Long, List<RankedTeam>>> getTeams(long... ids) { return new ApiFuture<>(() -> handler.getTeamsBySummoners(ids)); }
java
public Future<Map<String, RankedTeam>> getTeams(String... teamIds) { return new ApiFuture<>(() -> handler.getTeams(teamIds)); }
java
public Future<List<Long>> getSummonerIds(String... names) { return new ApiFuture<>(() -> handler.getSummonerIds(names)); }
java
public static ThrottledApiHandler developmentDefault(Shard shard, String token) { return new ThrottledApiHandler(shard, token, new Limit(10, 10, TimeUnit.SECONDS), new Limit(500, 10, TimeUnit.MINUTES)); }
java
public void updateRecord(final ORecordInternal<?> record) { if (isEnabled() && record.getIdentity().getClusterId() != excludedCluster && record.getIdentity().isValid()) { underlying.lock(record.getIdentity()); try { if (underlying.get(record.getIdentity()) != record) underlying.put(record); } finally { underlying.unlock(record.getIdentity()); } } secondary.updateRecord(record); }
java
public ORecordInternal<?> findRecord(final ORID rid) { if (!isEnabled()) // DELEGATE TO THE 2nd LEVEL CACHE return null; // secondary.retrieveRecord(rid); ORecordInternal<?> record; underlying.lock(rid); try { record = underlying.get(rid); if (record == null) { // DELEGATE TO THE 2nd LEVEL CACHE record = secondary.retrieveRecord(rid); if (record != null) // STORE IT LOCALLY underlying.put(record); } } finally { underlying.unlock(rid); } OProfiler.getInstance().updateCounter(record != null ? CACHE_HIT : CACHE_MISS, 1L); return record; }
java
@SuppressWarnings("rawtypes") public Object execute(final Map<Object, Object> iArgs) { if (indexName == null) throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet"); final ODatabaseRecord database = getDatabase(); final OIndex<?> idx; if (fields == null || fields.length == 0) { if (keyTypes != null) idx = database.getMetadata().getIndexManager() .createIndex(indexName, indexType.toString(), new OSimpleKeyIndexDefinition(keyTypes), null, null); else if (serializerKeyId != 0) { idx = database.getMetadata().getIndexManager() .createIndex(indexName, indexType.toString(), new ORuntimeKeyIndexDefinition(serializerKeyId), null, null); } else idx = database.getMetadata().getIndexManager().createIndex(indexName, indexType.toString(), null, null, null); } else { if (keyTypes == null || keyTypes.length == 0) { idx = oClass.createIndex(indexName, indexType, fields); } else { final OIndexDefinition idxDef = OIndexDefinitionFactory.createIndexDefinition(oClass, Arrays.asList(fields), Arrays.asList(keyTypes)); idx = database.getMetadata().getIndexManager() .createIndex(indexName, indexType.name(), idxDef, oClass.getPolymorphicClusterIds(), null); } } if (idx != null) return idx.getSize(); return null; }
java
public Team createTeam(String name, String tag) { return client.sendRpcAndWait(SERVICE, "createTeam", name, tag); }
java
public Team invitePlayer(long summonerId, TeamId teamId) { return client.sendRpcAndWait(SERVICE, "invitePlayer", summonerId, teamId); }
java
public Team kickPlayer(long summonerId, TeamId teamId) { return client.sendRpcAndWait(SERVICE, "kickPlayer", summonerId, teamId); }
java
static AnalysisResult analyse( Class<?> klass, Constructor<?> constructor) throws IOException { Class<?>[] parameterTypes = constructor.getParameterTypes(); InputStream in = klass.getResourceAsStream("/" + klass.getName().replace('.', '/') + ".class"); if (in == null) { throw new IllegalArgumentException(format("can not find bytecode for %s", klass)); } return analyse(in, klass.getName().replace('.', '/'), klass.getSuperclass().getName().replace('.', '/'), parameterTypes); }
java
@Override public String marshal(ZonedDateTime zonedDateTime) { if (null == zonedDateTime) { return null; } return zonedDateTime.withZoneSameInstant(ZoneOffset.UTC).format(formatter); }
java
public static boolean isValid(String sentence) { // Compare the characters after the asterisk to the calculation try { return sentence.substring(sentence.lastIndexOf("*") + 1) .equalsIgnoreCase(getChecksum(sentence)); } catch (AisParseException e) { return false; } }
java
private static Properties getEnvironmentFile(File configFile) { Properties mergedProperties = new Properties(); InputStream inputStream; try { inputStream = new FileInputStream(configFile); } catch (FileNotFoundException e) { // File does not exist. That's all right. return mergedProperties; } try { mergedProperties.load(inputStream); inputStream.close(); return mergedProperties; } catch (IOException e) { throw new RuntimeException(e); } }
java
private static OIndexSearchResult createIndexedProperty(final OSQLFilterCondition iCondition, final Object iItem) { if (iItem == null || !(iItem instanceof OSQLFilterItemField)) return null; if (iCondition.getLeft() instanceof OSQLFilterItemField && iCondition.getRight() instanceof OSQLFilterItemField) return null; final OSQLFilterItemField item = (OSQLFilterItemField) iItem; if (item.hasChainOperators() && !item.isFieldChain()) return null; final Object origValue = iCondition.getLeft() == iItem ? iCondition.getRight() : iCondition.getLeft(); if (iCondition.getOperator() instanceof OQueryOperatorBetween || iCondition.getOperator() instanceof OQueryOperatorIn) { return new OIndexSearchResult(iCondition.getOperator(), item.getFieldChain(), origValue); } final Object value = OSQLHelper.getValue(origValue); if (value == null) return null; return new OIndexSearchResult(iCondition.getOperator(), item.getFieldChain(), value); }
java
void addResult(String valueData, String detailData) { if (value) { if (valueData == null) throw new IllegalArgumentException(CLASS + ": valueData may not be null"); values.add(valueData); if (detail) { if (detailData == null) throw new IllegalArgumentException(CLASS + ": detailData may not be null"); details.add(detailData); } } counter++; }
java
public String marshal(Object jaxbObject) { // Precondition, check that the jaxbContext is set! if (jaxbContext == null) { logger.error("Trying to marshal with a null jaxbContext, returns null. Check your configuration, e.g. jaxb-transformers!"); return null; } try { StringWriter writer = new StringWriter(); Marshaller marshaller = jaxbContext.createMarshaller(); if (marshallProps != null) { for (Entry<String, Object> entry : marshallProps.entrySet()) { marshaller.setProperty(entry.getKey(), entry.getValue()); } } marshaller.marshal(jaxbObject, writer); String xml = writer.toString(); if (logger.isDebugEnabled()) logger.debug("marshalled jaxb object of type {}, returns xml: {}", jaxbObject.getClass().getSimpleName(), xml); return xml; } catch (JAXBException e) { throw new RuntimeException(e); } }
java
@VisibleForTesting static boolean isPghp(String line) { if (line == null) return false; else // return Pattern.matches("^(\\\\.*\\\\)?\\$PGHP.*$", line); return pghpPattern.matcher(line).matches(); }
java
public static boolean isExactEarthTimestamp(String line) { try { new NmeaMessageExactEarthTimestamp(line); return true; } catch (AisParseException e) { return false; } catch (NmeaMessageParseException e) { return false; } }
java
private static long getTime(int year, int month, int day, int hour, int minute, int second, int millisecond) { Calendar cal = Calendar.getInstance(Util.TIME_ZONE_UTC); cal.set(year, month - 1, day, hour, minute, second); cal.set(Calendar.MILLISECOND, millisecond); return cal.getTimeInMillis(); }
java
private String getFolderAndCreateIfMissing(String inFolder) { String folder = outputFolder; if (inFolder != null) { folder += "/" + inFolder; } mkdirs(folder); return folder; }
java
public static EventBus get() { if (EventBus.instance == null) { EventBus.instance = new EventBus(); } return EventBus.instance; }
java
@Override public ORecordIteratorClusters<REC> last() { currentClusterIdx = clusterIds.length - 1; current.clusterPosition = liveUpdated ? database.countClusterElements(clusterIds[currentClusterIdx]) : lastClusterPosition + 1; return this; }
java
private static OIdentifiable linkToStream(final StringBuilder buffer, final ORecordSchemaAware<?> iParentRecord, Object iLinked) { if (iLinked == null) // NULL REFERENCE return null; OIdentifiable resultRid = null; ORID rid; final ODatabaseRecord database = ODatabaseRecordThreadLocal.INSTANCE.get(); if (iLinked instanceof ORID) { // JUST THE REFERENCE rid = (ORID) iLinked; if (rid.isValid() && rid.isNew()) { // SAVE AT THE FLY AND STORE THE NEW RID final ORecord<?> record = rid.getRecord(); if (database.getTransaction().isActive()) { // USE THE DEFAULT CLUSTER database.save((ORecordInternal<?>) record); } else database.save((ORecordInternal<?>) record); if (record != null) rid = record.getIdentity(); resultRid = rid; } } else { if (iLinked instanceof String) iLinked = new ORecordId((String) iLinked); else if (!(iLinked instanceof ORecordInternal<?>)) { // NOT RECORD: TRY TO EXTRACT THE DOCUMENT IF ANY final String boundDocumentField = OObjectSerializerHelperManager.getInstance().getDocumentBoundField(iLinked.getClass()); if (boundDocumentField != null) iLinked = OObjectSerializerHelperManager.getInstance().getFieldValue(iLinked, boundDocumentField); } if (!(iLinked instanceof OIdentifiable)) throw new IllegalArgumentException("Invalid object received. Expected a OIdentifiable but received type=" + iLinked.getClass().getName() + " and value=" + iLinked); // RECORD ORecordInternal<?> iLinkedRecord = ((OIdentifiable) iLinked).getRecord(); rid = iLinkedRecord.getIdentity(); if (rid.isNew() || iLinkedRecord.isDirty()) { if (iLinkedRecord instanceof ODocument) { final OClass schemaClass = ((ODocument) iLinkedRecord).getSchemaClass(); database.save(iLinkedRecord, schemaClass != null ? database.getClusterNameById(schemaClass.getDefaultClusterId()) : null); } else // STORE THE TRAVERSED OBJECT TO KNOW THE RECORD ID. CALL THIS VERSION TO AVOID CLEAR OF STACK IN THREAD-LOCAL database.save(iLinkedRecord); final ODatabaseComplex<?> dbOwner = database.getDatabaseOwner(); dbOwner.registerUserObjectAfterLinkSave(iLinkedRecord); resultRid = iLinkedRecord; } if (iParentRecord != null && database instanceof ODatabaseRecord) { final ODatabaseRecord db = database; if (!db.isRetainRecords()) // REPLACE CURRENT RECORD WITH ITS ID: THIS SAVES A LOT OF MEMORY resultRid = iLinkedRecord.getIdentity(); } } if (rid.isValid()) rid.toString(buffer); return resultRid; }
java
@Override public ODocument toStream() { acquireExclusiveLock(); try { document.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING); try { final ORecordTrackedSet idxs = new ORecordTrackedSet(document); for (final OIndexInternal<?> i : indexes.values()) { idxs.add(i.updateConfiguration()); } document.field(CONFIG_INDEXES, idxs, OType.EMBEDDEDSET); } finally { document.setInternalStatus(ORecordElement.STATUS.LOADED); } document.setDirty(); return document; } finally { releaseExclusiveLock(); } }
java
private void releaseCallbacks(Exception ex) { synchronized (callbacks) { for (Map.Entry<Integer, InvokeCallback> cb: callbacks.entrySet()) { cb.getValue().release(ex); } } }
java
synchronized void line(String line, long arrivalTime) { if (count.incrementAndGet() % logCountFrequency == 0) log.info("count=" + count.get() + ",buffer size=" + lines.size()); NmeaMessage nmea; try { nmea = NmeaUtil.parseNmea(line); } catch (NmeaMessageParseException e) { listener.invalidNmea(line, arrivalTime, e.getMessage()); return; } // if is multi line message then don't report to listener till last // message in sequence has been received. if (!nmea.isSingleSentence()) { Optional<List<NmeaMessage>> messages = nmeaBuffer.add(nmea); if (messages.isPresent()) { Optional<NmeaMessage> joined = AisNmeaBuffer .concatenateMessages(messages.get()); if (joined.isPresent()) { if (joined.get().getUnixTimeMillis() != null) listener.message(joined.get().toLine(), joined.get() .getUnixTimeMillis()); else listener.message(joined.get().toLine(), arrivalTime); } // TODO else report error, might need to change signature of // listener to handle problem with multi-line message } return; } if (nmea.getUnixTimeMillis() != null) { listener.message(line, nmea.getUnixTimeMillis()); return; } if (!matchWithTimestampLine) { listener.message(line, arrivalTime); return; } if (!NmeaUtil.isValid(line)) return; addLine(line, arrivalTime); log.debug("buffer lines=" + lines.size()); Integer earliestTimestampLineIndex = getEarliestTimestampLineIndex(lines); Set<Integer> removeThese; if (earliestTimestampLineIndex != null) { removeThese = matchWithClosestAisMessageIfBufferLargeEnough( arrivalTime, earliestTimestampLineIndex); } else removeThese = findExpiredIndexesBeforeIndex(lastIndex()); TreeSet<Integer> orderedIndexes = Sets.newTreeSet(removeThese); for (int index : orderedIndexes.descendingSet()) { removeLineWithIndex(index); } }
java
private Set<Integer> findExpiredIndexesBeforeIndex(int index) { long indexTime = getLineTime(index); Set<Integer> removeThese = Sets.newHashSet(); for (int i = index - 1; i >= 0; i--) { if (indexTime - getLineTime(i) > MAXIMUM_ARRIVAL_TIME_DIFFERENCE_MS) { listener.timestampNotFound(getLine(i), getLineTime(i)); removeThese.add(i); } } return removeThese; }
java
private Set<Integer> matchWithClosestAisMessageIfBufferLargeEnough( long arrivalTime, Integer earliestTimestampLineIndex) { String timestampLine = getLine(earliestTimestampLineIndex); long time = getLineTime(earliestTimestampLineIndex); log.debug("ts=" + timestampLine + ",time=" + time); Set<Integer> removeThese; if (arrivalTime - time > MAXIMUM_ARRIVAL_TIME_DIFFERENCE_MS) { removeThese = matchWithClosestAisMessageAndFindIndexesToRemove( earliestTimestampLineIndex, timestampLine, time); } else removeThese = findExpiredIndexesBeforeIndex(earliestTimestampLineIndex); return removeThese; }
java
private Set<Integer> reportMatchAndFindIndexesToRemove( Integer earliestTimestampLineIndex, NmeaMessageExactEarthTimestamp timestamp, Integer lowestTimeDiffIndex) { String msg = getLine(lowestTimeDiffIndex); log.debug("found matching msg=" + msg); listener.message(msg, timestamp.getTime()); int maxIndex = Math .max(lowestTimeDiffIndex, earliestTimestampLineIndex); int minIndex = Math .min(lowestTimeDiffIndex, earliestTimestampLineIndex); // now remove from lists must remove bigger index first, // otherwise indexes will change return Sets.newHashSet(minIndex, maxIndex); }
java
public static MimeMessage createMimeMessage(Session session, String from, String[] to, String subject, String content, DataSource[] attachments) { logger.debug("Creates a mime message with {} attachments", (attachments == null) ? 0 : attachments.length); try { MimeMessage message = new MimeMessage(session); if (from != null) { message.setSender(new InternetAddress(from)); } if (subject != null) { message.setSubject(subject, "UTF-8"); } if (to != null) { for (String toAdr : to) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAdr)); } } if (attachments == null || attachments.length == 0) { // Setup a plain text message message.setContent(content, "text/plain; charset=UTF-8"); } else { // Setup a multipart message Multipart multipart = new MimeMultipart(); message.setContent(multipart); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(content, "text/plain; charset=UTF-8"); multipart.addBodyPart(messageBodyPart); // Add attachments, if any if (attachments != null) { for (DataSource attachment : attachments) { BodyPart attatchmentBodyPart = new MimeBodyPart(); attatchmentBodyPart.setDataHandler(new DataHandler(attachment)); attatchmentBodyPart.setFileName(attachment.getName()); multipart.addBodyPart(attatchmentBodyPart); } } } return message; } catch (AddressException e) { throw new RuntimeException(e); } catch (MessagingException e) { throw new RuntimeException(e); } }
java
public static void disableTlsServerCertificateCheck(Client client) { if (!(client.getConduit() instanceof HTTPConduit)) { log.warn("Conduit not of type HTTPConduit (" + client.getConduit().getClass().getName() + ") , skip disabling server certification validation."); return; } log.warn("Disables server certification validation for: " + client.getEndpoint().getEndpointInfo().getAddress()); HTTPConduit httpConduit = (HTTPConduit) client.getConduit(); TLSClientParameters tlsParams = new TLSClientParameters(); TrustManager[] trustAllCerts = new TrustManager[] { new FakeTrustManager() }; tlsParams.setTrustManagers(trustAllCerts); tlsParams.setDisableCNCheck(true); httpConduit.setTlsClientParameters(tlsParams); }
java
public boolean isRuleDefined(final String iResource) { for (ORole r : roles) if (r.hasRule(iResource)) return true; return false; }
java
public Object execute(final Map<Object, Object> iArgs) { if (attribute == null) throw new OCommandExecutionException("Cannot execute the command because it has not yet been parsed"); final OClassImpl sourceClass = (OClassImpl) getDatabase().getMetadata().getSchema().getClass(className); if (sourceClass == null) throw new OCommandExecutionException("Source class '" + className + "' not found"); final OPropertyImpl prop = (OPropertyImpl) sourceClass.getProperty(fieldName); if (prop == null) throw new OCommandExecutionException("Property '" + className + "." + fieldName + "' not exists"); prop.setInternalAndSave(attribute, value); return null; }
java
public void flush() { lock.writeLock().lock(); try { OMMapBufferEntry entry; for (Iterator<OMMapBufferEntry> it = bufferPoolLRU.iterator(); it.hasNext();) { entry = it.next(); if (entry.file != null && entry.file.isClosed()) { if (removeEntry(entry)) it.remove(); } } } finally { lock.writeLock().unlock(); } }
java
public void flushFile(final OFileMMap iFile) { lock.readLock().lock(); try { final List<OMMapBufferEntry> entries = bufferPoolPerFile.get(iFile); if (entries != null) for (OMMapBufferEntry entry : entries) entry.flush(); } finally { lock.readLock().unlock(); } }
java
private static int searchEntry(final List<OMMapBufferEntry> fileEntries, final long iBeginOffset, final int iSize) { if (fileEntries == null || fileEntries.size() == 0) return -1; int high = fileEntries.size() - 1; if (high < 0) // NOT FOUND return -1; int low = 0; int mid = -1; // BINARY SEARCH OMMapBufferEntry e; while (low <= high) { mid = (low + high) >>> 1; e = fileEntries.get(mid); if (iBeginOffset >= e.beginOffset && iBeginOffset + iSize <= e.beginOffset + e.size) { // FOUND: USE IT OProfiler.getInstance().updateCounter("OMMapManager.reusedPage", 1); e.counter++; return mid; } if (low == high) { if (iBeginOffset > e.beginOffset) // NEXT POSITION low++; // NOT FOUND return (low + 2) * -1; } if (iBeginOffset >= e.beginOffset) low = mid + 1; else high = mid; } // NOT FOUND return mid; }
java
public static Observable<Fix> from(File file, boolean backpressure, BinaryFixesFormat format) { if (backpressure) return BinaryFixesOnSubscribeWithBackp.from(file, format); else return BinaryFixesOnSubscribeFastPath.from(file, format); }
java
public void encodeAmf3(Object obj, Amf3Type marker) throws IOException { out.write(marker.ordinal()); if (marker == Amf3Type.NULL) { return; // Null marker is enough } serializeAmf3(obj, marker); }
java
@SneakyThrows(value = {InstantiationException.class, IllegalAccessException.class}) public void serializeAmf3(Object obj, Amf3Type marker) throws IOException { if (checkReferenceable(obj, marker)) { return; } Serialization context; if (amf3Serializers.containsKey(obj.getClass())) { amf3Serializers.get(obj.getClass()).serialize(obj, out); } else if ((context = Util.searchClassHierarchy(obj.getClass(), Serialization.class)) != null && !context.deserializeOnly()) { Amf3ObjectSerializer serializer = context.amf3Serializer().newInstance(); serializer.setTraitRefTable(traitRefTable); serializer.setTraitDefCache(traitDefCache); serializer.setWriter(this); serializer.serialize(obj, out); } else if (obj.getClass().isArray()) { // Arrays require special handling serializeArrayAmf3(obj); } else if (obj instanceof Enum) { // Enums are written by name serializeAmf3(((Enum) obj).name()); } else { Amf3ObjectSerializer serializer = new Amf3ObjectSerializer(); serializer.setTraitRefTable(traitRefTable); serializer.setTraitDefCache(traitDefCache); serializer.setWriter(this); serializer.serialize(obj, out); } out.flush(); }
java
@Override public Object evaluateRecord(final OIdentifiable iRecord, final OSQLFilterCondition iCondition, final Object iLeft, final Object iRight, OCommandContext iContext) { return true; }
java
public Object execute(final Map<Object, Object> iArgs) { if (name == null) throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet"); getDatabase().getMetadata().getIndexManager().dropIndex(name); return null; }
java
public void close() { for (Entry<String, OResourcePool<String, CH>> pool : pools.entrySet()) { for (CH channel : pool.getValue().getResources()) { channel.close(); } } }
java
public PlayerLifetimeStats retrievePlayerStatsByAccountId(long accountId, Season season) { return client.sendRpcAndWait(SERVICE, "retrievePlayerStatsByAccountId", accountId, season); }
java
public List<ChampionStatInfo> retrieveTopPlayedChampions(long accId, GameMode mode) { return client.sendRpcAndWait(SERVICE, "retrieveTopPlayedChampions", accId, mode); }
java
public AggregatedStats getAggregatedStats(long id, GameMode gameMode, Season season) { return client.sendRpcAndWait(SERVICE, "getAggregatedStats", id, gameMode, season.numeric); }
java
public EndOfGameStats getTeamEndOfGameStats(TeamId teamId, long gameId) { return client.sendRpcAndWait(SERVICE, "getTeamEndOfGameStats", teamId, gameId); }
java