Sample

int-5c1b0abcf56b-I13

Lower every eligible classic and enhanced for loop to a while loop

Matched original source

Lines167

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Scalabrino0.5360–1; higher is more readable
Dorn0.090–1; higher is more readable
Mi0.1190–1; higher is more readable
LLOC53Logical lines; fewer is more readable
DeepSeek V4 Pro11.670–20; mean of three runs
GPT-6.1 Sol160–20; mean of three runs
BTTF0.3070–1; higher is more readable

Views

Source code

package org.apache.kafka.connect.cli; import org.apache.kafka.common.utils.Time; import org.apache.kafka.common.utils.Utils; import org.apache.kafka.common.utils.internals.Exit; import org.apache.kafka.connect.connector.policy.ConnectorClientConfigOverridePolicy; import org.apache.kafka.connect.errors.ConnectException; import org.apache.kafka.connect.json.JsonConverter; import org.apache.kafka.connect.json.JsonConverterConfig; import org.apache.kafka.connect.runtime.Connect; import org.apache.kafka.connect.runtime.Herder; import org.apache.kafka.connect.runtime.Worker; import org.apache.kafka.connect.runtime.isolation.Plugins; import org.apache.kafka.connect.runtime.rest.RestClient; import org.apache.kafka.connect.runtime.rest.RestServer; import org.apache.kafka.connect.runtime.rest.entities.ConnectorInfo; import org.apache.kafka.connect.runtime.rest.entities.CreateConnectorRequest; import org.apache.kafka.connect.runtime.standalone.StandaloneConfig; import org.apache.kafka.connect.runtime.standalone.StandaloneHerder; import org.apache.kafka.connect.storage.FileOffsetBackingStore; import org.apache.kafka.connect.storage.OffsetBackingStore; import org.apache.kafka.connect.util.FutureCallback; import com.fasterxml.jackson.core.exc.StreamReadException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DatabindException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.Map; import static org.apache.kafka.connect.runtime.ConnectorConfig.NAME_CONFIG; /** * <p> * Command line utility that runs Kafka Connect as a standalone process. In this mode, work (connectors and tasks) is not * distributed. Instead, all the normal Connect machinery works within a single process. This is useful for ad hoc, * small, or experimental jobs. * </p> * <p> * Connector and task configs are stored in memory and are not persistent. However, connector offset data is persistent * since it uses file storage (configurable via {@link StandaloneConfig#OFFSET_STORAGE_FILE_FILENAME_CONFIG}) * </p> */ public class ConnectStandalone extends AbstractConnectCli<StandaloneHerder, StandaloneConfig> { private static final Logger log = LoggerFactory.getLogger(ConnectStandalone.class); public ConnectStandalone(String... args) { super(args); } @Override protected String usage() { return "ConnectStandalone worker.properties [connector1.properties connector2.json ...]"; } @Override public void processExtraArgs(Connect<StandaloneHerder> connect, String[] extraArgs) { try { { String[] loopArray = extraArgs; int loopIndex = 0; while (loopIndex < loopArray.length) { final String connectorConfigFile = loopArray[loopIndex++]; CreateConnectorRequest createConnectorRequest = parseConnectorConfigurationFile(connectorConfigFile); FutureCallback<Herder.Created<ConnectorInfo>> cb = new FutureCallback<>((error, info) -> { if (error != null) log.error("Failed to create connector for {}", connectorConfigFile); else log.info("Created connector {}", info.result().name()); }); connect.herder().putConnectorConfig( createConnectorRequest.name(), createConnectorRequest.config(), createConnectorRequest.initialTargetState(), false, cb); cb.get(); } } connect.herder().ready(); } catch (Throwable t) { log.error("Stopping after connector error", t); connect.stop(); Exit.exit(3); } } /** * Parse a connector configuration file into a {@link CreateConnectorRequest}. The file can have any one of the following formats (note that * we attempt to parse the file in this order): * <ol> * <li>A JSON file containing an Object with only String keys and values that represent the connector configuration.</li> * <li>A JSON file containing an Object that can be parsed directly into a {@link CreateConnectorRequest}</li> * <li>A valid Java Properties file (i.e. containing String key/value pairs representing the connector configuration)</li> * </ol> * <p> * Visible for testing. * * @param filePath the path of the connector configuration file * @return the parsed connector configuration in the form of a {@link CreateConnectorRequest} */ CreateConnectorRequest parseConnectorConfigurationFile(String filePath) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); File connectorConfigurationFile = Paths.get(filePath).toFile(); try { Map<String, String> connectorConfigs = objectMapper.readValue(connectorConfigurationFile, new TypeReference<>() { }); if (!connectorConfigs.containsKey(NAME_CONFIG)) { throw new ConnectException("Connector configuration at '" + filePath + "' is missing the mandatory '" + NAME_CONFIG + "' " + "configuration"); } return new CreateConnectorRequest(connectorConfigs.get(NAME_CONFIG), connectorConfigs, null); } catch (StreamReadException | DatabindException e) { log.debug("Could not parse connector configuration file '{}' into a Map with String keys and values", filePath); } try { objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); CreateConnectorRequest createConnectorRequest = objectMapper.readValue(connectorConfigurationFile, new TypeReference<>() { }); if (createConnectorRequest.config().containsKey(NAME_CONFIG)) { if (!createConnectorRequest.config().get(NAME_CONFIG).equals(createConnectorRequest.name())) { throw new ConnectException("Connector name configuration in 'config' doesn't match the one specified in 'name' at '" + filePath + "'"); } } else { createConnectorRequest.config().put(NAME_CONFIG, createConnectorRequest.name()); } return createConnectorRequest; } catch (StreamReadException | DatabindException e) { log.debug("Could not parse connector configuration file '{}' into an object of type {}", filePath, CreateConnectorRequest.class.getSimpleName()); } Map<String, String> connectorConfigs = Utils.propsToStringMap(Utils.loadProps(filePath)); if (!connectorConfigs.containsKey(NAME_CONFIG)) { throw new ConnectException("Connector configuration at '" + filePath + "' is missing the mandatory '" + NAME_CONFIG + "' " + "configuration"); } return new CreateConnectorRequest(connectorConfigs.get(NAME_CONFIG), connectorConfigs, null); } @Override protected StandaloneHerder createHerder(StandaloneConfig config, String workerId, Plugins plugins, ConnectorClientConfigOverridePolicy connectorClientConfigOverridePolicy, RestServer restServer, RestClient restClient) { OffsetBackingStore offsetBackingStore = new FileOffsetBackingStore(plugins.newInternalConverter( true, JsonConverter.class.getName(), Map.of(JsonConverterConfig.SCHEMAS_ENABLE_CONFIG, "false"))); offsetBackingStore.configure(config); Worker worker = new Worker(workerId, Time.SYSTEM, plugins, config, offsetBackingStore, connectorClientConfigOverridePolicy); return new StandaloneHerder(worker, config.kafkaClusterId(), connectorClientConfigOverridePolicy); } @Override protected StandaloneConfig createConfig(Map<String, String> workerProps) { return new StandaloneConfig(workerProps); } public static void main(String[] args) { ConnectStandalone connectStandalone = new ConnectStandalone(args); connectStandalone.run(); } }

Loading feature diagnosis…

Source regions

Feature contributions

Feature contributions

FeatureValueContribution
(log-odds)
Halstead volumeHow much symbolic information the code contains. It combines the total number of operators and values with the number of distinct ones.8568.021−282.745
Source linesThe number of non-empty source lines.167+66.8
Byte entropyHow varied the bytes in the source text are. Repeated bytes give a lower value; a more even mixture gives a higher value.4.722−7.083

Intercept 8.87 + feature contributions = -214.158 (log-odds).
Score = sigmoid(-214.158) = 0.

Score0.536

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.168−4.912
Indentation frequencyHow rapidly indentation changes from line to line.144+4.244
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.144−2.884
Identifier layout (horizontal)How rapidly the visual pattern of identifier characters changes from left to right. It measures spatial frequency, not the meaning of the names.146.976−2.56
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.166.973+1.924
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.146.952+1.567
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.072+0.24

Intercept 0.07 + feature contributions = -2.311 (log-odds).
Score = sigmoid(-2.311) = 0.09.

Score0.119
Score53
Run 1

The code is a mix of readable and problematic sections. The class structure and method breakdown are reasonably logical, but several issues hurt readability. The processExtraArgs method contains unnecessary nested blocks and a non-idiomatic while loop with manual index management, where a for-each would be clearer. Conditional blocks lack braces in places, creating merge risks and reduced clarity. Multiple actions are squeezed into single lines, especially in putConnectorConfig calls. The parseConnectorConfigurationFile method has a clear purpose but becomes lengthy, with three parse attempts that could be extracted or documented better. Variable names are mostly good, but the unusual loop style and extra nesting in processExtraArgs disrupt natural reading flow. The code would benefit significantly from cleaner iteration, consistent bracing, and breaking compound statements into separate lines for better granularity. The error handling is reasonable but adds length.

Run 2

The code is generally readable with clear intent, appropriate method decomposition, and useful Javadoc. The class structure is logical and methods like parseConnectorConfigurationFile are well-organized. However, there are notable readability issues: the processExtraArgs method contains an unnecessary nested block with a manual while loop using loopIndex and loopArray instead of a simpler for-each loop, which hurts clarity. The empty type references (new TypeReference<>() { }) are slightly ambiguous. Multi-line string concatenations in error messages are somewhat awkward. The createHerder method has a long parameter list that could be simplified. Overall, the code is maintainable but has some structural quirks that prevent a higher score.

Run 3

The code has reasonable method decomposition but contains significant readability issues. The processExtraArgs method has unnecessary nesting (redundant braces) and a contrived while-loop that mimics a for-loop with manual index management. Multiple actions are packed into single lines, and the lambda callback is dense. The parseConnectorConfigurationFile method is overly long and tries three parsing strategies in sequence with repeated error handling, making the flow difficult to follow. While imports are organized and class-level Javadoc is good, the method-level implementations lack clear separation of concerns. Variable names are generally descriptive, but the code would benefit from extracting helper methods, using standard for-each loops, and simplifying the JSON/properties parsing logic into smaller, focused methods.

Run 1

Code Structure: Well-separated methods organize CLI execution, configuration parsing, and runtime setup. Nesting: Mostly moderate, but the redundant block and indexed while loop in processExtraArgs add unnecessary depth; nested name validation could also be simplified. Clarity of intent: Descriptive names, documentation, and logging clearly explain responsibilities and parsing order, though the callback name cb is terse. Code length: Generally appropriate, but repeated mandatory-name checks and manual loop bookkeeping introduce avoidable verbosity. Action granularity: Most statements perform one action; indexing combined with incrementing slightly obscures iteration. Reading flow: Sequential parsing fallbacks and small setup methods provide a natural progression, but inconsistent indentation, tightly packed imports, long expressions, and omitted conditional braces reduce visual consistency.

Run 2

Code Structure: Well-separated methods organize CLI behavior, configuration parsing, and runtime creation; parsing fallbacks follow a documented order. Nesting: Mostly moderate, but the redundant block and manual while-loop bookkeeping in processExtraArgs add unnecessary depth, and connector-name validation uses nested conditionals. Clarity of intent: Descriptive names, useful Javadoc, and contextual logging make the purpose clear; the abbreviated callback variable cb is less expressive. Code length: Generally appropriate, though repeated mandatory-name validation and verbose loop setup could be simplified. Action granularity: Most statements perform one action, but array access combined with index increment slightly complicates reading. Reading flow: Startup and parsing sequences are natural, with early returns aiding comprehension; inconsistent indentation, tightly packed imports, and long expressions create minor friction.

Run 3

Code Structure: Well-separated methods organize CLI setup, connector creation, configuration parsing, and runtime construction. Nesting: Mostly moderate, but the redundant block and manual indexed loop in processExtraArgs add unnecessary depth; nested name validation could be flattened. Clarity of intent: Descriptive identifiers, useful documentation, and contextual logging make the purpose and parsing fallback order clear. Code length: Generally appropriate, although repeated mandatory-name validation and verbose loop scaffolding add avoidable length. Action granularity: Most statements perform one action, but array access combined with index increment slightly obscures iteration. Reading flow: Methods follow a logical lifecycle, and sequential parsing attempts are easy to follow. Inconsistent indentation, long signatures and expressions, ungrouped imports, and exception-driven fallbacks introduce minor friction.