name
stringlengths
12
178
code_snippet
stringlengths
8
36.5k
score
float64
3.26
3.68
pulsar_AuthenticationDataKeyStoreTls_hasDataForTls_rdh
/* TLS */ @Override public boolean hasDataForTls() { return true; }
3.26
pulsar_MessageIdAdv_getBatchIndex_rdh
/** * Get the batch index. * * @return -1 if the message is not in a batch */ default int getBatchIndex() { return -1; }
3.26
pulsar_MessageIdAdv_compareTo_rdh
/** * The default implementation of {@link Comparable#compareTo(Object)}. */ default int compareTo(MessageId o) { if (!(o instanceof MessageIdAdv)) { throw new UnsupportedOperationException("Unknown MessageId type: " + (o != null ? o.getClass().getName() : "null")); } final MessageIdAdv other = ((MessageIdAdv) (o)); int result = Long.compare(this.getLedgerId(), other.getLedgerId()); if (result != 0) { return result; } result = Long.compare(this.getEntryId(), other.getEntryId());if (result != 0) { return result; } // TODO: Correct the following compare logics, see https://github.com/apache/pulsar/pull/18981 result = Integer.compare(this.getPartitionIndex(), other.getPartitionIndex()); if (result != 0) { return result; } return Integer.compare(this.getBatchIndex(), other.getBatchIndex());}
3.26
pulsar_MessageIdAdv_getBatchSize_rdh
/** * Get the batch size. * * @return 0 if the message is not in a batch */ default int getBatchSize() { return 0; }
3.26
pulsar_AuthenticationMetrics_authenticateSuccess_rdh
/** * Log authenticate success event to the authentication metrics. * * @param providerName * The short class name of the provider * @param authMethod * Authentication method name */ public static void authenticateSuccess(String providerName, String authMethod) { authSuccessMetrics.labels(providerName, authMethod).inc(); }
3.26
pulsar_AuthenticationMetrics_authenticateFailure_rdh
/** * Log authenticate failure event to the authentication metrics. * * @param providerName * The short class name of the provider * @param authMethod * Authentication method name. * @param errorCode * Error code. */ public static void authenticateFailure(String providerName, String authMethod, Enum<?> errorCode) { authFailuresMetrics.labels(providerName, authMethod, errorCode.name()).inc(); }
3.26
pulsar_WindowLifecycleListener_onActivation_rdh
/** * Called on activation of the window due to the {@link TriggerPolicy}. * * @param events * the list of current events in the window. * @param newEvents * the newly added events since last activation. * @param expired * the expired events since last activation. * @param referenceTime * the reference (event or processing) time that resulted in activation */ default void onActivation(List<T> events, List<T> newEvents, List<T> expired, Long referenceTime) { throw new UnsupportedOperationException("Not implemented"); }
3.26
pulsar_SaslRoleTokenSigner_sign_rdh
/** * Returns a signed string. * <p/> * The signature '&s=SIGNATURE' is appended at the end of the string. * * @param str * string to sign. * @return the signed string. */ public String sign(String str) { if ((str == null) || (str.length() == 0)) { throw new IllegalArgumentException("NULL or empty string to sign"); } String signature = computeSignature(str); return (str + SIGNATURE) + signature; }
3.26
pulsar_SaslRoleTokenSigner_computeSignature_rdh
/** * Returns the signature of a string. * * @param str * string to sign. * @return the signature for the string. */ protected String computeSignature(String str) { try { MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(str.getBytes()); md.update(secret); byte[] digest = md.digest(); return new Base64(0).encodeToString(digest); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException("It should not happen, " + ex.getMessage(), ex); } }
3.26
pulsar_SaslRoleTokenSigner_verifyAndExtract_rdh
/** * Verifies a signed string and extracts the original string. * * @param signedStr * the signed string to verify and extract. * @return the extracted original string. * @throws AuthenticationException * thrown if the given string is not a signed string or if the signature is invalid. */ public String verifyAndExtract(String signedStr) throws AuthenticationException { int index = signedStr.lastIndexOf(SIGNATURE); if (index == (-1)) { throw new AuthenticationException("Invalid signed text: " + signedStr); } String originalSignature = signedStr.substring(index + SIGNATURE.length()); String v3 = signedStr.substring(0, index);String currentSignature = computeSignature(v3); if (!MessageDigest.isEqual(originalSignature.getBytes(), currentSignature.getBytes())) { throw new AuthenticationException("Invalid signature"); } return v3; }
3.26
pulsar_PushPulsarSource_getQueueLength_rdh
/** * Get length of the queue that records are push onto * Users can override this method to customize the queue length. * * @return queue length */ public int getQueueLength() { return DEFAULT_QUEUE_LENGTH; }
3.26
pulsar_LeastResourceUsageWithWeight_updateAndGetMaxResourceUsageWithWeight_rdh
/** * Update and get the max resource usage with weight of broker according to the service configuration. * * @param broker * the broker name. * @param brokerData * The broker load data. * @param conf * The service configuration. * @return the max resource usage with weight of broker */ private double updateAndGetMaxResourceUsageWithWeight(String broker, BrokerData brokerData, ServiceConfiguration conf) { final double historyPercentage = conf.getLoadBalancerHistoryResourcePercentage(); Double historyUsage = brokerAvgResourceUsageWithWeight.get(broker); LocalBrokerData localData = brokerData.getLocalData(); // If the broker restarted or MsgRate is 0, should use current resourceUsage to cover the historyUsage if ((localData.getBundles().size() == 0) || ((localData.getMsgRateIn() == 0) && (localData.getMsgRateOut() == 0))) { historyUsage = null; } double resourceUsage = brokerData.getLocalData().getMaxResourceUsageWithWeight(conf.getLoadBalancerCPUResourceWeight(), conf.getLoadBalancerDirectMemoryResourceWeight(), conf.getLoadBalancerBandwithInResourceWeight(), conf.getLoadBalancerBandwithOutResourceWeight()); historyUsage = (historyUsage == null) ? resourceUsage : (historyUsage * historyPercentage) + ((1 - historyPercentage) * resourceUsage); if (log.isDebugEnabled()) { log.debug(("Broker {} get max resource usage with weight: {}, history resource percentage: {}%, CPU weight: " + "{}, MEMORY weight: {}, DIRECT MEMORY weight: {}, BANDWIDTH IN weight: {}, BANDWIDTH ") + "OUT weight: {} ", broker, historyUsage, historyPercentage, conf.getLoadBalancerCPUResourceWeight(), conf.getLoadBalancerMemoryResourceWeight(), conf.getLoadBalancerDirectMemoryResourceWeight(), conf.getLoadBalancerBandwithInResourceWeight(), conf.getLoadBalancerBandwithOutResourceWeight()); } brokerAvgResourceUsageWithWeight.put(broker, historyUsage); return historyUsage; }
3.26
pulsar_LeastResourceUsageWithWeight_getMaxResourceUsageWithWeight_rdh
// A broker's max resource usage with weight using its historical load and short-term load data with weight. private double getMaxResourceUsageWithWeight(final String broker, final BrokerData brokerData, final ServiceConfiguration conf) { final double overloadThreshold = conf.getLoadBalancerBrokerOverloadedThresholdPercentage() / 100.0; final double maxUsageWithWeight = updateAndGetMaxResourceUsageWithWeight(broker, brokerData, conf); if (maxUsageWithWeight > overloadThreshold) { final LocalBrokerData localData = brokerData.getLocalData(); log.warn((("Broker {} is overloaded, max resource usage with weight percentage: {}%, " + "CPU: {}%, MEMORY: {}%, DIRECT MEMORY: {}%, BANDWIDTH IN: {}%, ") + "BANDWIDTH OUT: {}%, CPU weight: {}, MEMORY weight: {}, DIRECT MEMORY weight: {}, ") + "BANDWIDTH IN weight: {}, BANDWIDTH OUT weight: {}", broker, maxUsageWithWeight * 100, localData.getCpu().percentUsage(), localData.getMemory().percentUsage(), localData.getDirectMemory().percentUsage(), localData.getBandwidthIn().percentUsage(), localData.getBandwidthOut().percentUsage(), conf.getLoadBalancerCPUResourceWeight(), conf.getLoadBalancerMemoryResourceWeight(), conf.getLoadBalancerDirectMemoryResourceWeight(), conf.getLoadBalancerBandwithInResourceWeight(), conf.getLoadBalancerBandwithOutResourceWeight()); } if (log.isDebugEnabled()) {log.debug("Broker {} has max resource usage with weight percentage: {}%", brokerData.getLocalData().getWebServiceUrl(), maxUsageWithWeight * 100); } return maxUsageWithWeight; }
3.26
pulsar_LeastResourceUsageWithWeight_selectBroker_rdh
/** * Find a suitable broker to assign the given bundle to. * This method is not thread safety. * * @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 synchronized Optional<String> selectBroker(Set<String> candidates, BundleData bundleToAssign, LoadData loadData, ServiceConfiguration conf) { if (candidates.isEmpty()) { log.info("There are no available brokers as candidates at this point for bundle: {}", bundleToAssign); return Optional.empty(); } bestBrokers.clear(); // Maintain of list of all the best scoring brokers and then randomly // select one of them at the end. double totalUsage = 0.0; for (String broker : candidates) { BrokerData brokerData = loadData.getBrokerData().get(broker); double usageWithWeight = getMaxResourceUsageWithWeight(broker, brokerData, conf);totalUsage += usageWithWeight; } final double avgUsage = totalUsage / candidates.size(); final double diffThreshold = conf.getLoadBalancerAverageResourceUsageDifferenceThresholdPercentage() / 100.0; candidates.forEach(broker -> { Double avgResUsage = brokerAvgResourceUsageWithWeight.getOrDefault(broker, MAX_RESOURCE_USAGE); if ((avgResUsage + diffThreshold) <= avgUsage) { bestBrokers.add(broker); } }); if (bestBrokers.isEmpty()) { // Assign randomly as all brokers are overloaded. log.warn("Assign randomly as all {} brokers are overloaded.", candidates.size()); bestBrokers.addAll(candidates); } if (log.isDebugEnabled()) { log.debug("Selected {} best brokers: {} from candidate brokers: {}", bestBrokers.size(), bestBrokers, candidates); } return Optional.of(bestBrokers.get(ThreadLocalRandom.current().nextInt(bestBrokers.size())));}
3.26
pulsar_AbstractCmdConsume_updateConfig_rdh
/** * Set client configuration. */ public void updateConfig(ClientBuilder clientBuilder, Authentication authentication, String serviceURL) { this.clientBuilder = clientBuilder; this.authentication = authentication; this.serviceURL = serviceURL; }
3.26
pulsar_AbstractCmdConsume_interpretMessage_rdh
/** * Interprets the message to create a string representation. * * @param message * The message to interpret * @param displayHex * Whether to display BytesMessages in hexdump style, ignored for simple text messages * @return String representation of the message */ protected String interpretMessage(Message<?> message, boolean displayHex) throws IOException { StringBuilder sb = new StringBuilder(); String properties = Arrays.toString(message.getProperties().entrySet().toArray()); String data; Object value = message.getValue(); if (value == null) { data = "null"; } else if (value instanceof byte[]) { byte[] msgData = ((byte[]) (value)); data = interpretByteArray(displayHex, msgData); } else if (value instanceof GenericObject) { Map<String, Object> asMap = genericObjectToMap(((GenericObject) (value)), displayHex); data = asMap.toString(); } else if (value instanceof ByteBuffer) { data = new String(getBytes(((ByteBuffer) (value)))); } else { data = value.toString();} String key = null; if (message.hasKey()) { key = message.getKey(); } sb.append("key:[").append(key).append("], "); if (!properties.isEmpty()) { sb.append("properties:").append(properties).append(", "); } sb.append("content:").append(data); return sb.toString(); }
3.26
pulsar_JsonRecordBuilderImpl_set_rdh
/** * Sets the value of a field. * * @param field * the field to set. * @param value * the value to set. * @return a reference to the RecordBuilder. */ @Override public GenericRecordBuilder set(Field field, Object value) { set(field.getName(), value); return this; }
3.26
pulsar_JsonRecordBuilderImpl_clear_rdh
/** * Clears the value of the given field. * * @param field * the field to clear. * @return a reference to the RecordBuilder. */@Override public GenericRecordBuilder clear(Field field) { clear(field.getName()); return this; }
3.26
pulsar_TransactionPendingAckStoreProvider_newProvider_rdh
/** * Construct a provider from the provided class. * * @param providerClassName * {@link String} the provider class name * @return an instance of transaction buffer provider. */ static TransactionPendingAckStoreProvider newProvider(String providerClassName) throws IOException { try { TransactionPendingAckStoreProvider ackStoreProvider = Reflections.createInstance(providerClassName, TransactionPendingAckStoreProvider.class, Thread.currentThread().getContextClassLoader());return ackStoreProvider; } catch (Exception e) { throw new IOException(e); } } /** * Open the pending ack store. * * @param subscription * {@link PersistentSubscription} * @return a future represents the result of the operation. an instance of {@link PendingAckStore}
3.26
pulsar_OneStageAuthenticationState_authenticateAsync_rdh
/** * Warning: this method is not intended to be called concurrently. */ @Override public CompletableFuture<AuthData> authenticateAsync(AuthData authData) {if (authRole != null) { // Authentication is already completed return CompletableFuture.completedFuture(null); } this.authenticationDataSource = new AuthenticationDataCommand(new String(authData.getBytes(), UTF_8), remoteAddress, sslSession);return provider.authenticateAsync(authenticationDataSource).thenApply(role -> { this.authRole = role; // Single stage authentication always returns null return null; }); }
3.26
pulsar_OneStageAuthenticationState_authenticate_rdh
/** * * @deprecated use {@link #authenticateAsync(AuthData)} */@Deprecated(since = "3.0.0") @Override public AuthData authenticate(AuthData authData) throws AuthenticationException { try { return authenticateAsync(authData).get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } /** * * @deprecated rely on result from {@link #authenticateAsync(AuthData)}. For more information, see the Javadoc for {@link AuthenticationState#isComplete()}
3.26
pulsar_ModularLoadManager_writeBrokerDataOnZooKeeper_rdh
/** * As any broker, write the local broker data to ZooKeeper, forced or not. */default void writeBrokerDataOnZooKeeper(boolean force) { writeBrokerDataOnZooKeeper(); }
3.26
pulsar_ServiceUrlProvider_close_rdh
/** * Close the resource that the provider allocated. */ @Override default void close() { // do nothing }
3.26
pulsar_CustomCommandFactoryProvider_createCustomCommandFactories_rdh
/** * create a Command Factory. */ public static List<CustomCommandFactory> createCustomCommandFactories(Properties conf) throws IOException { String names = conf.getProperty("customCommandFactories", ""); List<CustomCommandFactory> result = new ArrayList<>(); if (names.isEmpty()) { // early exit return result; } String directory = conf.getProperty("cliExtensionsDirectory", "cliextensions"); String narExtractionDirectory = NarClassLoader.DEFAULT_NAR_EXTRACTION_DIR; CustomCommandFactoryDefinitions definitions = searchForCustomCommandFactories(directory, narExtractionDirectory); for (String name : names.split(",")) { CustomCommandFactoryMetaData metaData = definitions.getFactories().get(name); if (null == metaData) { throw new RuntimeException((("No factory is found for name `" + name) + "`. Available names are : ") + definitions.getFactories()); } CustomCommandFactory factory = load(metaData, narExtractionDirectory); if (factory != null) { result.add(factory);} log.debug("Successfully loaded command factory for name `{}`", name); } return result; }
3.26
pulsar_AdditionalServletUtils_load_rdh
/** * Load the additional servlets according to the additional servlet definition. * * @param metadata * the additional servlet definition. */ public AdditionalServletWithClassLoader load(AdditionalServletMetadata metadata, String narExtractionDirectory) throws IOException { final File narFile = metadata.getArchivePath().toAbsolutePath().toFile(); NarClassLoader ncl = NarClassLoaderBuilder.builder().narFile(narFile).parentClassLoader(AdditionalServlet.class.getClassLoader()).extractionDirectory(narExtractionDirectory).build(); AdditionalServletDefinition def = getAdditionalServletDefinition(ncl); if (StringUtils.isBlank(def.getAdditionalServletClass())) { throw new IOException((("Additional servlets `" + def.getName()) + "` does NOT provide an ") + "additional servlets implementation"); } try { Class additionalServletClass = ncl.loadClass(def.getAdditionalServletClass()); Object additionalServlet = additionalServletClass.getDeclaredConstructor().newInstance(); if (!(additionalServlet instanceof AdditionalServlet)) { throw new IOException(("Class " + def.getAdditionalServletClass()) + " does not implement additional servlet interface"); } AdditionalServlet servlet = ((AdditionalServlet) (additionalServlet)); return new AdditionalServletWithClassLoader(servlet, ncl); } catch (Throwable t) { rethrowIOException(t); return null; } }
3.26
pulsar_AdditionalServletUtils_getAdditionalServletDefinition_rdh
/** * Retrieve the additional servlet definition from the provided nar package. * * @param narPath * the path to the additional servlet NAR package * @return the additional servlet definition * @throws IOException * when fail to load the additional servlet or get the definition */ public AdditionalServletDefinition getAdditionalServletDefinition(String narPath, String narExtractionDirectory) throws IOException { try (NarClassLoader ncl = NarClassLoaderBuilder.builder().narFile(new File(narPath)).extractionDirectory(narExtractionDirectory).build()) { return getAdditionalServletDefinition(ncl); } }
3.26
pulsar_AdditionalServletUtils_searchForServlets_rdh
/** * Search and load the available additional servlets. * * @param additionalServletDirectory * the directory where all the additional servlets are stored * @return a collection of additional servlet definitions * @throws IOException * when fail to load the available additional servlets from the provided directory. */ public AdditionalServletDefinitions searchForServlets(String additionalServletDirectory, String narExtractionDirectory) throws IOException { Path path = Paths.get(additionalServletDirectory).toAbsolutePath(); log.info("Searching for additional servlets in {}", path); AdditionalServletDefinitions servletDefinitions = new AdditionalServletDefinitions(); if (!path.toFile().exists()) { log.warn("Pulsar additional servlets directory not found"); return servletDefinitions; } try (DirectoryStream<Path> stream = Files.newDirectoryStream(path, "*.nar")) { for (Path archive : stream) {try { AdditionalServletDefinition def = AdditionalServletUtils.getAdditionalServletDefinition(archive.toString(), narExtractionDirectory); log.info("Found additional servlet from {} : {}", archive, def); checkArgument(StringUtils.isNotBlank(def.getName())); checkArgument(StringUtils.isNotBlank(def.getAdditionalServletClass())); AdditionalServletMetadata metadata = new AdditionalServletMetadata(); metadata.setDefinition(def); metadata.setArchivePath(archive); servletDefinitions.servlets().put(def.getName(), metadata); } catch (Throwable t) { log.warn((("Failed to load additional servlet from {}." + " It is OK however if you want to use this additional servlet,") + " please make sure you put the correct additional servlet NAR") + " package in the additional servlets directory.", archive, t); } } } return servletDefinitions; }
3.26
pulsar_PulsarMetadata_getPulsarColumns_rdh
/** * Convert pulsar schema into presto table metadata. */ @VisibleForTesting public List<ColumnMetadata> getPulsarColumns(TopicName topicName, SchemaInfo schemaInfo, boolean withInternalColumns, PulsarColumnHandle.HandleKeyValueType handleKeyValueType) { SchemaType schemaType = schemaInfo.getType(); if (schemaType.isStruct() || schemaType.isPrimitive()) { return getPulsarColumnsFromSchema(topicName, schemaInfo, withInternalColumns, handleKeyValueType); } else if (schemaType.equals(SchemaType.KEY_VALUE)) {return getPulsarColumnsFromKeyValueSchema(topicName, schemaInfo, withInternalColumns); } else { throw new IllegalArgumentException("Unsupported schema : " + schemaInfo); } }
3.26
pulsar_PulsarAvroRowDecoder_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) { GenericRecord avroRecord; try { GenericAvroRecord record = ((GenericAvroRecord) (genericAvroSchema.decode(byteBuf))); avroRecord = record.getAvroRecord(); } catch (Exception e) { e.printStackTrace(); throw new TrinoException(GENERIC_INTERNAL_ERROR, "Decoding avro record failed.", e); } return Optional.of(columnDecoders.entrySet().stream().collect(toImmutableMap(Map.Entry::getKey, entry -> entry.getValue().decodeField(avroRecord)))); }
3.26
pulsar_AuthenticationState_refreshAuthentication_rdh
/** * If the authentication state supports refreshing and the credentials are expired, * the auth provider will call this method to initiate the refresh process. * <p> * The auth state here will return the broker side data that will be used to send * a challenge to the client. * * @return the {@link AuthData} for the broker challenge to client * @throws AuthenticationException */ default AuthData refreshAuthentication() throws AuthenticationException { return AuthData.REFRESH_AUTH_DATA; }
3.26
pulsar_AuthenticationState_isExpired_rdh
/** * If the authentication state is expired, it will force the connection to be re-authenticated. */ default boolean isExpired() { return false; }
3.26
pulsar_AuthenticationState_getStateId_rdh
/** * Get AuthenticationState ID. */ default long getStateId() { return -1L; }
3.26
pulsar_AuthenticationState_m1_rdh
/** * Challenge passed in auth data. If authentication is complete after the execution of this method, return null. * Otherwise, return response data to be sent to the client. * * <p>Note: the implementation of {@link AuthenticationState#authenticate(AuthData)} converted a null result into a * zero length byte array when {@link AuthenticationState#isComplete()} returned false after authentication. In * order to simplify this interface, the determination of whether to send a challenge back to the client is only * based on the result of this method. In order to maintain backwards compatibility, the default implementation of * this method calls {@link AuthenticationState#isComplete()} and returns a result compliant with the new * paradigm.</p> */ default CompletableFuture<AuthData> m1(AuthData authData) { try { AuthData result = this.m0(authData); if (isComplete()) { return CompletableFuture.completedFuture(null); } else { return result != null ? CompletableFuture.completedFuture(result) : CompletableFuture.completedFuture(AuthData.of(new byte[0])); } } catch (Exception e) { return FutureUtil.failedFuture(e); } }
3.26
pulsar_OwnedBundle_handleUnloadRequest_rdh
/** * It unloads the bundle by closing all topics concurrently under this bundle. * * <pre> * a. disable bundle ownership in memory and not in zk * b. close all the topics concurrently * c. delete ownership znode from zookeeper. * </pre> * * @param pulsar * @param timeout * timeout for unloading bundle. It doesn't throw exception if it times out while waiting on closing all * topics * @param timeoutUnit * @throws Exception */ public CompletableFuture<Void> handleUnloadRequest(PulsarService pulsar, long timeout, TimeUnit timeoutUnit) { return handleUnloadRequest(pulsar, timeout, timeoutUnit, true); }
3.26
pulsar_OwnedBundle_isActive_rdh
/** * Access method to the namespace state to check whether the namespace is active or not. * * @return boolean value indicate that the namespace is active or not. */ public boolean isActive() { return IS_ACTIVE_UPDATER.get(this) == TRUE;}
3.26
pulsar_OwnedBundle_getNamespaceBundle_rdh
/** * Access to the namespace name. * * @return NamespaceName */ public NamespaceBundle getNamespaceBundle() { return this.f0; }
3.26
pulsar_MessageUtils_messageConverter_rdh
/** * Message convert to FlatMessage. * * @param message * @return FlatMessage List */ public static List<FlatMessage> messageConverter(Message message) { try { if (message == null) { return null; } List<FlatMessage> flatMessages = new ArrayList<>(); List<CanalEntry.Entry> entrys = null; if (message.isRaw()) { List<ByteString> rawEntries = message.getRawEntries(); entrys = new ArrayList<CanalEntry.Entry>(rawEntries.size()); for (ByteString byteString : rawEntries) { CanalEntry.Entry entry = CanalEntry.Entry.parseFrom(byteString); entrys.add(entry); } } else { entrys = message.getEntries(); } for (CanalEntry.Entry entry : entrys) {if ((entry.getEntryType() == EntryType.TRANSACTIONBEGIN) || (entry.getEntryType() == EntryType.TRANSACTIONEND)) { continue; } CanalEntry.RowChange rowChange; try { rowChange = CanalEntry.RowChange.parseFrom(entry.getStoreValue()); } catch (Exception e) { throw new RuntimeException("ERROR ## parser of eromanga-event has an error, data:" + entry.toString(), e); } CanalEntry.EventType eventType = rowChange.getEventType(); FlatMessage flatMessage = new FlatMessage(message.getId()); flatMessages.add(flatMessage); flatMessage.setDatabase(entry.getHeader().getSchemaName()); flatMessage.setTable(entry.getHeader().getTableName()); flatMessage.setIsDdl(rowChange.getIsDdl()); flatMessage.setType(eventType.toString()); flatMessage.setEs(entry.getHeader().getExecuteTime()); flatMessage.setTs(System.currentTimeMillis()); flatMessage.setSql(rowChange.getSql()); if (!rowChange.getIsDdl()) {List<Map<String, String>> data = new ArrayList<>(); List<Map<String, String>> old = new ArrayList<>(); for (CanalEntry.RowData rowData : rowChange.getRowDatasList()) { if (((eventType != EventType.INSERT) && (eventType != EventType.UPDATE)) && (eventType != EventType.DELETE)) {continue; } List<CanalEntry.Column> columns; if (eventType == EventType.DELETE) { columns = rowData.getBeforeColumnsList(); } else { columns = rowData.getAfterColumnsList(); } columns.size(); for (CanalEntry.Column column : columns) { Map<String, String> row = genColumn(column); if (column.getUpdated()) { row.put("updated", "1");} else { row.put("updated", "0"); } data.add(row); } if (eventType == EventType.UPDATE) { for (CanalEntry.Column column : rowData.getBeforeColumnsList()) { Map<String, String> rowOld = genColumn(column); old.add(rowOld); } } } if (!data.isEmpty()) { flatMessage.setData(data);} if (!old.isEmpty()) { flatMessage.setOld(old); } } } return flatMessages; } catch (Exception e) {throw new RuntimeException(e); } }
3.26
pulsar_ProducerInterceptors_onSendAcknowledgement_rdh
/** * This method is called when the message send to the broker has been acknowledged, or when sending the record fails * before it gets send to the broker. * This method calls {@link ProducerInterceptor#onSendAcknowledgement(Producer, Message, MessageId, Throwable)} * method for each interceptor. * * This method does not throw exceptions. Exceptions thrown by any of interceptor methods are caught and ignored. * * @param producer * the producer which contains the interceptor. * @param message * The message returned from the last interceptor is returned from * {@link ProducerInterceptor#beforeSend(Producer, Message)} * @param msgId * The message id that broker returned. Null if has error occurred. * @param exception * The exception thrown during processing of this message. Null if no error occurred. */ public void onSendAcknowledgement(Producer producer, Message message, MessageId msgId, Throwable exception) { for (ProducerInterceptor interceptor : interceptors) { if (!interceptor.eligible(message)) { continue; } try { interceptor.onSendAcknowledgement(producer, message, msgId, exception); } catch (Throwable e) {log.warn("Error executing interceptor onSendAcknowledgement callback ", e); } } }
3.26
pulsar_ProducerInterceptors_beforeSend_rdh
/** * This is called when client sends message to pulsar broker, before key and value gets serialized. * The method calls {@link ProducerInterceptor#beforeSend(Producer,Message)} method. Message returned from * first interceptor's beforeSend() is passed to the second interceptor beforeSend(), and so on in the * interceptor chain. The message returned from the last interceptor is returned from this method. * * This method does not throw exceptions. Exceptions thrown by any interceptor methods are caught and ignored. * If a interceptor in the middle of the chain, that normally modifies the message, throws an exception, * the next interceptor in the chain will be called with a message returned by the previous interceptor that did * not throw an exception. * * @param producer * the producer which contains the interceptor. * @param message * the message from client * @return the message to send to topic/partition */ public Message beforeSend(Producer producer, Message message) { Message interceptorMessage = message; for (ProducerInterceptor interceptor : interceptors) { if (!interceptor.eligible(message)) { continue; } try { interceptorMessage = interceptor.beforeSend(producer, interceptorMessage); } catch (Throwable e) { if (producer != null) { log.warn("Error executing interceptor beforeSend callback for topicName:{} ", producer.getTopic(), e); } else { log.warn("Error Error executing interceptor beforeSend callback ", e); } } } return interceptorMessage; }
3.26
pulsar_BatchSource_readNext_rdh
/** * Read data and return a record. * Return null if no more records are present for this task * * @return a record */ Record<T> readNext() throws Exception { }
3.26
pulsar_ManagedLedgerConfig_getClock_rdh
/** * Get clock to use to time operations. * * @return a clock */ public Clock getClock() { return clock; }
3.26
pulsar_ManagedLedgerConfig_getMaxBacklogBetweenCursorsForCaching_rdh
/** * Max backlog gap between backlogged cursors while caching to avoid caching entry which can be * invalidated before other backlog cursor can reuse it from cache. * * @return */ public int getMaxBacklogBetweenCursorsForCaching() { return maxBacklogBetweenCursorsForCaching; }
3.26
pulsar_ManagedLedgerConfig_getAckQuorumSize_rdh
/** * * @return the ackQuorumSize */ public int getAckQuorumSize() { return f0; }
3.26
pulsar_ManagedLedgerConfig_isAutoSkipNonRecoverableData_rdh
/** * Skip reading non-recoverable/unreadable data-ledger under managed-ledger's list. It helps when data-ledgers gets * corrupted at bookkeeper and managed-cursor is stuck at that ledger. */public boolean isAutoSkipNonRecoverableData() { return autoSkipNonRecoverableData; }
3.26
pulsar_ManagedLedgerConfig_getMaxBatchDeletedIndexToPersist_rdh
/** * * @return max batch deleted index that will be persisted and recoverd. */public int getMaxBatchDeletedIndexToPersist() { return maxBatchDeletedIndexToPersist; }
3.26
pulsar_ManagedLedgerConfig_setWriteQuorumSize_rdh
/** * * @param writeQuorumSize * the writeQuorumSize to set */ public ManagedLedgerConfig setWriteQuorumSize(int writeQuorumSize) { this.writeQuorumSize = writeQuorumSize; return this; }
3.26
pulsar_ManagedLedgerConfig_isUnackedRangesOpenCacheSetEnabled_rdh
/** * should use {@link ConcurrentOpenLongPairRangeSet} to store unacked ranges. * * @return */ public boolean isUnackedRangesOpenCacheSetEnabled() { return unackedRangesOpenCacheSetEnabled; }
3.26
pulsar_ManagedLedgerConfig_setRetentionSizeInMB_rdh
/** * The retention size is used to set a maximum retention size quota on the ManagedLedger. * <p> * Retention size and retention time ({@link #setRetentionTime(int, TimeUnit)}) are together used to retain the * ledger data when there are no cursors or when all the cursors have marked the data for deletion. * Data will be deleted in this case when both retention time and retention size settings don't prevent deleting * the data marked for deletion. * <p> * A retention size of 0 (default) will make data to be deleted immediately. * <p> * A retention size of -1, means to have an unlimited retention size. * * @param retentionSizeInMB * quota for message retention */ public ManagedLedgerConfig setRetentionSizeInMB(long retentionSizeInMB) { this.retentionSizeInMB = retentionSizeInMB; return this; }
3.26
pulsar_ManagedLedgerConfig_getDigestType_rdh
/** * * @return the digestType */ public DigestType getDigestType() { return digestType; }
3.26
pulsar_ManagedLedgerConfig_m1_rdh
/** * * @return the writeQuorumSize */ public int m1() { return writeQuorumSize; }
3.26
pulsar_ManagedLedgerConfig_getMetadataOperationsTimeoutSeconds_rdh
/** * Ledger-Op (Create/Delete) timeout. * * @return */ public long getMetadataOperationsTimeoutSeconds() { return metadataOperationsTimeoutSeconds; }
3.26
pulsar_ManagedLedgerConfig_setMinimumBacklogEntriesForCaching_rdh
/** * Set Minimum backlog after that broker will start caching backlog reads. * * @param minimumBacklogEntriesForCaching */ public void setMinimumBacklogEntriesForCaching(int minimumBacklogEntriesForCaching) { this.minimumBacklogEntriesForCaching = minimumBacklogEntriesForCaching; }
3.26
pulsar_ManagedLedgerConfig_setReadEntryTimeoutSeconds_rdh
/** * Ledger read entry timeout after which callback will be completed with failure. (disable timeout by setting. * readTimeoutSeconds <= 0) * * @param readEntryTimeoutSeconds * @return */ public ManagedLedgerConfig setReadEntryTimeoutSeconds(long readEntryTimeoutSeconds) { this.readEntryTimeoutSeconds = readEntryTimeoutSeconds; return this; }
3.26
pulsar_ManagedLedgerConfig_getMetadataEnsemblesize_rdh
/** * * @return the metadataEnsemblesize */ public int getMetadataEnsemblesize() {return metadataEnsembleSize; }
3.26
pulsar_ManagedLedgerConfig_getMetadataMaxEntriesPerLedger_rdh
/** * * @return the metadataMaxEntriesPerLedger */ public int getMetadataMaxEntriesPerLedger() { return metadataMaxEntriesPerLedger; }
3.26
pulsar_ManagedLedgerConfig_getMaxUnackedRangesToPersist_rdh
/** * * @return max unacked message ranges that will be persisted and recovered. */ public int getMaxUnackedRangesToPersist() { return maxUnackedRangesToPersist; }
3.26
pulsar_ManagedLedgerConfig_getMaxEntriesPerLedger_rdh
/** * * @return the maxEntriesPerLedger */ public int getMaxEntriesPerLedger() { return maxEntriesPerLedger; }
3.26
pulsar_ManagedLedgerConfig_setMaxUnackedRangesToPersist_rdh
/** * * @param maxUnackedRangesToPersist * max unacked message ranges that will be persisted and receverd. */ public ManagedLedgerConfig setMaxUnackedRangesToPersist(int maxUnackedRangesToPersist) { this.maxUnackedRangesToPersist = maxUnackedRangesToPersist; return this; }
3.26
pulsar_ManagedLedgerConfig_getMaxSizePerLedgerMb_rdh
/** * * @return the maxSizePerLedgerMb */ public int getMaxSizePerLedgerMb() { return maxSizePerLedgerMb; }
3.26
pulsar_ManagedLedgerConfig_setMetadataAckQuorumSize_rdh
/** * * @param metadataAckQuorumSize * the metadataAckQuorumSize to set */ public ManagedLedgerConfig setMetadataAckQuorumSize(int metadataAckQuorumSize) { this.metadataAckQuorumSize = metadataAckQuorumSize; return this; }
3.26
pulsar_ManagedLedgerConfig_getRetentionSizeInMB_rdh
/** * * @return quota for message retention */public long getRetentionSizeInMB() { return retentionSizeInMB; }
3.26
pulsar_ManagedLedgerConfig_setMetadataMaxEntriesPerLedger_rdh
/** * * @param metadataMaxEntriesPerLedger * the metadataMaxEntriesPerLedger to set */ public ManagedLedgerConfig setMetadataMaxEntriesPerLedger(int metadataMaxEntriesPerLedger) { this.metadataMaxEntriesPerLedger = metadataMaxEntriesPerLedger; return this; }
3.26
pulsar_ManagedLedgerConfig_m0_rdh
/** * * @return the maximum rollover time. */ public long m0() { return maximumRolloverTimeMs; }
3.26
pulsar_ManagedLedgerConfig_getLedgerOffloader_rdh
/** * Get ledger offloader which will be used to offload ledgers to longterm storage. * * The default offloader throws an exception on any attempt to offload. * * @return a ledger offloader */ public LedgerOffloader getLedgerOffloader() { return ledgerOffloader; }
3.26
pulsar_ManagedLedgerConfig_setMaxBacklogBetweenCursorsForCaching_rdh
/** * Set maximum backlog distance between backlogged curosr to avoid caching unused entry. * * @param maxBacklogBetweenCursorsForCaching */ public void setMaxBacklogBetweenCursorsForCaching(int maxBacklogBetweenCursorsForCaching) { this.maxBacklogBetweenCursorsForCaching = maxBacklogBetweenCursorsForCaching; }
3.26
pulsar_ManagedLedgerConfig_setLedgerOffloader_rdh
/** * Set ledger offloader to use for offloading ledgers to longterm storage. * * @param offloader * the ledger offloader to use */ public ManagedLedgerConfig setLedgerOffloader(LedgerOffloader offloader) { this.ledgerOffloader = offloader; return this; }
3.26
pulsar_ManagedLedgerConfig_getPassword_rdh
/** * * @return the password */ public byte[] getPassword() { return Arrays.copyOf(password, password.length); }
3.26
pulsar_ManagedLedgerConfig_getMetadataAckQuorumSize_rdh
/** * * @return the metadataAckQuorumSize */ public int getMetadataAckQuorumSize() { return metadataAckQuorumSize; }
3.26
pulsar_ManagedLedgerConfig_setMaximumRolloverTime_rdh
/** * Set the maximum rollover time for ledgers in this managed ledger. * * <p/>If the ledger is not rolled over until this time, even if it has not reached the number of entry or size * limit, this setting will trigger rollover. This parameter can be used for topics with low request rate to force * rollover, so recovery failure does not have to go far back. * * @param maximumRolloverTime * the maximum rollover time * @param unit * the time unit */ public void setMaximumRolloverTime(int maximumRolloverTime, TimeUnit unit) { this.maximumRolloverTimeMs = unit.toMillis(maximumRolloverTime); checkArgument(maximumRolloverTimeMs >= minimumRolloverTimeMs, "Maximum rollover time needs to be greater than minimum rollover time"); }
3.26
pulsar_ManagedLedgerConfig_getReadEntryTimeoutSeconds_rdh
/** * Ledger read-entry timeout. * * @return */ public long getReadEntryTimeoutSeconds() { return readEntryTimeoutSeconds; }
3.26
pulsar_ManagedLedgerConfig_getLedgerRolloverTimeout_rdh
/** * * @return the ledgerRolloverTimeout */ public int getLedgerRolloverTimeout() { return ledgerRolloverTimeout; }
3.26
pulsar_ManagedLedgerConfig_m2_rdh
/** * * @return the metadataWriteQuorumSize */ public int m2() { return metadataWriteQuorumSize; }
3.26
pulsar_ManagedLedgerConfig_setAddEntryTimeoutSeconds_rdh
/** * Add-entry timeout after which add-entry callback will be failed if add-entry is not succeeded. * * @param addEntryTimeoutSeconds */ public ManagedLedgerConfig setAddEntryTimeoutSeconds(long addEntryTimeoutSeconds) { this.addEntryTimeoutSeconds = addEntryTimeoutSeconds; return this; }
3.26
pulsar_ManagedLedgerConfig_setClock_rdh
/** * Set clock to use for time operations. * * @param clock * the clock to use */ public ManagedLedgerConfig setClock(Clock clock) { this.clock = clock; return this; }
3.26
pulsar_ManagedLedgerConfig_getBookKeeperEnsemblePlacementPolicyClassName_rdh
/** * Managed-ledger can setup different custom EnsemblePlacementPolicy (eg: affinity to write ledgers to only setup of * group of bookies). * * @return */ public Class<? extends EnsemblePlacementPolicy> getBookKeeperEnsemblePlacementPolicyClassName() { return bookKeeperEnsemblePlacementPolicyClassName; }
3.26
pulsar_ManagedLedgerConfig_setAckQuorumSize_rdh
/** * * @param ackQuorumSize * the ackQuorumSize to set */ public ManagedLedgerConfig setAckQuorumSize(int ackQuorumSize) { this.f0 = ackQuorumSize; return this; }
3.26
pulsar_ManagedLedgerConfig_getBookKeeperEnsemblePlacementPolicyProperties_rdh
/** * Returns properties required by configured bookKeeperEnsemblePlacementPolicy. * * @return */ public Map<String, Object> getBookKeeperEnsemblePlacementPolicyProperties() {return bookKeeperEnsemblePlacementPolicyProperties;}
3.26
pulsar_ManagedLedgerConfig_getThrottleMarkDelete_rdh
/** * * @return the throttling rate limit for mark-delete calls */ public double getThrottleMarkDelete() { return throttleMarkDelete; }
3.26
pulsar_ManagedLedgerConfig_getMinimumBacklogCursorsForCaching_rdh
/** * Minimum cursors with backlog after which broker is allowed to cache read entries to reuse them for other cursors' * backlog reads. (Default = 0, broker will not cache backlog reads) * * @return */ public int getMinimumBacklogCursorsForCaching() { return minimumBacklogCursorsForCaching; }
3.26
pulsar_ManagedLedgerConfig_setLedgerRolloverTimeout_rdh
/** * * @param ledgerRolloverTimeout * the ledgerRolloverTimeout to set */ public ManagedLedgerConfig setLedgerRolloverTimeout(int ledgerRolloverTimeout) { this.ledgerRolloverTimeout = ledgerRolloverTimeout; return this; }
3.26
pulsar_ManagedLedgerConfig_setBookKeeperEnsemblePlacementPolicyClassName_rdh
/** * Returns EnsemblePlacementPolicy configured for the Managed-ledger. * * @param bookKeeperEnsemblePlacementPolicyClassName */ public void setBookKeeperEnsemblePlacementPolicyClassName(Class<? extends EnsemblePlacementPolicy> bookKeeperEnsemblePlacementPolicyClassName) { this.bookKeeperEnsemblePlacementPolicyClassName = bookKeeperEnsemblePlacementPolicyClassName; }
3.26
pulsar_ManagedLedgerConfig_setDigestType_rdh
/** * * @param digestType * the digestType to set */ public ManagedLedgerConfig setDigestType(DigestType digestType) { this.digestType = digestType; return this; }
3.26
pulsar_ManagedLedgerConfig_isLazyCursorRecovery_rdh
/** * * @return the lazyCursorRecovery */ public boolean isLazyCursorRecovery() { return lazyCursorRecovery; }
3.26
pulsar_ManagedLedgerConfig_getEnsembleSize_rdh
/** * * @return the ensembleSize */ public int getEnsembleSize() { return ensembleSize; }
3.26
pulsar_ManagedLedgerConfig_setMaxEntriesPerLedger_rdh
/** * * @param maxEntriesPerLedger * the maxEntriesPerLedger to set */ public ManagedLedgerConfig setMaxEntriesPerLedger(int maxEntriesPerLedger) { this.maxEntriesPerLedger = maxEntriesPerLedger; return this; }
3.26
pulsar_ManagedLedgerConfig_setMetadataOperationsTimeoutSeconds_rdh
/** * Ledger-Op (Create/Delete) timeout after which callback will be completed with failure. * * @param metadataOperationsTimeoutSeconds */ public ManagedLedgerConfig setMetadataOperationsTimeoutSeconds(long metadataOperationsTimeoutSeconds) { this.metadataOperationsTimeoutSeconds = metadataOperationsTimeoutSeconds; return this; }
3.26
pulsar_ManagedLedgerConfig_setMaxSizePerLedgerMb_rdh
/** * * @param maxSizePerLedgerMb * the maxSizePerLedgerMb to set */ public ManagedLedgerConfig setMaxSizePerLedgerMb(int maxSizePerLedgerMb) { this.maxSizePerLedgerMb = maxSizePerLedgerMb; return this; }
3.26
pulsar_ManagedLedgerConfig_getRetentionTimeMillis_rdh
/** * * @return duration for which messages are retained */ public long getRetentionTimeMillis() { return retentionTimeMs; }
3.26
pulsar_ManagedLedgerConfig_setMetadataEnsembleSize_rdh
/** * * @param metadataEnsembleSize * the metadataEnsembleSize to set */ public ManagedLedgerConfig setMetadataEnsembleSize(int metadataEnsembleSize) { this.metadataEnsembleSize = metadataEnsembleSize; return this;}
3.26
pulsar_ManagedLedgerConfig_getMaxUnackedRangesToPersistInMetadataStore_rdh
/** * * @return max unacked message ranges up to which it can store in Zookeeper */ public int getMaxUnackedRangesToPersistInMetadataStore() { return maxUnackedRangesToPersistInMetadataStore; }
3.26
pulsar_ManagedLedgerConfig_setInactiveLedgerRollOverTime_rdh
/** * Set rollOver time for inactive ledgers. * * @param inactiveLedgerRollOverTimeMs * @param unit */ public void setInactiveLedgerRollOverTime(int inactiveLedgerRollOverTimeMs, TimeUnit unit) { this.inactiveLedgerRollOverTimeMs = ((int) (unit.toMillis(inactiveLedgerRollOverTimeMs))); }
3.26
pulsar_ManagedLedgerConfig_setMetadataWriteQuorumSize_rdh
/** * * @param metadataWriteQuorumSize * the metadataWriteQuorumSize to set */ public ManagedLedgerConfig setMetadataWriteQuorumSize(int metadataWriteQuorumSize) { this.metadataWriteQuorumSize = metadataWriteQuorumSize; return this; }
3.26
pulsar_ManagedLedgerConfig_getMinimumRolloverTimeMs_rdh
/** * * @return the minimum rollover time */ public int getMinimumRolloverTimeMs() {return minimumRolloverTimeMs; }
3.26
pulsar_ManagedLedgerConfig_setPassword_rdh
/** * * @param password * the password to set */ public ManagedLedgerConfig setPassword(String password) { this.password = password.getBytes(StandardCharsets.UTF_8); return this; }
3.26
pulsar_ManagedLedgerConfig_getMinimumBacklogEntriesForCaching_rdh
/** * Minimum backlog should exist to leverage caching for backlog reads. * * @return */ public int getMinimumBacklogEntriesForCaching() { return minimumBacklogEntriesForCaching; }
3.26
pulsar_ManagedLedgerConfig_m3_rdh
/** * Managed-ledger can setup different custom EnsemblePlacementPolicy which needs * bookKeeperEnsemblePlacementPolicy-Properties. * * @param bookKeeperEnsemblePlacementPolicyProperties */public void m3(Map<String, Object> bookKeeperEnsemblePlacementPolicyProperties) {this.bookKeeperEnsemblePlacementPolicyProperties = bookKeeperEnsemblePlacementPolicyProperties; }
3.26
pulsar_ManagedLedgerConfig_setMinimumRolloverTime_rdh
/** * Set the minimum rollover time for ledgers in this managed ledger. * * <p/>If this time is > 0, a ledger will not be rolled over more frequently than the specified time, even if it has * reached the maximum number of entries or maximum size. This parameter can be used to reduce the amount of * rollovers on managed ledger with high write throughput. * * @param minimumRolloverTime * the minimum rollover time * @param unit * the time unit */ public void setMinimumRolloverTime(int minimumRolloverTime, TimeUnit unit) { this.minimumRolloverTimeMs = ((int) (unit.toMillis(minimumRolloverTime))); checkArgument(maximumRolloverTimeMs >= minimumRolloverTimeMs, "Minimum rollover time needs to be less than maximum rollover time"); }
3.26
pulsar_ManagedLedgerConfig_setEnsembleSize_rdh
/** * * @param ensembleSize * the ensembleSize to set */ public ManagedLedgerConfig setEnsembleSize(int ensembleSize) { this.ensembleSize = ensembleSize; return this; }
3.26
pulsar_ManagedLedgerConfig_setLazyCursorRecovery_rdh
/** * Whether to recover cursors lazily when trying to recover a * managed ledger backing a persistent topic. It can improve write availability of topics. * The caveat is now when recovered ledger is ready to write we're not sure if all old consumers last mark * delete position can be recovered or not. * * @param lazyCursorRecovery * if enable lazy cursor recovery. */ public ManagedLedgerConfig setLazyCursorRecovery(boolean lazyCursorRecovery) { this.lazyCursorRecovery = lazyCursorRecovery; return this; }
3.26
pulsar_ManagedLedgerConfig_setRetentionTime_rdh
/** * Set the retention time for the ManagedLedger. * <p> * Retention time and retention size ({@link #setRetentionSizeInMB(long)}) are together used to retain the * ledger data when there are no cursors or when all the cursors have marked the data for deletion. * Data will be deleted in this case when both retention time and retention size settings don't prevent deleting * the data marked for deletion. * <p> * A retention time of 0 (default) will make data to be deleted immediately. * <p> * A retention time of -1, means to have an unlimited retention time. * * @param retentionTime * duration for which messages should be retained * @param unit * time unit for retention time */ public ManagedLedgerConfig setRetentionTime(int retentionTime, TimeUnit unit) { this.retentionTimeMs = unit.toMillis(retentionTime); return this; }
3.26