name
stringlengths
12
178
code_snippet
stringlengths
8
36.5k
score
float64
3.26
3.68
pulsar_PulsarProtobufNativeRowDecoder_decodeRow_rdh
/** * Decode ByteBuf by {@link org.apache.pulsar.client.api.schema.GenericSchema}. * * @param byteBuf * @return */ @Override public Optional<Map<DecoderColumnHandle, FieldValueProvider>> decodeRow(ByteBuf byteBuf) { DynamicMessage v0; try { GenericProtobufNativeRecord record = ((GenericProtobufNativeRecord) (genericProtobufNativeSchema.decode(byteBuf))); v0 = record.getProtobufRecord(); } catch (Exception e) { log.error(e);throw new TrinoException(GENERIC_INTERNAL_ERROR, "Decoding protobuf record failed.", e); } return Optional.of(columnDecoders.entrySet().stream().collect(toImmutableMap(Map.Entry::getKey, entry -> entry.getValue().decodeField(v0)))); }
3.26
pulsar_RocksdbMetadataStore_serialize_rdh
/** * Note: we can only add new fields, but not change or remove existing fields. */ public byte[] serialize() { byte[] result = new byte[HEADER_SIZE + data.length]; ByteBuffer buffer = ByteBuffer.wrap(result); buffer.putInt(HEADER_SIZE); buffer.putInt(FORMAT_VERSION_V1); buffer.putLong(version); buffer.putLong(owner); buffer.putLong(createdTimestamp); buffer.putLong(modifiedTimestamp); buffer.put(((byte) (ephemeral ? 1 : 0))); buffer.put(data); return result; }
3.26
pulsar_SaslRoleToken_getUserRole_rdh
/** * Returns the user name. * * @return the user name. */ public String getUserRole() { return userRole; }
3.26
pulsar_SaslRoleToken_setExpires_rdh
/** * Sets the expiration of the token. * * @param expires * expiration time of the token in milliseconds since the epoch. */ public void setExpires(long expires) { if (this != SaslRoleToken.f0) { this.expires = expires;generateToken(); } }
3.26
pulsar_SaslRoleToken_checkForIllegalArgument_rdh
/** * Check if the provided value is invalid. Throw an error if it is invalid, NOP otherwise. * * @param value * the value to check. * @param name * the parameter name to use in an error message if the value is invalid. */ private static void checkForIllegalArgument(String value, String name) { if (((value == null) || (value.length() == 0)) || value.contains(f1)) { throw new IllegalArgumentException(name + ILLEGAL_ARG_MSG); } }
3.26
pulsar_SaslRoleToken_generateToken_rdh
/** * Generates the token. */ private void generateToken() { StringBuilder sb = new StringBuilder(); sb.append(USER_ROLE).append("=").append(getUserRole()).append(f1); sb.append(SESSION).append("=").append(getSession()).append(f1); sb.append(EXPIRES).append("=").append(getExpires()); token = sb.toString(); }
3.26
pulsar_SaslRoleToken_isExpired_rdh
/** * Returns if the token has expired. * * @return if the token has expired. */ public boolean isExpired() { return (getExpires() != (-1)) && (System.currentTimeMillis() > getExpires()); }
3.26
pulsar_SaslRoleToken_split_rdh
/** * Splits the string representation of a token into attributes pairs. * * @param tokenStr * string representation of a token. * @return a map with the attribute pairs of the token. * @throws AuthenticationException * thrown if the string representation of the token could not be broken into * attribute pairs. */ private static Map<String, String> split(String tokenStr) throws AuthenticationException { Map<String, String> map = new HashMap<String, String>(); StringTokenizer st = new StringTokenizer(tokenStr, f1); while (st.hasMoreTokens()) { String part = st.nextToken();int separator = part.indexOf('='); if (separator == (-1)) { throw new AuthenticationException("Invalid authentication token"); }String key = part.substring(0, separator); String value = part.substring(separator + 1); map.put(key, value); } return map; }
3.26
pulsar_BrokerDiscoveryProvider_getAvailableBrokers_rdh
/** * Access the list of available brokers. * Used by Protocol Handlers * * @return the list of available brokers * @throws PulsarServerException */ public List<? extends ServiceLookupData> getAvailableBrokers() throws PulsarServerException { return metadataStoreCacheLoader.getAvailableBrokers(); }
3.26
pulsar_BrokerDiscoveryProvider_nextBroker_rdh
/** * Find next broker {@link LoadManagerReport} in round-robin fashion. * * @return * @throws PulsarServerException */ LoadManagerReport nextBroker() throws PulsarServerException { List<LoadManagerReport> availableBrokers = metadataStoreCacheLoader.getAvailableBrokers(); if (availableBrokers.isEmpty()) { throw new PulsarServerException("No active broker is available");} else {int brokersCount = availableBrokers.size();int nextIdx = signSafeMod(counter.getAndIncrement(), brokersCount); return availableBrokers.get(nextIdx); } }
3.26
pulsar_ConnectorUtils_getIOSourceClass_rdh
/** * Extract the Pulsar IO Source class from a connector archive. */ public static String getIOSourceClass(NarClassLoader narClassLoader) throws IOException { ConnectorDefinition conf = getConnectorDefinition(narClassLoader); if (StringUtils.isEmpty(conf.getSourceClass())) { throw new IOException(String.format("The '%s' connector does not provide a source implementation", conf.getName())); } try { // Try to load source class and check it implements Source interface Class sourceClass = narClassLoader.loadClass(conf.getSourceClass()); if (!(Source.class.isAssignableFrom(sourceClass) || BatchSource.class.isAssignableFrom(sourceClass))) { throw new IOException(String.format("Class %s does not implement interface %s or %s", conf.getSourceClass(), Source.class.getName(), BatchSource.class.getName()));} } catch (Throwable t) { Exceptions.rethrowIOException(t); } return conf.getSourceClass(); }
3.26
pulsar_ConnectorUtils_getIOSinkClass_rdh
/** * Extract the Pulsar IO Sink class from a connector archive. */ public static String getIOSinkClass(NarClassLoader narClassLoader) throws IOException { ConnectorDefinition conf = getConnectorDefinition(narClassLoader); if (StringUtils.isEmpty(conf.getSinkClass())) { throw new IOException(String.format("The '%s' connector does not provide a sink implementation", conf.getName())); } try { // Try to load sink class and check it implements Sink interface Class sinkClass = narClassLoader.loadClass(conf.getSinkClass()); if (!Sink.class.isAssignableFrom(sinkClass)) { throw new IOException((("Class " + conf.getSinkClass()) + " does not implement interface ") + Sink.class.getName()); } } catch (Throwable t) { Exceptions.rethrowIOException(t); } return conf.getSinkClass(); }
3.26
pulsar_TransactionUtil_canTransitionTo_rdh
/** * Check if the a status can be transaction to a new status. * * @param newStatus * the new status * @return true if the current status can be transitioning to. */ public static boolean canTransitionTo(TxnStatus currentStatus, TxnStatus newStatus) { switch (currentStatus) { case OPEN : return (newStatus != COMMITTED) && (newStatus != ABORTED); case COMMITTING : return (newStatus == COMMITTING) || (newStatus == COMMITTED); case COMMITTED : return newStatus == COMMITTED; case ABORTING : return (newStatus == ABORTING) || (newStatus == ABORTED); case ABORTED : return newStatus == ABORTED; default : throw new IllegalArgumentException("Unknown txn status : " + newStatus); } }
3.26
pulsar_WindowManager_scanEvents_rdh
/** * Scan events in the queue, using the expiration policy to check * if the event should be evicted or not. * * @param fullScan * if set, will scan the entire queue; if not set, will stop * as soon as an event not satisfying the expiration policy is found * @return the list of events to be processed as a part of the current window */ private List<Event<T>> scanEvents(boolean fullScan) { log.debug("Scan events, eviction policy {}", evictionPolicy); List<Event<T>> eventsToExpire = new ArrayList<>(); List<Event<T>> eventsToProcess = new ArrayList<>(); lock.lock(); try { Iterator<Event<T>> it = queue.iterator(); while (it.hasNext()) { Event<T> windowEvent = it.next(); EvictionPolicy.Action action = evictionPolicy.evict(windowEvent); if (action == EXPIRE) { eventsToExpire.add(windowEvent); it.remove(); } else if ((!fullScan) || (action == STOP)) { break; } else if (action == PROCESS) { eventsToProcess.add(windowEvent); } } expiredEvents.addAll(eventsToExpire); } finally { lock.unlock(); } eventsSinceLastExpiry.set(0); if (log.isDebugEnabled()) { log.debug("[{}] events expired from window.", eventsToExpire.size()); } if (!eventsToExpire.isEmpty()) {log.debug("invoking windowLifecycleListener.onExpiry"); windowLifecycleListener.onExpiry(eventsToExpire); } return eventsToProcess; }
3.26
pulsar_WindowManager_add_rdh
/** * Tracks a window event. * * @param windowEvent * the window event to track */ public void add(Event<T> windowEvent) { // watermark events are not added to the queue. if (windowEvent.isWatermark()) { if (log.isDebugEnabled()) { log.debug("Got watermark event with ts {}", windowEvent.getTimestamp()); } } else { queue.add(windowEvent); } m0(windowEvent);compactWindow(); }
3.26
pulsar_WindowManager_getSlidingCountTimestamps_rdh
/** * Scans the event queue and returns the list of event ts * falling between startTs (exclusive) and endTs (inclusive) * at each sliding interval counts. * * @param startTs * the start timestamp (exclusive) * @param endTs * the end timestamp (inclusive) * @param slidingCount * the sliding interval count * @return the list of event ts */ public List<Long> getSlidingCountTimestamps(long startTs, long endTs, int slidingCount) { List<Long> timestamps = new ArrayList<>(); if (endTs > startTs) { int count = 0; long ts = Long.MIN_VALUE; for (Event<T> event : queue) { if ((event.getTimestamp() > startTs) && (event.getTimestamp() <= endTs)) { ts = Math.max(ts, event.getTimestamp()); if (((++count) % slidingCount) == 0) { timestamps.add(ts); } } } } return timestamps; }
3.26
pulsar_WindowManager_compactWindow_rdh
/** * expires events that fall out of the window every * EXPIRE_EVENTS_THRESHOLD so that the window does not grow * too big. */ protected void compactWindow() {if (eventsSinceLastExpiry.incrementAndGet() >= EXPIRE_EVENTS_THRESHOLD) { scanEvents(false); } }
3.26
pulsar_WindowManager_m1_rdh
/** * Scans the event queue and returns number of events having * timestamp less than or equal to the reference time. * * @param referenceTime * the reference timestamp in millis * @return the count of events with timestamp less than or equal to referenceTime */ public int m1(long referenceTime) { int count = 0; for (Event<T> event : queue) { if (event.getTimestamp() <= referenceTime) { ++count; } } return count; }
3.26
pulsar_WindowManager_getEarliestEventTs_rdh
/** * Scans the event queue and returns the next earliest event ts * between the startTs and endTs. * * @param startTs * the start ts (exclusive) * @param endTs * the end ts (inclusive) * @return the earliest event ts between startTs and endTs */ public long getEarliestEventTs(long startTs, long endTs) { long minTs = Long.MAX_VALUE; for (Event<T> event : queue) { if ((event.getTimestamp() > startTs) && (event.getTimestamp() <= endTs)) {minTs = Math.min(minTs, event.getTimestamp()); } } return minTs; }
3.26
pulsar_WindowManager_onTrigger_rdh
/** * The callback invoked by the trigger policy. */ @Override public boolean onTrigger() { List<Event<T>> windowEvents = null; List<Event<T>> expired = null; lock.lock(); try { /* scan the entire window to handle out of order events in the case of time based windows. */ windowEvents = scanEvents(true); expired = new ArrayList<>(expiredEvents); expiredEvents.clear(); } finally { lock.unlock(); } List<Event<T>> events = new ArrayList<>(); List<Event<T>> newEvents = new ArrayList<>(); for (Event<T> event : windowEvents) { events.add(event);if (!prevWindowEvents.contains(event)) { newEvents.add(event); } } prevWindowEvents.clear(); if (!events.isEmpty()) { prevWindowEvents.addAll(windowEvents); if (log.isDebugEnabled()) { log.debug("invoking windowLifecycleListener onActivation, [{}] events in window.", events.size()); } windowLifecycleListener.onActivation(events, newEvents, expired, evictionPolicy.getContext().getReferenceTime()); } else { log.debug("No events in the window, skipping onActivation"); } triggerPolicy.reset(); return !events.isEmpty(); }
3.26
pulsar_LeastLongTermMessageRate_selectBroker_rdh
/** * Find a suitable broker to assign the given bundle to. * * @param candidates * The candidates for which the bundle may be assigned. * @param bundleToAssign * The data for the bundle to assign. * @param loadData * The load data from the leader broker. * @param conf * The service configuration. * @return The name of the selected broker as it appears on ZooKeeper. */ @Override public Optional<String> selectBroker(final Set<String> candidates, final BundleData bundleToAssign, final LoadData loadData, final ServiceConfiguration conf) { bestBrokers.clear(); double minScore = Double.POSITIVE_INFINITY; // Maintain of list of all the best scoring brokers and then randomly // select one of them at the end. for (String broker : candidates) { final BrokerData brokerData = loadData.getBrokerData().get(broker); final double score = getScore(brokerData, conf); if (score == Double.POSITIVE_INFINITY) { final LocalBrokerData localData = brokerData.getLocalData(); log.warn("Broker {} is overloaded: CPU: {}%, MEMORY: {}%, DIRECT MEMORY: {}%, BANDWIDTH IN: {}%, " + "BANDWIDTH OUT: {}%", broker, localData.getCpu().percentUsage(), localData.getMemory().percentUsage(), localData.getDirectMemory().percentUsage(), localData.getBandwidthIn().percentUsage(), localData.getBandwidthOut().percentUsage()); }if (score < minScore) { // Clear best brokers since this score beats the other brokers. bestBrokers.clear(); bestBrokers.add(broker);minScore = score; } else if (score == minScore) { // Add this broker to best brokers since it ties with the best score. bestBrokers.add(broker); } } if (bestBrokers.isEmpty()) { // All brokers are overloaded. // Assign randomly in this case. bestBrokers.addAll(candidates); } if (bestBrokers.isEmpty()) { // If still, it means there are no available brokers at this point return Optional.empty(); } return Optional.of(bestBrokers.get(ThreadLocalRandom.current().nextInt(bestBrokers.size()))); }
3.26
pulsar_LeastLongTermMessageRate_getScore_rdh
// Form a score for a broker using its preallocated bundle data and time average data. // This is done by summing all preallocated long-term message rates and adding them to the broker's overall // long-term message rate, which is itself the sum of the long-term message rate of every allocated bundle. // Any broker at (or above) the overload threshold will have a score of POSITIVE_INFINITY. private static double getScore(final BrokerData brokerData, final ServiceConfiguration conf) { final double overloadThreshold = conf.getLoadBalancerBrokerOverloadedThresholdPercentage() / 100.0; final double maxUsage = brokerData.getLocalData().getMaxResourceUsage(); if (maxUsage > overloadThreshold) { log.warn("Broker {} is overloaded: max usage={}", brokerData.getLocalData().getWebServiceUrl(), maxUsage); return Double.POSITIVE_INFINITY; } double totalMessageRate = 0; for (BundleData bundleData : brokerData.getPreallocatedBundleData().values()) { final TimeAverageMessageData longTermData = bundleData.getLongTermData(); totalMessageRate += longTermData.getMsgRateIn() + longTermData.getMsgRateOut(); } // calculate estimated score final TimeAverageBrokerData timeAverageData = brokerData.getTimeAverageData(); final double timeAverageLongTermMessageRate = timeAverageData.getLongTermMsgRateIn() + timeAverageData.getLongTermMsgRateOut(); final double totalMessageRateEstimate = totalMessageRate + timeAverageLongTermMessageRate; if (log.isDebugEnabled()) { log.debug("Broker {} has long term message rate {}", brokerData.getLocalData().getWebServiceUrl(), totalMessageRateEstimate);} return totalMessageRateEstimate;}
3.26
pulsar_EntryImpl_getDataAndRelease_rdh
// Only for test @Override public byte[] getDataAndRelease() { byte[] array = getData(); release(); return array; }
3.26
pulsar_AuthenticationDataSource_hasDataFromHttp_rdh
/* HTTP */ /** * Check if data from HTTP are available. * * @return true if this authentication data contain data from HTTP */ default boolean hasDataFromHttp() { return false; }
3.26
pulsar_AuthenticationDataSource_authenticate_rdh
/** * Evaluate and challenge the data that passed in, and return processed data back. * It is used for mutual authentication like SASL. * NOTE: this method is not called by the Pulsar authentication framework. * * @deprecated use {@link AuthenticationProvider} or {@link AuthenticationState}. */@Deprecated default AuthData authenticate(AuthData data) throws AuthenticationException { throw new AuthenticationException("Not supported"); }
3.26
pulsar_AuthenticationDataSource_hasDataFromCommand_rdh
/* Command */ /** * Check if data from Pulsar protocol are available. * * @return true if this authentication data contain data from Pulsar protocol */ default boolean hasDataFromCommand() { return false; }
3.26
pulsar_AuthenticationDataSource_setSubscription_rdh
/** * Subscription name can be necessary for consumption. */ default void setSubscription(String subscription) { }
3.26
pulsar_SecretsProviderConfigurator_doAdmissionChecks_rdh
/** * Do config checks to see whether the secrets provided are conforming. */ default void doAdmissionChecks(AppsV1Api appsV1Api, CoreV1Api coreV1Api, String jobNamespace, String jobName, Function.FunctionDetails functionDetails) { }
3.26
pulsar_PartialRoundRobinMessageRouterImpl_choosePartition_rdh
/** * Choose a partition based on the topic metadata. * Key hash routing isn't supported. * * @param msg * message * @param metadata * topic metadata * @return the partition to route the message. */ public int choosePartition(Message<?> msg, TopicMetadata metadata) { final List<Integer> newPartialList = new ArrayList<>(m0(metadata)); return newPartialList.get(signSafeMod(PARTITION_INDEX_UPDATER.getAndIncrement(this), newPartialList.size())); }
3.26
pulsar_TripleLongPriorityQueue_peekN3_rdh
/** * Read the 3rd long item in the top tuple in the priority queue. * * <p>The tuple will not be extracted */ public long peekN3() { checkArgument(tuplesCount != 0); return array.readLong(2); }
3.26
pulsar_TripleLongPriorityQueue_peekN1_rdh
/** * Read the 1st long item in the top tuple in the priority queue. * * <p>The tuple will not be extracted */ public long peekN1() { checkArgument(tuplesCount != 0); return array.readLong(0); }
3.26
pulsar_TripleLongPriorityQueue_clear_rdh
/** * Clear all items. */ public void clear() { this.tuplesCount = 0; shrinkCapacity(); }
3.26
pulsar_TripleLongPriorityQueue_pop_rdh
/** * Removes the first item from the queue. */ public void pop() { checkArgument(tuplesCount != 0); swap(0, tuplesCount - 1); tuplesCount--; siftDown(0); shrinkCapacity();}
3.26
pulsar_GeoPersistentReplicator_getProducerName_rdh
/** * * @return Producer name format : replicatorPrefix.localCluster-->remoteCluster */ @Override protected String getProducerName() { return (getReplicatorName(replicatorPrefix, localCluster) + REPL_PRODUCER_NAME_DELIMITER) + remoteCluster; }
3.26
pulsar_TopicCountEquallyDivideBundleSplitAlgorithm_getSplitBoundary_rdh
/** * This algorithm divides the bundle into two parts with the same topics count. */public class TopicCountEquallyDivideBundleSplitAlgorithm implements NamespaceBundleSplitAlgorithm { @Override public CompletableFuture<List<Long>> getSplitBoundary(BundleSplitOption bundleSplitOption) { NamespaceService service = bundleSplitOption.getService(); NamespaceBundle bundle = bundleSplitOption.getBundle(); return service.getOwnedTopicListForNamespaceBundle(bundle).thenCompose(topics -> { if ((topics == null) || (topics.size() <= 1)) { return CompletableFuture.completedFuture(null); } List<Long> topicNameHashList = new ArrayList<>(topics.size()); for (String topic : topics) { topicNameHashList.add(bundle.getNamespaceBundleFactory().getLongHashCode(topic)); } Collections.sort(topicNameHashList); long splitStart = topicNameHashList.get(Math.max((topicNameHashList.size() / 2) - 1, 0)); long splitEnd = topicNameHashList.get(topicNameHashList.size() / 2); long splitMiddle = splitStart + ((splitEnd - splitStart) / 2); return CompletableFuture.completedFuture(Collections.singletonList(splitMiddle)); }); }
3.26
pulsar_FieldParser_stringToList_rdh
/** * Converts comma separated string to List. * * @param <T> * type of list * @param val * comma separated values. * @return The converted list with type {@code <T>}. */ public static <T> List<T> stringToList(String val, Class<T> type) { if (val == null) { return null; } String[] tokens = trim(val).split(","); return Arrays.stream(tokens).map(t -> { return convert(trim(t), type); }).collect(Collectors.toList()); }
3.26
pulsar_FieldParser_stringToInteger_rdh
/** * *** --- Converters --- *** */ /** * Converts String to Integer. * * @param val * The String to be converted. * @return The converted Integer value. */ public static Integer stringToInteger(String val) { String v = trim(val); if (internal.StringUtil.isNullOrEmpty(v)) { return null; } else { return Integer.valueOf(v); } }
3.26
pulsar_FieldParser_stringToDouble_rdh
/** * Converts String to Double. * * @param val * The String to be converted. * @return The converted Double value. */ public static Double stringToDouble(String val) { String v = trim(val); if (internal.StringUtil.isNullOrEmpty(v)) {return null; } else { return Double.valueOf(v); } }
3.26
pulsar_FieldParser_stringToSet_rdh
/** * Converts comma separated string to Set. * * @param <T> * type of set * @param val * comma separated values. * @return The converted set with type {@code <T>}. */ public static <T> Set<T> stringToSet(String val, Class<T> type) { if (val == null) { return null; } String[] tokens = trim(val).split(","); return Arrays.stream(tokens).map(t -> { return convert(trim(t), type); }).collect(Collectors.toCollection(LinkedHashSet::new)); }
3.26
pulsar_FieldParser_stringToBoolean_rdh
/** * Converts String to Boolean. * * @param value * The String to be converted. * @return The converted Boolean value. */ public static Boolean stringToBoolean(String value) { return Boolean.valueOf(value); }
3.26
pulsar_FieldParser_stringToFloat_rdh
/** * Converts String to float. * * @param val * The String to be converted. * @return The converted Double value. */ public static Float stringToFloat(String val) { return Float.valueOf(trim(val)); }
3.26
pulsar_FieldParser_booleanToString_rdh
/** * Converts Boolean to String. * * @param value * The Boolean to be converted. * @return The converted String value. */ public static String booleanToString(Boolean value) { return value.toString(); }
3.26
pulsar_FieldParser_m0_rdh
/** * Converts String to Long. * * @param val * The String to be converted. * @return The converted Long value. */ public static Long m0(String val) { return Long.valueOf(trim(val)); }
3.26
pulsar_FieldParser_integerToString_rdh
/** * Converts Integer to String. * * @param value * The Integer to be converted. * @return The converted String value. */ public static String integerToString(Integer value) { return value.toString(); }
3.26
pulsar_FieldParser_update_rdh
/** * Update given Object attribute by reading it from provided map properties. * * @param properties * which key-value pair of properties to assign those values to given object * @param obj * object which needs to be updated * @throws IllegalArgumentException * if the properties key-value contains incorrect value type */ public static <T> void update(Map<String, String> properties, T obj) throws IllegalArgumentException { Field[] fields = obj.getClass().getDeclaredFields(); Arrays.stream(fields).forEach(f -> { if (properties.containsKey(f.getName())) { try { f.setAccessible(true); String v = properties.get(f.getName()); if (!StringUtils.isBlank(v)) { f.set(obj, value(trim(v), f)); } else { setEmptyValue(v, f, obj); } } catch (Exception e) { throw new IllegalArgumentException(format("failed to initialize %s field while setting value %s", f.getName(), properties.get(f.getName())), e); } } }); }
3.26
pulsar_FieldParser_setEmptyValue_rdh
/** * Sets the empty/null value if field is allowed to be set empty. * * @param strValue * @param field * @param obj * @throws IllegalArgumentException * @throws IllegalAccessException */ public static <T> void setEmptyValue(String strValue, Field field, T obj) throws IllegalArgumentException, IllegalAccessException { requireNonNull(field); // if field is not primitive type Type fieldType = field.getGenericType(); if (fieldType instanceof ParameterizedType) { if (field.getType().equals(List.class)) { field.set(obj, new ArrayList<>()); } else if (field.getType().equals(Set.class)) { field.set(obj, new LinkedHashSet<>()); } else if (field.getType().equals(Optional.class)) { field.set(obj, Optional.empty()); } else { throw new IllegalArgumentException(format("unsupported field-type %s for %s", field.getType(), field.getName())); } } else if (Number.class.isAssignableFrom(field.getType()) || fieldType.getClass().equals(String.class)) { field.set(obj, null); } }
3.26
pulsar_FieldParser_convert_rdh
/** * Convert the given object value to the given class. * * @param from * The object value to be converted. * @param to * The type class which the given object should be converted to. * @return The converted object value. * @throws UnsupportedOperationException * If no suitable converter can be found. * @throws RuntimeException * If conversion failed somehow. This can be caused by at least an ExceptionInInitializerError, * IllegalAccessException or InvocationTargetException. */ @SuppressWarnings("unchecked") public static <T> T convert(Object from, Class<T> to) {requireNonNull(to); if (from == null) { return null; } to = ((Class<T>) (wrap(to))); // Can we cast? Then just do it. if (to.isAssignableFrom(from.getClass())) { return to.cast(from);} // Lookup the suitable converter. String converterId = (from.getClass().getName() + "_") + to.getName(); Method converter = CONVERTERS.get(converterId); if (to.isEnum()) { // Converting string to enum EnumResolver r = EnumResolver.constructUsingToString(((Class<Enum<?>>) (to)), ANNOTATION_INTROSPECTOR); T value = ((T) (r.findEnum(((String) (from))))); if (value == null) { throw new RuntimeException((("Invalid value '" + from) + "' for enum ") + to); } return value; } if (converter == null) { throw new UnsupportedOperationException(((("Cannot convert from " + from.getClass().getName()) + " to ") + to.getName()) + ". Requested converter does not exist."); } // Convert the value. try { Object val = converter.invoke(to, from); return to.cast(val); } catch (Exception e) { throw new RuntimeException((((("Cannot convert from " + from.getClass().getName()) + " to ") + to.getName()) + ". Conversion failed with ") + e.getMessage(), e); } }
3.26
pulsar_TestRetrySupport_incrementSetupNumber_rdh
/** * This method should be called in the setup method of the concrete class. * * This increases an internal counter and resets the failure state which are used to determine * whether cleanup is needed before a test method is called. */ protected final void incrementSetupNumber() { f0++; failedSetupNumber = -1; LOG.debug("currentSetupNumber={}", f0); }
3.26
pulsar_TestRetrySupport_markCurrentSetupNumberCleaned_rdh
/** * This method should be called in the cleanup method of the concrete class. */ protected final void markCurrentSetupNumberCleaned() { cleanedUpSetupNumber = f0; LOG.debug("cleanedUpSetupNumber={}", cleanedUpSetupNumber); }
3.26
pulsar_DateFormatter_parse_rdh
/** * * @param datetime * @return the parsed timestamp (in milliseconds) of the provided datetime * @throws DateTimeParseException */ public static long parse(String datetime) throws DateTimeParseException { Instant instant = Instant.from(DATE_FORMAT.parse(datetime)); return instant.toEpochMilli(); }
3.26
pulsar_DateFormatter_format_rdh
/** * * @return a String representing a particular time instant */public static String format(Instant instant) { return DATE_FORMAT.format(instant); }
3.26
pulsar_DateFormatter_now_rdh
/** * * @return a String representing the current datetime */ public static String now() { return format(Instant.now()); }
3.26
pulsar_TransactionBufferProvider_newProvider_rdh
/** * Construct a provider from the provided class. * * @param providerClassName * the provider class name. * @return an instance of transaction buffer provider. */ static TransactionBufferProvider newProvider(String providerClassName) throws IOException { try { TransactionBufferProvider transactionBufferProvider = Reflections.createInstance(providerClassName, TransactionBufferProvider.class, Thread.currentThread().getContextClassLoader()); return transactionBufferProvider; } catch (Exception e) { throw new IOException(e); } }
3.26
pulsar_AbstractTopic_updatePublishDispatcher_rdh
/** * update topic publish dispatcher for this topic. */ public void updatePublishDispatcher() { synchronized(topicPublishRateLimiterLock) { PublishRate publishRate = topicPolicies.getPublishRate().get(); if ((publishRate.publishThrottlingRateInByte > 0) || (publishRate.publishThrottlingRateInMsg > 0)) { log.info("Enabling publish rate limiting {} on topic {}", publishRate, getName()); if (!preciseTopicPublishRateLimitingEnable) { this.brokerService.setupTopicPublishRateLimiterMonitor(); }if ((this.topicPublishRateLimiter == null) || (this.topicPublishRateLimiter == PublishRateLimiter.DISABLED_RATE_LIMITER)) { // create new rateLimiter if rate-limiter is disabled if (preciseTopicPublishRateLimitingEnable) { this.topicPublishRateLimiter = new PrecisePublishLimiter(publishRate, () -> this.enableCnxAutoRead(), brokerService.pulsar().getExecutor());} else { this.topicPublishRateLimiter = new PublishRateLimiterImpl(publishRate); } } else { this.topicPublishRateLimiter.update(publishRate); } } else { if (log.isDebugEnabled()) { log.debug("Disabling publish throttling for {}", this.topic); } if (topicPublishRateLimiter != null) { topicPublishRateLimiter.close(); } this.topicPublishRateLimiter = PublishRateLimiter.DISABLED_RATE_LIMITER; enableProducerReadForPublishRateLimiting(); } } }
3.26
pulsar_AbstractTopic_updateBrokerSubscriptionTypesEnabled_rdh
// subscriptionTypesEnabled is dynamic and can be updated online. public void updateBrokerSubscriptionTypesEnabled() { topicPolicies.getSubscriptionTypesEnabled().updateBrokerValue(subTypeStringsToEnumSet(brokerService.pulsar().getConfiguration().getSubscriptionTypesEnabled())); }
3.26
pulsar_AbstractTopic_enableProducerReadForPublishRateLimiting_rdh
/** * it sets cnx auto-readable if producer's cnx is disabled due to publish-throttling. */ protected void enableProducerReadForPublishRateLimiting() { if (producers != null) { producers.values().forEach(producer -> { producer.getCnx().cancelPublishRateLimiting(); producer.getCnx().enableCnxAutoRead(); }); } }
3.26
pulsar_AbstractTopic_getTopicPolicies_rdh
/** * Get {@link TopicPolicies} for this topic. * * @return TopicPolicies, if they exist. Otherwise, the value will not be present. */ public Optional<TopicPolicies> getTopicPolicies() { return brokerService.getTopicPolicies(TopicName.get(topic)); }
3.26
pulsar_LoadSheddingStrategy_onActiveBrokersChange_rdh
/** * Triggered when active broker changes. * * @param activeBrokers * active Brokers */ default void onActiveBrokersChange(Set<String> activeBrokers) { }
3.26
pulsar_Topic_getOriginalProducerName_rdh
/** * Return the producer name for the original producer. * * For messages published locally, this will return the same local producer name, though in case of replicated * messages, the original producer name will differ */ default String getOriginalProducerName() {return null; }
3.26
pulsar_ManagedLedgerFactoryImpl_deleteManagedLedger_rdh
/** * Delete all managed ledger resources and metadata. */ void deleteManagedLedger(String managedLedgerName, CompletableFuture<ManagedLedgerConfig> mlConfigFuture, DeleteLedgerCallback callback, Object ctx) { // Read the managed ledger metadata from store asyncGetManagedLedgerInfo(managedLedgerName, new ManagedLedgerInfoCallback() {@Override public void getInfoComplete(ManagedLedgerInfo info, Object ctx) {BookKeeper bkc = getBookKeeper(); // First delete all cursors resources List<CompletableFuture<Void>> futures = info.cursors.entrySet().stream().map(e -> deleteCursor(bkc, managedLedgerName, e.getKey(), e.getValue())).collect(Collectors.toList()); Futures.waitForAll(futures).thenRun(() -> { deleteManagedLedgerData(bkc, managedLedgerName, info, mlConfigFuture, callback, ctx);}).exceptionally(ex -> { callback.deleteLedgerFailed(new ManagedLedgerException(ex), ctx); return null; }); } @Override public void getInfoFailed(ManagedLedgerException exception, Object ctx) { callback.deleteLedgerFailed(exception, ctx); } }, ctx); }
3.26
pulsar_ManagedLedgerFactoryImpl_getManagedLedgers_rdh
/** * Helper for getting stats. * * @return */ public Map<String, ManagedLedgerImpl> getManagedLedgers() { // Return a view of already created ledger by filtering futures not yet completed return Maps.filterValues(Maps.transformValues(ledgers, future -> future.getNow(null)), Predicates.notNull()); }
3.26
pulsar_SystemTopicBasedTopicPoliciesService_readMorePoliciesAsync_rdh
/** * This is an async method for the background reader to continue syncing new messages. * * Note: You should not do any blocking call here. because it will affect * #{@link SystemTopicBasedTopicPoliciesService#getTopicPoliciesAsync(TopicName)} method to block loading topic. */ private void readMorePoliciesAsync(SystemTopicClient.Reader<PulsarEvent> reader) { reader.readNextAsync().thenAccept(msg -> { refreshTopicPoliciesCache(msg); notifyListener(msg); }).whenComplete((__, ex) -> { if (ex == null) { readMorePoliciesAsync(reader); } else { Throwable v28 = FutureUtil.unwrapCompletionException(ex); if (v28 instanceof PulsarClientException.AlreadyClosedException) { log.warn("Read more topic policies exception, close the read now!", ex); cleanCacheAndCloseReader(reader.getSystemTopic().getTopicName().getNamespaceObject(), false); } else { log.warn("Read more topic polices exception, read again.", ex); readMorePoliciesAsync(reader); } } }); }
3.26
pulsar_TopicName_isV2_rdh
/** * Returns true if this a V2 topic name prop/ns/topic-name. * * @return true if V2 */ public boolean isV2() { return cluster == null; }
3.26
pulsar_TopicName_getLookupName_rdh
/** * Get a string suitable for completeTopicName lookup. * * <p>Example: * * <p>persistent://tenant/cluster/namespace/completeTopicName -> * persistent/tenant/cluster/namespace/completeTopicName * * @return */ public String getLookupName() { if (isV2()) { return String.format("%s/%s/%s/%s", domain, tenant, namespacePortion, getEncodedLocalName()); } else { return String.format("%s/%s/%s/%s/%s", domain, tenant, cluster, namespacePortion, getEncodedLocalName()); } }
3.26
pulsar_TopicName_getTopicPartitionNameString_rdh
/** * A helper method to get a partition name of a topic in String. * * @return topic + "-partition-" + partition. */ public static String getTopicPartitionNameString(String topic, int partitionIndex) { return (topic + PARTITIONED_TOPIC_SUFFIX) + partitionIndex; }
3.26
pulsar_TopicName_fromPersistenceNamingEncoding_rdh
/** * get topic full name from managedLedgerName. * * @return the topic full name, format -> domain://tenant/namespace/topic */public static String fromPersistenceNamingEncoding(String mlName) { // The managedLedgerName convention is: tenant/namespace/domain/topic // We want to transform to topic full name in the order: domain://tenant/namespace/topic if ((mlName == null) || (mlName.length() == 0)) { return mlName; } List<String> v11 = Splitter.on("/").splitToList(mlName); String tenant; String cluster; String namespacePortion; String domain; String localName; if (v11.size() == 4) { tenant = v11.get(0); cluster = null; namespacePortion = v11.get(1); domain = v11.get(2); localName = v11.get(3); return String.format("%s://%s/%s/%s", domain, tenant, namespacePortion, localName); } else if (v11.size() == 5) { tenant = v11.get(0); cluster = v11.get(1);namespacePortion = v11.get(2); domain = v11.get(3); localName = v11.get(4); return String.format("%s://%s/%s/%s/%s", domain, tenant, cluster, namespacePortion, localName); } else {throw new IllegalArgumentException("Invalid managedLedger name: " + mlName); } }
3.26
pulsar_TopicName_getPersistenceNamingEncoding_rdh
/** * Returns the name of the persistence resource associated with the completeTopicName. * * @return the relative path to be used in persistence */ public String getPersistenceNamingEncoding() { // The convention is: domain://tenant/namespace/topic // We want to persist in the order: tenant/namespace/domain/topic // For legacy naming scheme, the convention is: domain://tenant/cluster/namespace/topic // We want to persist in the order: tenant/cluster/namespace/domain/topic if (isV2()) { return String.format("%s/%s/%s/%s", tenant, namespacePortion, domain, getEncodedLocalName()); } else { return String.format("%s/%s/%s/%s/%s", tenant, cluster, namespacePortion, domain, getEncodedLocalName()); } }
3.26
pulsar_PulsarClientImplementationBindingImpl_convertKeyValueDataStringToSchemaInfoSchema_rdh
/** * Convert the key/value schema info data json bytes to key/value schema info data bytes. * * @param keyValueSchemaInfoDataJsonBytes * the key/value schema info data json bytes * @return the key/value schema info data bytes */ public byte[] convertKeyValueDataStringToSchemaInfoSchema(byte[] keyValueSchemaInfoDataJsonBytes) throws IOException { return SchemaUtils.convertKeyValueDataStringToSchemaInfoSchema(keyValueSchemaInfoDataJsonBytes); }
3.26
pulsar_PulsarClientImplementationBindingImpl_decodeKeyValueEncodingType_rdh
/** * Decode the kv encoding type from the schema info. * * @param schemaInfo * the schema info * @return the kv encoding type */ public KeyValueEncodingType decodeKeyValueEncodingType(SchemaInfo schemaInfo) { return KeyValueSchemaInfo.decodeKeyValueEncodingType(schemaInfo); }
3.26
pulsar_PulsarClientImplementationBindingImpl_decodeKeyValueSchemaInfo_rdh
/** * Decode the key/value schema info to get key schema info and value schema info. * * @param schemaInfo * key/value schema info. * @return the pair of key schema info and value schema info */ public KeyValue<SchemaInfo, SchemaInfo> decodeKeyValueSchemaInfo(SchemaInfo schemaInfo) { return KeyValueSchemaInfo.decodeKeyValueSchemaInfo(schemaInfo); }
3.26
pulsar_PulsarClientImplementationBindingImpl_jsonifySchemaInfoWithVersion_rdh
/** * Jsonify the schema info with version. * * @param schemaInfoWithVersion * the schema info with version * @return the jsonified schema info with version */ public String jsonifySchemaInfoWithVersion(SchemaInfoWithVersion schemaInfoWithVersion) { return SchemaUtils.jsonifySchemaInfoWithVersion(schemaInfoWithVersion); }
3.26
pulsar_PulsarClientImplementationBindingImpl_convertKeyValueSchemaInfoDataToString_rdh
/** * Convert the key/value schema data. * * @param kvSchemaInfo * the key/value schema info * @return the convert key/value schema data string */ public String convertKeyValueSchemaInfoDataToString(KeyValue<SchemaInfo, SchemaInfo> kvSchemaInfo) throws IOException { return SchemaUtils.convertKeyValueSchemaInfoDataToString(kvSchemaInfo); }
3.26
pulsar_PulsarClientImplementationBindingImpl_jsonifyKeyValueSchemaInfo_rdh
/** * Jsonify the key/value schema info. * * @param kvSchemaInfo * the key/value schema info * @return the jsonified schema info */ public String jsonifyKeyValueSchemaInfo(KeyValue<SchemaInfo, SchemaInfo> kvSchemaInfo) { return SchemaUtils.jsonifyKeyValueSchemaInfo(kvSchemaInfo); }
3.26
pulsar_PulsarClientImplementationBindingImpl_jsonifySchemaInfo_rdh
/** * Jsonify the schema info. * * @param schemaInfo * the schema info * @return the jsonified schema info */ public String jsonifySchemaInfo(SchemaInfo schemaInfo) { return SchemaUtils.jsonifySchemaInfo(schemaInfo); }
3.26
pulsar_PulsarClientImplementationBindingImpl_encodeKeyValueSchemaInfo_rdh
/** * Encode key & value into schema into a KeyValue schema. * * @param schemaName * the final schema name * @param keySchema * the key schema * @param valueSchema * the value schema * @param keyValueEncodingType * the encoding type to encode and decode key value pair * @return the final schema info */ public <K, V> SchemaInfo encodeKeyValueSchemaInfo(String schemaName, Schema<K> keySchema, Schema<V> valueSchema, KeyValueEncodingType keyValueEncodingType) { return KeyValueSchemaInfo.encodeKeyValueSchemaInfo(schemaName, keySchema, valueSchema, keyValueEncodingType); }
3.26
pulsar_DispatchRateLimiter_getDispatchRateOnMsg_rdh
/** * Get configured msg dispatch-throttling rate. Returns -1 if not configured * * @return */ public long getDispatchRateOnMsg() { return dispatchRateLimiterOnMessage != null ? dispatchRateLimiterOnMessage.getRate() : -1; }
3.26
pulsar_DispatchRateLimiter_updateDispatchRate_rdh
/** * Update dispatch rate by updating msg and byte rate-limiter. If dispatch-rate is configured &lt; 0 then it closes * the rate-limiter and disables appropriate rate-limiter. * * @param dispatchRate */ public synchronized void updateDispatchRate(DispatchRate dispatchRate) { // synchronized to prevent race condition from concurrent zk-watch log.info("setting message-dispatch-rate {}", dispatchRate);long msgRate = dispatchRate.getDispatchThrottlingRateInMsg(); long byteRate = dispatchRate.getDispatchThrottlingRateInByte(); long ratePeriod = dispatchRate.getRatePeriodInSecond(); Supplier<Long> permitUpdaterMsg = (dispatchRate.isRelativeToPublishRate()) ? () -> getRelativeDispatchRateInMsg(dispatchRate) : null; // update msg-rateLimiter if (msgRate > 0) { if (this.dispatchRateLimiterOnMessage == null) { this.dispatchRateLimiterOnMessage = RateLimiter.builder().scheduledExecutorService(brokerService.pulsar().getExecutor()).permits(msgRate).rateTime(ratePeriod).timeUnit(TimeUnit.SECONDS).permitUpdater(permitUpdaterMsg).isDispatchOrPrecisePublishRateLimiter(true).build(); } else { this.dispatchRateLimiterOnMessage.setRate(msgRate, dispatchRate.getRatePeriodInSecond(), TimeUnit.SECONDS, permitUpdaterMsg); } } else // message-rate should be disable and close if (this.dispatchRateLimiterOnMessage != null) { this.dispatchRateLimiterOnMessage.close(); this.dispatchRateLimiterOnMessage = null; } Supplier<Long> v12 = (dispatchRate.isRelativeToPublishRate()) ? () -> getRelativeDispatchRateInByte(dispatchRate) : null; // update byte-rateLimiter if (byteRate > 0) { if (this.dispatchRateLimiterOnByte == null) { this.dispatchRateLimiterOnByte = RateLimiter.builder().scheduledExecutorService(brokerService.pulsar().getExecutor()).permits(byteRate).rateTime(ratePeriod).timeUnit(TimeUnit.SECONDS).permitUpdater(v12).isDispatchOrPrecisePublishRateLimiter(true).build(); } else { this.dispatchRateLimiterOnByte.setRate(byteRate, dispatchRate.getRatePeriodInSecond(), TimeUnit.SECONDS, v12); } } else // message-rate should be disable and close if (this.dispatchRateLimiterOnByte != null) {this.dispatchRateLimiterOnByte.close(); this.dispatchRateLimiterOnByte = null; } }
3.26
pulsar_DispatchRateLimiter_getAvailableDispatchRateLimitOnByte_rdh
/** * returns available byte-permit if msg-dispatch-throttling is enabled else it returns -1. * * @return */ public long getAvailableDispatchRateLimitOnByte() { return dispatchRateLimiterOnByte == null ? -1 : dispatchRateLimiterOnByte.getAvailablePermits(); }
3.26
pulsar_DispatchRateLimiter_hasMessageDispatchPermit_rdh
/** * checks if dispatch-rate limit is configured and if it's configured then check if permits are available or not. * * @return */ public boolean hasMessageDispatchPermit() { return ((dispatchRateLimiterOnMessage == null) || (dispatchRateLimiterOnMessage.getAvailablePermits() > 0)) && ((dispatchRateLimiterOnByte == null) || (dispatchRateLimiterOnByte.getAvailablePermits() > 0));}
3.26
pulsar_DispatchRateLimiter_tryDispatchPermit_rdh
/** * It acquires msg and bytes permits from rate-limiter and returns if acquired permits succeed. * * @param msgPermits * @param bytePermits * @return */ public boolean tryDispatchPermit(long msgPermits, long bytePermits) { boolean acquiredMsgPermit = ((msgPermits <= 0) || (dispatchRateLimiterOnMessage == null)) || dispatchRateLimiterOnMessage.tryAcquire(msgPermits); boolean acquiredBytePermit = ((bytePermits <= 0) || (dispatchRateLimiterOnByte == null)) || dispatchRateLimiterOnByte.tryAcquire(bytePermits); return acquiredMsgPermit && acquiredBytePermit; }
3.26
pulsar_DispatchRateLimiter_createDispatchRate_rdh
/** * createDispatchRate according to broker service config. * * @return */ private DispatchRate createDispatchRate() { int dispatchThrottlingRateInMsg; long dispatchThrottlingRateInByte; ServiceConfiguration config = brokerService.pulsar().getConfiguration(); switch (type) { case TOPIC : dispatchThrottlingRateInMsg = config.getDispatchThrottlingRatePerTopicInMsg(); dispatchThrottlingRateInByte = config.getDispatchThrottlingRatePerTopicInByte(); break; case SUBSCRIPTION : dispatchThrottlingRateInMsg = config.getDispatchThrottlingRatePerSubscriptionInMsg(); dispatchThrottlingRateInByte = config.getDispatchThrottlingRatePerSubscriptionInByte(); break; case REPLICATOR : dispatchThrottlingRateInMsg = config.getDispatchThrottlingRatePerReplicatorInMsg(); dispatchThrottlingRateInByte = config.getDispatchThrottlingRatePerReplicatorInByte(); break; case BROKER : dispatchThrottlingRateInMsg = config.getDispatchThrottlingRateInMsg(); dispatchThrottlingRateInByte = config.getDispatchThrottlingRateInByte(); break; default : dispatchThrottlingRateInMsg = -1; dispatchThrottlingRateInByte = -1; } return DispatchRate.builder().dispatchThrottlingRateInMsg(dispatchThrottlingRateInMsg).dispatchThrottlingRateInByte(dispatchThrottlingRateInByte).ratePeriodInSecond(1).relativeToPublishRate((type != Type.BROKER) && config.isDispatchThrottlingRateRelativeToPublishRate()).build(); }
3.26
pulsar_DispatchRateLimiter_getDispatchRateOnByte_rdh
/** * Get configured byte dispatch-throttling rate. Returns -1 if not configured * * @return */ public long getDispatchRateOnByte() { return dispatchRateLimiterOnByte != null ? dispatchRateLimiterOnByte.getRate() : -1; }
3.26
pulsar_DispatchRateLimiter_getAvailableDispatchRateLimitOnMsg_rdh
/** * returns available msg-permit if msg-dispatch-throttling is enabled else it returns -1. * * @return */ public long getAvailableDispatchRateLimitOnMsg() { return dispatchRateLimiterOnMessage == null ? -1 : dispatchRateLimiterOnMessage.getAvailablePermits(); }
3.26
pulsar_DispatchRateLimiter_isDispatchRateLimitingEnabled_rdh
/** * Checks if dispatch-rate limiting is enabled. * * @return */ public boolean isDispatchRateLimitingEnabled() { return (dispatchRateLimiterOnMessage != null) || (dispatchRateLimiterOnByte != null); }
3.26
pulsar_MBeanStatsGenerator_createMetricsByDimension_rdh
/** * Creates a MBean dimension key for metrics. * * @param objectName * @return */ private Metrics createMetricsByDimension(ObjectName objectName) { Map<String, String> dimensionMap = new HashMap<>(); dimensionMap.put("MBean", objectName.toString());// create with current version return Metrics.create(dimensionMap); }
3.26
pulsar_AbstractMultiVersionReader_m0_rdh
/** * TODO: think about how to make this async. */ protected SchemaInfo m0(byte[] schemaVersion) { try { return schemaInfoProvider.getSchemaByVersion(schemaVersion).get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new SerializationException("Interrupted at fetching schema info for " + SchemaUtils.getStringSchemaVersion(schemaVersion), e); } catch (ExecutionException e) { throw new SerializationException("Failed at fetching schema info for " + SchemaUtils.getStringSchemaVersion(schemaVersion), e.getCause()); } }
3.26
pulsar_RateLimiter_getRate_rdh
/** * Returns configured permit rate per pre-configured rate-period. * * @return rate */ public synchronized long getRate() { return this.permits; }
3.26
pulsar_RateLimiter_setRate_rdh
/** * Resets new rate with new permits and rate-time. * * @param permits * @param rateTime * @param timeUnit * @param permitUpdaterByte */ public synchronized void setRate(long permits, long rateTime, TimeUnit timeUnit, Supplier<Long> permitUpdaterByte) { if (renewTask != null) { renewTask.cancel(false); } this.permits = permits; this.rateTime = rateTime; this.timeUnit = timeUnit; this.permitUpdater = permitUpdaterByte; this.renewTask = createTask(); }
3.26
pulsar_RateLimiter_getAvailablePermits_rdh
/** * Return available permits for this {@link RateLimiter}. * * @return returns 0 if permits is not available */ public long getAvailablePermits() { return Math.max(0, this.permits - this.acquiredPermits); }
3.26
pulsar_RateLimiter_tryAcquire_rdh
/** * Acquires permits from this {@link RateLimiter} if it can be acquired immediately without delay. * * <p>This method is equivalent to {@code tryAcquire(1)}. * * @return {@code true} if the permits were acquired, {@code false} otherwise */ public synchronized boolean tryAcquire() { return tryAcquire(1);}
3.26
pulsar_RateLimiter_acquire_rdh
/** * Acquires the given number of permits from this {@code RateLimiter}, blocking until the request be granted. * * @param acquirePermit * the number of permits to acquire */ public synchronized void acquire(long acquirePermit) throws InterruptedException { checkArgument(!isClosed(), "Rate limiter is already shutdown"); checkArgument(acquirePermit <= this.permits, "acquiring permits must be less or equal than initialized rate =" + this.permits); // lazy init and start task only once application start using it if (renewTask == null) {renewTask = createTask(); } boolean canAcquire = false; do { canAcquire = (acquirePermit < 0) || (acquiredPermits < this.permits); if (!canAcquire) { wait(); } else { acquiredPermits += acquirePermit; } } while (!canAcquire ); }
3.26
pulsar_DefaultMetadataResolver_fromIssuerUrl_rdh
/** * Gets a well-known metadata URL for the given OAuth issuer URL. * * @param issuerUrl * The authorization server's issuer identifier * @return a resolver */ public static DefaultMetadataResolver fromIssuerUrl(URL issuerUrl) { return new DefaultMetadataResolver(getWellKnownMetadataUrl(issuerUrl)); }
3.26
pulsar_DefaultMetadataResolver_resolve_rdh
/** * Resolves the authorization metadata. * * @return metadata * @throws IOException * if the metadata could not be resolved. */ public Metadata resolve() throws IOException { try { URLConnection c = this.metadataUrl.openConnection(); if (connectTimeout != null) { c.setConnectTimeout(((int) (connectTimeout.toMillis()))); } if (readTimeout != null) { c.setReadTimeout(((int) (readTimeout.toMillis()))); }c.setRequestProperty("Accept", "application/json"); Metadata metadata; try (InputStream inputStream = c.getInputStream()) { metadata = this.objectReader.readValue(inputStream); } return metadata; } catch (IOException e) { throw new IOException("Cannot obtain authorization metadata from " + metadataUrl.toString(), e); } }
3.26
pulsar_MLTransactionSequenceIdGenerator_onManagedLedgerPropertiesInitialize_rdh
// When all of ledger have been deleted, we will generate sequenceId from managedLedger properties @Override public void onManagedLedgerPropertiesInitialize(Map<String, String> propertiesMap) { if ((propertiesMap == null) || (propertiesMap.size() == 0)) { return; } if (propertiesMap.containsKey(MAX_LOCAL_TXN_ID)) { sequenceId.set(Long.parseLong(propertiesMap.get(MAX_LOCAL_TXN_ID))); } }
3.26
pulsar_SinkContext_seek_rdh
/** * Reset the subscription associated with this topic and partition to a specific message id. * * @param topic * - topic name * @param partition * - partition id (0 for non-partitioned topics) * @param messageId * to reset to * @throws PulsarClientException */ default void seek(String topic, int partition, MessageId messageId) throws PulsarClientException { throw new UnsupportedOperationException("not implemented"); }
3.26
pulsar_SinkContext_getSubscriptionType_rdh
/** * Get subscription type used by the source providing data for the sink. * * @return subscription type */ default SubscriptionType getSubscriptionType() { throw new UnsupportedOperationException("Context does not provide SubscriptionType"); }
3.26
pulsar_SinkContext_resume_rdh
/** * Resume requesting messages. * * @param topic * - topic name * @param partition * - partition id (0 for non-partitioned topics) */ default void resume(String topic, int partition) throws PulsarClientException { throw new UnsupportedOperationException("not implemented"); }
3.26
pulsar_SinkContext_pause_rdh
/** * Stop requesting new messages for given topic and partition until {@link #resume(String topic, int partition)} * is called. * * @param topic * - topic name * @param partition * - partition id (0 for non-partitioned topics) */ default void pause(String topic, int partition) throws PulsarClientException { throw new UnsupportedOperationException("not implemented"); }
3.26
pulsar_NarUnpacker_unpackNar_rdh
/** * Unpacks the specified nar into the specified base working directory. * * @param nar * the nar to unpack * @param baseWorkingDirectory * the directory to unpack to * @return the directory to the unpacked NAR * @throws IOException * if unable to explode nar */ public static File unpackNar(final File nar, final File baseWorkingDirectory) throws IOException { return doUnpackNar(nar, baseWorkingDirectory, null); }
3.26
pulsar_NarUnpacker_unpack_rdh
/** * Unpacks the NAR to the specified directory. * * @param workingDirectory * the root directory to which the NAR should be unpacked. * @throws IOException * if the NAR could not be unpacked. */ private static void unpack(final File nar, final File workingDirectory) throws IOException { try (JarFile jarFile = new JarFile(nar)) { Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); String name = jarEntry.getName(); File f = new File(workingDirectory, name); if (jarEntry.isDirectory()) { FileUtils.ensureDirectoryExistAndCanReadAndWrite(f); } else { // The directory entry might appear after the file entry FileUtils.ensureDirectoryExistAndCanReadAndWrite(f.getParentFile()); makeFile(jarFile.getInputStream(jarEntry), f); } } } }
3.26