auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
static Cleanable forResultSet(final ResultSet rs) { return () -> rs.close(); }

Target:
Meh: you could use `rs::close` instead of a lambda. They're semantically equivalent--I just like the way method handles look. Not critical for merge, obviously.. :)
Source:
protected String locateSql(final Handle h) { return h.getConfig(SqlObjects.class).getSqlLocator().locate(sqlObjectType, method); }

Target:
Meh: these methods could be package private
Source:
private JpaClass(Class<C> clazz) { logger.debug("init {}", clazz); this.members = unmodifiableList(new ArrayList<>(inspectClass(clazz))); logger.debug("init {}: members.", clazz, members.size()); }

Target:
this is somewhat redundant with the following log statement
Source:
public static <T> T open(DBI dbi, Class<T> sqlObjectType) { try { check(OPEN); return (T) OPEN.invoke(dbi, sqlObjectType); } catch (Throwable t) { throw new RuntimeException("Error during `SqlObjectBuilder.open` invocation", t); } }

Target:
this will wrap e.g. `UnableToOpenConnectionException` or other `DbiException` subclasses
Source:
<T, R> Collector<T, ?, R> createCollectorFor(Class<R> type) { for (CollectorFactory<?, ?, ?> factory : factories) { if (factory.accepts(type)) { return ((CollectorFactory<T, ?, R>) factory).newCollector(type); } } throw new IllegalStateException("No collector builder available for " + type.getName()); }

Target:
I know you are only mirroring how the existing registries work, but I wonder if it would make sense for these to either return a nullable type or an `Optional<Collector<...>>` so that lookups can be done without necessarily throwing an exception. If so, probably a change that should be done to the existing registries as well.
Source:
public void testFoo() throws Exception { assumeTrue(postgresIsInstalled); DAO dao = dbi.open(DAO.class); Long brian_id = dao.insert("Brian"); long keith_id = dao.insert("Keith"); assertThat(dao.findNameById(brian_id), equalTo("Brian")); assertThat(dao.findNameById(keith_id), equalTo("Keith")); dao.close(); }

Target:
Would this be better in the `@Before` ? Gets rid of the `if (!postgresIsInstalled)` blocks entirely, and should work just the same: https://github.com/junit-team/junit/wiki/Assumptions-with-assume
Source:
private void restoreAutoCommitState(final Handle handle) { try { final LocalStuff stuff = localStuff.remove(handle); if (stuff != null) { handle.getConnection().setAutoCommit(stuff.getInitialAutocommit()); stuff.getCheckpoints().clear(); } } catch (SQLException e) { throw new UnableToRestoreAutoCommitStateException(e); } finally { // prevent memory leak if rollback throws an exception if (localStuff.containsKey(handle)) { localStuff.remove(handle); } } }

Target:
Checking `containsKey` before calling `remove` is redundant and should be removed
Source:
public Map<String, Object> convertJobGrabToText(@RequestBody Graph graph) { Map<String, Object> response = new HashMap<String, Object>(); try { String dslText = graph.toDSLText(); response.put("text", dslText); } catch (JobSpecificationException jse) { response.put("error", jse.toExceptionDescriptor()); } catch (Throwable e) { response.put("error", e.toString()); } return response; }

Target:
For consistence with the statement higher up, use: `new HashMap<>();`
Source:
public static boolean isComposedJobDefinition(String definition){ String patternString = "(\\|\\|(?=([^\\\"']*[\\\"'][^\\\"']*[\\\"'])*[^\\\"']*$)) " + "| (\\&(?=([^\\\"']*[\\\"'][^\\\"']*[\\\"'])*[^\\\"']*$)) "; Pattern pattern = Pattern.compile(patternString); Matcher matcher = pattern.matcher(definition); return matcher.find(); }

Target:
Any shot of breaking this up a bit so that someone can understand what we're looking for?
Source:
public static void setUp() { System.setProperty("XD_HOME", "../.."); RandomConfigurationSupport randomConfigSupport = new RandomConfigurationSupport(); application = new SingleNodeApplication().run(); SingleNodeIntegrationTestSupport singleNodeIntegrationTestSupport = new SingleNodeIntegrationTestSupport( application); }

Target:
These variables are not used (randomConfigSupport and singleNodeIntegrationTestSupport) and the tests run ok without them - is there some magic they provide that I am not aware of? Or, can I just remove them?
Source:
public SparkStreamingPlugin(MessageBus messageBus) { super(messageBus, null); }

Target:
I think there is a 1 parameter version of this constructor that you can use instead of passing `null`.
Source:
public void undeploy(String name) { Assert.hasText(name, "name cannot be blank or null"); validateBeforeUndeploy(name); logger.trace("Undeploying {}", name); D definition = getDefinitionRepository().findOne(name); if (definition == null) { throwNoSuchDefinitionException(name); } final I instance = instanceRepository.findOne(name); if (instance == null) { throwNotDeployedException(name); } instanceRepository.delete(instance); undeployResource(name); }

Target:
Same here, it seems that `validateBeforeUndeploy` is doing the exact same thing as the code below.
Source:
public int selectPartition(Object key, int partitionCount) { int hashCode = key.hashCode(); if (hashCode == Integer.MIN_VALUE) { hashCode = 0; } return Math.abs(hashCode) % partitionCount; }

Target:
Actually, I think the modulo should not be part of the strategy as it is always applied. Even, on closer inspection, I think there is an issue with ``` if (partition >= meta.partitionCount) { partition = partition % meta.partitionCount; } if (partition < 0) { partition = Math.abs(partition); } ``` => What if partition is less than `-meta.partitionCount` ? The modulo should be always applied, then abs() IMHO
Source:
public void stop() { logger.info("stopping SparkDriver"); try { // todo: when possible (spark 1.3.0), change to streamingContext.stop(false, true) without the cancel if (javaStreamingContext != null) { javaStreamingContext.ssc().sc().cancelAllJobs(); javaStreamingContext.close(); } if (streamingContext != null) { streamingContext.sc().cancelAllJobs(); streamingContext.stop(true, false); } super.stop(); } catch (Exception e) { logger.warn("Exception when stopping the spark module " + e); } }

Target:
is this what we want here? The first boolean indicates stopping the actual SparkContext and the 2nd boolean is FALSE for "graceful" So, two things jump out: 1) those boolean values are the reverse of what we mention in the TODO above this 2) this is different than the Java version (where we just call close), and that was done that way - along with the cancel call - as a temporary workaround until the proper stop (with false, true) would work
Source:
private Module createAndConfigureModuleInstance(ModuleDescriptor moduleDescriptor, ModuleOptions moduleOptions, ModuleDeploymentProperties deploymentProperties) { String name = (String) moduleOptions.asPropertySource().getProperty(MODULE_EXECUTION_FRAMEWORK); if (Processor.MODULE_EXECUTION_FRAMEWORK.equals(name)) { return createSparkModule(moduleDescriptor, moduleOptions, deploymentProperties); } Module module = moduleDescriptor.isComposed() ? createCompositeModule(moduleDescriptor, moduleOptions, deploymentProperties) : createSimpleModule(moduleDescriptor, moduleOptions, deploymentProperties); return module; }

Target:
Should see what Rx/Reactor brings, but the main flow of decisions seems weird here. Also, you're not leveraging the module ClassLoader, which seems wrong.
Source:
public void missingConfigThrowsException() { ModuleDefinition moduleDefinition = ModuleDefinitions.simple("missing", ModuleType.processor, "classpath:/ModuleFactoryTests/modules/processor/missing"); ModuleDescriptor moduleDescriptor = new ModuleDescriptor.Builder() .setModuleDefinition(moduleDefinition) .setModuleName("missing") .setGroup("group") .setModuleDefinition(moduleDefinition) .build(); createResourceConfiguredModule("missing",ModuleType.processor); }

Target:
Just browsing through the web interface at the moment, but I don't see `moduleDescriptor` being used in the test
Source:
public String[] profilesToActivate() { if (this.regexPattern != null) { return new String[] { REGEX_PATTERN_FILTER }; } else if (this.pattern != null) { return new String[] { SIMPLE_PATTERN_FILTER }; } else { return new String[] { ACCEPT_ALL_FILES }; } }

Target:
Don't need last else
Source:
boolean isEitherPasswordOrPrivateKeyAndPassPhrase() { if (!StringUtils.hasText(password)) { return StringUtils.hasText(privateKey) && StringUtils.hasText(passPhrase); } else { return !StringUtils.hasText(privateKey) && !StringUtils.hasText(passPhrase); } }

Target:
don't need the else here. Too bad java doesn't have XOR :)
Source:
protected void deployModules(Container container) throws Exception { String containerName = container.getName(); logger.info("Container arrived: {}", containerName); // before attempting to deploy unallocated modules, // wait to see if any more containers show up; this // will mitigate "overloading" of the container that // just arrived Thread.sleep(1000); deployUnallocatedStreamModules(); deployUnallocatedJobModules(); }

Target:
When deploying the modules, since we no longer target **only** the arriving container but match all the available containers from the repository, can we have a `scheduled` deployer that performs the redeployment operation on a given time to all the targeting container. What I see from here is that the whole logic doesn't use the `arriving container` info anymore.
Source:
public String getLocalTime(Date date) { Assert.notNull(date, "The provided date must not be null."); return CommonUtils.getLocalTime(date, this.clientTimeZone); }

Target:
The reason for the NPE in `doStopJobExecution(org.springframework.xd.shell.command.JobCommandTests)` comes from here: ``` final String startTimeAsString = this.configuration.getLocalTime(jobExecutionInfoResource.getJobExecution().getStartTime()); ``` The JobExecution startTime can be null.
Source:
public int hashCode() { int result = container.hashCode(); result = 31 * result + moduleSequence.hashCode(); result = 31 * result + moduleDescriptorKey.hashCode(); return result; }

Target:
Should this still include the key's hashCode as well as adding the sequence hashCode?
Source:
private boolean hasDeploymentInfo() { boolean hasValue = false; for (String s : deploymentDesc) { hasValue |= StringUtils.hasText(s); } if (!hasValue) { return false; } if (StringUtils.isEmpty(deploymentDesc[MODULE_LABEL])) { throw new IllegalStateException("Module label missing"); } if (StringUtils.isEmpty(deploymentDesc[CONTAINER])) { throw new IllegalStateException("Container missing"); } return true; }

Target:
Could use Assert.state() here (since IllegalStateException is desired) or Assert.hasText(..) (which would instead throw IllegalArgumentException). In either case though, the 6 lines could be replaced by 2, and it improves test coverage (unless we have tests that make it into each of these if blocks).
Source:
public QualifiedModuleName convertFromText(String value, Class<?> targetType, String optionContext) { int colonIndex = value.indexOf(':'); if (colonIndex == -1) { logger.warning("Incorrect syntax. Valid syntax is '<ModuleType>:<ModuleName>'."); logger.warning("For example, 'module info source:file' to get 'file' <source> module info."); throw new ShellException(); } RESTModuleType moduleType = validateAndReturnModuleType(colonIndex, value); QualifiedModuleName result = new QualifiedModuleName(value.substring(colonIndex + 1), moduleType); return result; }

Target:
why not just pass a single arg to validateAndReturnModuleType(..), e.g.: ``` validateAndReturnModuleType(value.substring(0, colonIndex)); ```
Source:
public RedisTestMessageBus(RedisConnectionFactory connectionFactory, MultiTypeCodec<Object> codec) { RedisMessageBus messageBus = new RedisMessageBus(connectionFactory, codec); this.setMessageBus(messageBus); GenericApplicationContext context = new GenericApplicationContext(); context.refresh(); messageBus.setApplicationContext(context); this.setMessageBus(messageBus); template = new StringRedisTemplate(connectionFactory); }

Target:
Remove, please, this line.
Source:
private void checkForIllegalStreamName(String streamName, String streamDef) { try { StreamNode sn = parse(streamName, streamDef); fail("expected to fail but parsed " + sn.stringify()); } catch (StreamDefinitionException e) { assertEquals(XDDSLMessages.ILLEGAL_STREAM_NAME, e.getMessageCode()); assertEquals(0, e.getPosition()); e.printStackTrace(); assertEquals(streamName, e.getInserts()[0]); } }

Target:
did you intend to leave the printStackTrace() here?
Source:
public void initialize(ConfigurableApplicationContext applicationContext) { String adminPort = applicationContext.getEnvironment().resolvePlaceholders(ADMIN_PORT_PLACEHOLDER); ServerSocket socket = null; try { socket = new ServerSocket(Integer.parseInt(adminPort)); } catch (IOException e) { throw new AdminPortNotAvailableException(adminPort); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { // It is very unlikely to get an exception here. e.printStackTrace(); } } } }

Target:
I would not even bother printing the stack trace here. It won't do us any good to see it.
Source:
protected ContainerAttributesResource instantiateResource(ContainerAttributes entity) { return new ContainerAttributesResource(entity.getId(), entity.getPid(), entity.getHost(), entity.getIp()); }

Target:
It looks like we need to modify ContainerAttributesResource to simply take a Map in its constructor. That way it's not only simpler, but it would also mean that all attribute values (including user-provided ones beyond those available OOTB) would be represented by the resource representation.
Source:
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if (applicationContext instanceof AbstractApplicationContext) { ((AbstractApplicationContext) applicationContext).setId(this.containerMetadata.getId()); } this.context = applicationContext; }

Target:
This is one of the reasons I didn't create a PR yet; not sure what the answer is yet but was going to explore it (possibly using ApplicationContextInitializer and creating ContainerMetadata earlier). Earlier (current master) we had a static method being called to publish the container started event from a context (static so SingleNodeApplication could also call it), but that definitely needs to change. We need a bean, with a managed lifecycle.
Source:
public void close() { if (containerContext != null) { containerContext.close(); if (moduleDeployer != null) { ConfigurableApplicationContext moduleCommon = moduleDeployer.getCommonContext(); if (moduleCommon != null) { moduleCommon.close(); } } } if (adminContext != null) { adminContext.close(); ApplicationContext parent = adminContext.getParent(); if (parent instanceof ConfigurableApplicationContext) { ((ConfigurableApplicationContext) parent).close(); } } }

Target:
Seems to me that this is only handled in the SingleNode case, not in the distributed case, am I correct? Moreover, having the launcher know about all those contexts seems a bit ugly to me. I guess I would expect it to be more transparent (maybe by listening for some kind of close event or whatever?)
Source:
protected MessageBus getMessageBus() { testMessageBus = new RabbitTestMessageBus(rabbitAvailableRule.getResource(), getCodec()); return testMessageBus; }

Target:
should this only initialize the testMessageBus instance if it's null? (could be synchronized at method-level or in a synchronized block)
Source:
public void testLaunchJobTwiceWhereMakeUniqueIsFalse() { logger.info("Launch batch job (makeUnique=false) twice"); executeJobCreate(MY_JOB, JOB_WITH_PARAMETERS_DESCRIPTOR + " --makeUnique=false"); checkForJobInList(MY_JOB, JOB_WITH_PARAMETERS_DESCRIPTOR + " --makeUnique=false", true); executeJobLaunch(MY_JOB); CommandResult result = executeCommandExpectingFailure("job launch --name " + MY_JOB); System.out.println("*************************" + result.getException().getMessage()); assertThat( result.getException().getMessage(), containsString("A job instance already exists and is complete for parameters={}. If you want to run this job again, change the parameters.")); }

Target:
I assume this was meant to be removed?
Source:
public StepExecutionProgressInfoResource(StepExecution stepExecution, StepExecutionHistory stepExecutionHistory, double percentageComplete, boolean isFinished, double duration) { Assert.notNull(stepExecution, "stepExecution must not be null."); Assert.notNull(stepExecutionHistory, "stepExecution must not be null."); this.stepExecution = stepExecution; this.stepExecutionHistory = stepExecutionHistory; this.percentageComplete = percentageComplete; this.finished = isFinished ? "true" : "false"; this.duration = duration; }

Target:
Why use a String in the Resource. The client should be responsible for formatting.
Source:
public synchronized byte[] serialize(Message<?> message) throws SerializationException { Kryo kryo = kryoInstance(); Output output = new Output(2048, -1); kryo.writeObjectOrNull(output, message, GenericMessage.class); return output.getBuffer(); }

Target:
Looking at these 3 methods, I don't see why they need to be synchronized. All the state appears to be in method-scope.
Source:
protected void closeOutputStreams() throws IOException { if (outputHolder != null) { outputHolder.getStream().close(); if (outputHolder.getWrappedStream() != null) { outputHolder.getWrappedStream().close(); } outputHolder = null; } }

Target:
is it necessary to wrap these in try/catch (but still propagate the exception at the end) so that if one fails the other close() is not bypassed?
Source:
private ModuleType verifyModuleOfTypeExists(ModuleDeploymentRequest request, String moduleName, ModuleType type) { ModuleDefinition def = moduleDefinitionRepository.findByNameAndType(moduleName, type); if (def == null || def.getResource() == null) { List<ModuleDefinition> definitions = moduleDefinitionRepository.findByName(moduleName); if (definitions == null || definitions.size() == 0) { throw new NoSuchModuleException(moduleName); } // TODO: revisit this method altogether; it shouldn't apply to composite modules but at this stage we don't // know whether the 'stream' is actually a composite module (and we do want to verify complete streams) // the following method was removed from MDR: (leaving here as a reminder for the TODO) // The module is known but this doesn't seem to be a standard stream, // assume it is a composite module stream that isn't deployable by itself // request.tagAsUndeployable(); return definitions.get(0).getType(); } return def.getType(); }

Target:
Code smell: clarify contract of repository regarding emptyness
Source:
protected synchronized void handleMessageInternal(Message<?> message) throws Exception { String payloadString = message.getPayload().toString(); Class<?> type = (payloadString.contains("\"composite\":true")) ? CompositeModuleDeploymentRequest.class : ModuleDeploymentRequest.class; Object deserialized = this.mapper.readValue(payloadString, type); if (deserialized instanceof CompositeModuleDeploymentRequest) { handleCompositeModuleDeployment((CompositeModuleDeploymentRequest) deserialized, message); } else { handleDeploymentRequest((ModuleDeploymentRequest) deserialized, message); } }

Target:
I guess this is on your laundry list, right ;)
Source:
public void onReadError(Exception exception) { if (logger.isDebugEnabled()) { logger.debug("Executing onReadError: " + exception.getMessage(), exception); } final Message<Exception> message = MessageBuilder.withPayload(exception) .setHeader(BatchJobHeaders.BATCH_LISTENER_EVENT_TYPE, BatchListenerEventType.ITEM_LISTENER_ON_READ_ERROR) .build(); notificationsChannel.send(message); }

Target:
Add the .name()
Source:
public TarArchiveEntry(final Path file) { this(file, file.toString()); }

Target:
What will happen if `file` is absolute?
Source:
public void findImplementations() { ResolverUtil<VFS> resolverUtil = new ResolverUtil<>(); resolverUtil.findImplementations(VFS.class, "org.apache.ibatis.io"); Set<Class<? extends VFS>> classSets = resolverUtil.getClasses(); classSets.forEach(c -> Assert.assertTrue(VFS.class.isAssignableFrom(c))); }

Target:
Should verify size of resolved classes.
Source:
public void setUp() throws Exception { currentContextClassLoader = Thread.currentThread().getContextClassLoader(); }

Target:
Can omit `public` on JUnit 5.
Source:
public Object get(Object key) { String strKey = (String) key; if (super.containsKey(strKey)) { return super.get(strKey); } if (parameterMetaObject == null) { return null; } if (fallbackParameterObject) { return parameterMetaObject.hasGetter(strKey) ? parameterMetaObject.getValue(strKey) : parameterMetaObject.getOriginalObject(); } else { // issue #61 do not modify the context when reading return parameterMetaObject.getValue(strKey); } }

Target:
This part can be slightly simpler. ```java if (fallbackParameterObject && !parameterMetaObject.hasGetter(strKey)) { return parameterMetaObject.getOriginalObject(); ```
Source:
public int update(String sql, Object... args) throws SQLException { try (PreparedStatement ps = connection.prepareStatement(sql)) { setParameters(ps, args); return ps.executeUpdate(); } }

Target:
Probably, this changes will broken a current behavior that ignore exception if the `Statement.close` throw a `SQLException`.
Source:
private ReentrantLock getLockForKey(Object key) { return locks.computeIfAbsent(key, (k) -> new ReentrantLock()); }

Target:
`(k)` -> `k` ```suggestion return locks.computeIfAbsent(key, k -> new ReentrantLock()); ```
Source:
public Iterator<T> iterator() { if (isClosed()) { throw new IllegalStateException("A Cursor is already closed."); } if (iteratorRetrieved) { throw new IllegalStateException("Cannot open more than one iterator on a Cursor"); } iteratorRetrieved = true; return cursorIterator; }

Target:
It would be better to check `isClosed()` after checking `iteratorRetrieved` because the error message is more specific.
Source:
public Object getNullableResult(ResultSet rs, String columnName) throws SQLException { Array array = rs.getArray(columnName); return (array == null || rs.wasNull()) ? null : array.getArray(); }

Target:
A lot of your changes are because of this logic. I'm curious what driver returns a non null for an object type but returns true for rs.wasNull() I've only see it happen for primitive types but never for object types
Source:
protected String sqlxmlToString(SQLXML sqlxml) throws SQLException { String result = sqlxml.getString(); sqlxml.free(); return result; }

Target:
I think it needs the null check.
Source:
public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException { SQLXML sqlxml = ps.getConnection().createSQLXML(); sqlxml.setString(parameter); ps.setSQLXML(i, sqlxml); sqlxml.free(); }

Target:
If you need to call `free()`, it may be better to call it in try-finally.
Source:
public void testInsertAnnotated() throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); try { InsertMapper mapper = sqlSession.getMapper(InsertMapper.class); Name name = new Name(); name.setFirstName("Fred"); name.setLastName("Flintstone"); int rows = mapper.insertNameAnnotated(name); assertNotNull(name.getId()); assertEquals(1, rows); } finally { sqlSession.close(); } }

Target:
I prefer use try-with-resources as follow: ```java try(SqlSession sqlSession = sqlSessionFactory.openSession()) { InsertMapper mapper = sqlSession.getMapper(InsertMapper.class); Name name = new Name(); name.setFirstName("Fred"); name.setLastName("Flintstone"); int rows = mapper.insertNameAnnotated(name); assertNotNull(name.getId()); assertEquals(1, rows); } ```
Source:
private void populateWriterArray() { columnWriters = new ArrayList<>(); // Case for empty result set if (firstRow == null || firstRow.length == 0) { return; } int colPosition = 0; for (String value : firstRow) { columnWriters.add(new StringColumnWriter(value, rowWriter, colPosition)); colPosition++; } }

Target:
Can `columnWriters = new ArrayList<>();` go here (after `firstRow` checks)?
Source:
private TupleMetadata buildSchema() { this.firstRow = csvReader.parseNext(); // Case for empty dataset if (firstRow == null) { return builder.buildSchema(); } // Parse the first row for (String value : firstRow) { builder.addNullable(value, TypeProtos.MinorType.VARCHAR); } return builder.buildSchema(); }

Target:
Does it make sense to refactor complete function to this: ```java this.firstRow = csvReader.parseNext(); if (firstRow != null) { for (String value : firstRow) { builder.addNullable(value, TypeProtos.MinorType.VARCHAR); } } return builder.buildSchema(); ```
Source:
private IterOutcome handleRightIncoming() { outer: for (;;) { IterOutcome outcome = next(0, right); switch (outcome) { case NONE: state = State.LEFT; break outer; case NOT_YET: return outcome; case OK_NEW_SCHEMA: case OK: appendStatistics(statisticsCollector); break; default: throw new UnsupportedOperationException("Unsupported upstream state " + outcome); } } return null; }

Target:
I use IntelliJ IDEA, the warning was the following: `'for' loop may be replaced with 'while' loop`. Its description is ``` Reports for loops which contain neither initialization or update components, and can thus be replaced by simpler while statements. Example: for(; exitCondition(); ) { process(); } This loop can be replaced with while(exitCondition()) { process(); } A fix action is also available for other for loops, so you can replace any for loop with while. Use the checkbox below if you wish this inspection to ignore for loops with trivial or non-existent conditions. ```
Source:
protected ElementParser resolve(TokenIterator tokenizer) { tupleParser.loader().removeNullMarker(this); if (tokenizer.peek() == JsonToken.START_ARRAY) { // The value is [], [ foo, so resolve directly return tupleParser.resolveField(key, tokenizer); } else { } // The value is [], foo, so must artificially create the // surrounding array to get a repeated type, which will // then parse the item as one-item array. return tupleParser.resolveArray(key, tokenizer); }

Target:
Could you please remove the empty block?
Source:
private boolean processNextRow() { try { // Stop reading when you run out of data if (!spssReader.readNextCase()) { return false; } rowWriter.start(); for (SpssColumnWriter spssColumnWriter : writerList) { spssColumnWriter.load(spssReader); } rowWriter.save(); } catch (IOException e) { throw UserException .dataReadError(e) .message("Error reading SPSS File.") .addContext(e.getMessage()) .addContext(errorContext) .build(logger); } return true; }

Target:
Not necessary. Better is: ``` .context("Error reading SPSS File.") ``` And let the message be the underlying error.
Source:
public void allocateNew() throws OutOfMemoryException { if (!allocateNewSafe()) { throw new OutOfMemoryException("" + "Failed to allocate memory for " + getClass().getSimpleName()); } }

Target:
```suggestion throw new OutOfMemoryException( ```
Source:
public static List<SchemaPath> expandMetadata(int dirCount) { List<String> selected = Lists.newArrayList( FULLY_QUALIFIED_NAME_COL, FILE_PATH_COL, FILE_NAME_COL, SUFFIX_COL); for (int i = 0; i < dirCount; i++) { selected.add(PARTITION_COL + Integer.toString(i)); } return RowSetTestUtils.projectList(selected); }

Target:
Arrays.asList
Source:
public void testNullUserAgent() throws Exception { String query = "SELECT parse_user_agent(CAST(null as VARCHAR)) AS agent FROM (values(1))"; Map<?, ?> emptyMap = new HashMap<>(); testBuilder() .sqlQuery(query) .ordered() .baselineColumns("agent") .baselineValues(emptyMap) .go(); }

Target:
```suggestion Map<?, ?> emptyMap = Collections.emptyMap(); ```
Source:
public void eval() { // Get the timestamp in milliseconds long timestamp = inputDate.value; // Get the interval in milliseconds long groupByInterval = interval.value; java.time.Instant instant = java.time.Instant.ofEpochMilli(timestamp - (timestamp % groupByInterval)); java.time.LocalDateTime localDate = instant.atZone(java.time.ZoneId.of("UTC")).toLocalDateTime(); out.value = localDate.atZone(java.time.ZoneId.of("UTC")).toInstant().toEpochMilli(); }

Target:
@cgivre, could you please explain, what happens here? Initially, you calculate the required milliseconds, after that creates `Instant` instance based on that, converts it to `LocalDateTime` at `UTC` timezone, converts it to `ZonedDateTime`, converts it to `Instant` and after that converts back to milliseconds. Are all these transformations required? Usually, UDF shouldn't apply timezone to the values they handle.
Source:
public void eval() { // Get the timestamp in milliseconds long timestamp = inputDate.value; // Get the interval in milliseconds long intervalToAdd = interval.value; out.value = (long) java.lang.Math.floor(timestamp / intervalToAdd) * intervalToAdd; }

Target:
isn't simpler formula ```timestamp - (timestamp % interval)``` ?
Source:
public String toString() { String result = type.name(); for (int i = 0; i < arrayDims; i++) { result += "[]"; } return result; }

Target:
Could you please replace strings concatenation with `StringBuilder` usage.
Source:
public void sendOk(int credit) { everLargestAdviceCredit = credit > everLargestAdviceCredit ? credit : everLargestAdviceCredit; if (0 == count.decrementAndGet()) { BitData.AckWithCredit ackWithCredit = BitData.AckWithCredit.newBuilder().setAllowedCredit(everLargestAdviceCredit).build(); Response ackResponse = new Response(BitData.RpcType.DATA_ACK_WITH_CREDIT, ackWithCredit); sender.send(ackResponse); } }

Target:
This might be a bit clearer: ``` everLargestAdviceCredit = Math.max(everLargestAdviceCredit, credit); ```
Source:
public boolean equals(final Object other) { if (other == this) { return true; } if (other == null || !(other instanceof Map.Entry)) { return false; } final Map.Entry<?, ?> entry = (Map.Entry<?, ?>) other; return Objects.equal(key, entry.getKey()) && Objects.equal(value, entry.getValue()); }

Target:
```suggestion Map.Entry<?, ?> entry = (Map.Entry<?, ?>) other; ```
Source:
public SystemPluginLocator(PluginRegistryContext context) { this.context = checkNotNull(context); }

Target:
I think we can skip not null check, let's assume caller knows what he is doing and not going to pass null context.
Source:
protected FileScanFramework.FileScanBuilder frameworkBuilder(OptionManager options, EasySubScan scan) { FileScanFramework.FileScanBuilder builder = new FileScanFramework.FileScanBuilder(); builder.setReaderFactory(new AvroReaderFactory(new AvroBatchReader.AvroReaderConfig(this))); initScanBuilder(builder, scan); builder.setNullType(Types.optional(TypeProtos.MinorType.VARCHAR)); return builder; }

Target:
No harm in setting this. But, I wonder if this is the right choice for Avro? Avro has a schema which, presumably, all files should follow. If schema evolution occurred (new field added), we'd really want to use the proper data type when reading old files without that column. This is of course a long-standing limitation of Drill's "pure" schema-on-read approach: while creating the reader is the wrong time to be guessing the schema of columns we are not going to see.
Source:
protected int processIpV6Packet() { try { return super.processIpV6Packet(); } catch (IllegalStateException ise) { return -1; } catch (ArrayIndexOutOfBoundsException e) { return -1; } }

Target:
Use multi-catch
Source:
public ConstantFilter(Set<LogicalExpression> constantBoundaries) { super(); this.constantBoundaries = constantBoundaries; }

Target:
```suggestion ```
Source:
public FunctionHolderExpression(String nameUsed, ExpressionPosition pos, List<LogicalExpression> args) { super(pos); this.nameUsed = nameUsed; if (args == null) { this.args = ImmutableList.of(); } else if (args instanceof ImmutableList) { this.args = (ImmutableList<LogicalExpression>) args; } else { this.args = ImmutableList.copyOf(args); } }

Target:
Could you please replace these if blocks with `ImmutableList.copyOf`, it produces these checks internally to avoid copying is possible.
Source:
public ValueVector getOutgoingValueVector(TypedFieldId fieldId) { Class<?> clazz = fieldId.getIntermediateClass(); int[] fieldIds = fieldId.getFieldIds(); return outgoingBatch.getValueAccessorById(clazz, fieldIds).getValueVector(); }

Target:
```suggestion private ValueVector getOutgoingValueVector(TypedFieldId fieldId) { ```
Source:
void addField(ValueVector vv, LogicalExpression logicalExpression, OutputColumnType outputColumnType, String inputColumnName, String outputColumnName) { if(isFixedWidth(vv)) { addFixedWidthField(vv); } else { addVariableWidthField(vv, logicalExpression, outputColumnType, inputColumnName, outputColumnName); } }

Target:
```suggestion private void addField(ValueVector vv, LogicalExpression logicalExpression, OutputColumnType outputColumnType, ```
Source:
private CapitalizingJdbcSchema determineDefaultSchema(String connectionSchemaName) { CapitalizingJdbcSchema connSchema; if (connectionSchemaName == null || (connSchema = schemaMap.get(connectionSchemaName.toLowerCase())) == null) { // todo: this selection of default schema isn't correct, users are getting implicit random schema as default connSchema = schemaMap.values().iterator().next(); } return (CapitalizingJdbcSchema) connSchema.getDefaultSchema(); }

Target:
Is casting without instance of check safe here?
Source:
public Table getTable(String name) { if (defaultSchema != null) { try { return defaultSchema.getTable(name); } catch (RuntimeException e) { JdbcStoragePlugin.logger.warn("Failure while attempting to read table '{}' from JDBC source.", name, e); } } // no table was found. return null; }

Target:
Why just runtime exception? I assume you want to ignore all exceptions...
Source:
JdbcIntermediatePrelConverterRule() { super(JdbcDrel.class, (Predicate<RelNode>) input -> true, DrillRel.DRILL_LOGICAL, Prel.DRILL_PHYSICAL, DrillRelFactories.LOGICAL_BUILDER, "JDBC_PREL_Converter"); }

Target:
Since this rule does not preserve any state, can we use it as a singleton, i.e. reuse the same instance?
Source:
private static SqlNode expandAvg(final SqlNode arg) { final SqlParserPos pos = SqlParserPos.ZERO; final SqlNode sum = DrillCalciteSqlAggFunctionWrapper.SUM.createCall(pos, arg); final SqlNode count = SqlStdOperatorTable.COUNT.createCall(pos, arg); final SqlNode sumAsDouble = CastHighOp.createCall(pos, sum); return SqlStdOperatorTable.DIVIDE.createCall( pos, sumAsDouble, count); }

Target:
final
Source:
private static String readAFileIntoString(String filePath) { String content = ""; try { content = new String ( Files.readAllBytes( Paths.get(filePath) ) ); } catch (IOException e) { e.printStackTrace(); } return content; }

Target:
This method has numerous code style issues: - `{` are on the new lines - extra spaces before `(`, ``)` - `e.printStackTrace();`
Source:
public static String getPrincipalFromParts(final String primary, final String instance, final String realm) { checkNotNull(primary); checkNotNull(realm); return checkNotNull(primary) + ((instance != "")? "/" + instance: "") + "@" + checkNotNull(realm); }

Target:
You have already checked that primary and realm are not null
Source:
public static RowSetReaderImpl build(BatchAccessor batch) { VectorContainer container = batch.container(); try { return build(container, new HyperSchemaInference().infer(container), batch.selectionVector4()); } catch (SchemaChangeException e) { throw new UnsupportedOperationException(e); } }

Target:
Why is we capture schema change exception, unsupported exception is thrown?
Source:
public <T extends BaseSubScan> CloseableRecordBatch createScan(ExecutorFragmentContext context, BaseSubScan subScan) throws ExecutionSetupException { try { final ScanFrameworkBuilder builder = options.scanFactory.scanBuilderShim(this, context.getOptions(), subScan); return builder.buildScanOperator(context, subScan); } catch (final UserException e) { // Rethrow user exceptions directly throw e; } catch (final Throwable e) { // Wrap all others throw new ExecutionSetupException(e); } }

Target:
Maybe we can remove final here and in exceptions?
Source:
public BaseSubScan(BaseGroupScan groupScan) { super(groupScan.getUserName()); storagePlugin = groupScan.storagePlugin(); this.columns = groupScan.getColumns(); }

Target:
```suggestion this.storagePlugin = groupScan.storagePlugin(); ```
Source:
public void copy(ColumnReader from) { throw new UnsupportedOperationException("Cannot copy values through a type converter"); }

Target:
If type converters shouldn't support copy then maybe makes sense to mark the method as final here.
Source:
public void setValueCount(int topLevelValueCount) { if (topLevelValueCount == 0) { return; } int childValueCount; if (topLevelValueCount == 0) { childValueCount = 0; offsets.getMutator().setValueCount(0); } else { emptyPopulator.populate(topLevelValueCount); childValueCount = offsets.getAccessor().get(topLevelValueCount); } for (ValueVector v : getChildren()) { v.getMutator().setValueCount(childValueCount); } }

Target:
Looks like this code wouldn't be triggered because of the return above.
Source:
public HttpGroupScan ( HttpStoragePluginConfig config, HttpScanSpec scanSpec, List<SchemaPath> columns ) { super("no-user"); this.httpStoragePluginConfig = config; this.httpScanSpec = scanSpec; this.columns = columns == null || columns.size() == 0 ? ALL_COLUMNS : columns; }

Target:
Group scans are wildly complicate (too much so.) One of the odd things is that they are serialized to JSON. (As part of the "logical plan.") This means that this class must be Jackson-serializable. Here, your plugin takes the config (which is serializable). If you find you need the plugin itself, then there is a hokey-pokey you must do. See [this wiki](https://github.com/paul-rogers/drill/wiki/Create-a-Storage-Plugin) for more info.
Source:
public SubScan getSpecificScan(int minorFragmentId) { logger.debug("HttpGroupScan getSpecificScan"); return new HttpSubScan(httpStoragePluginConfig, httpScanSpec, columns); }

Target:
This will be called once because `getMaxParallelizationWidth()` returns 1. Should this plugin allow sharding requests? If I'm requesting a time range, say, should the plugin try to split the time ranges into multiple small requests that Drill can spread across Drillbits? That is a VERY complex topic that I'm still trying to sort out...
Source:
public Table getTable(String tableName) { DynamicDrillTable table = activeTables.get(name); if (table != null) { return table; } if (!activeTables.containsKey(name)) { return registerTable(name, new DynamicDrillTable(plugin, pluginName, new HttpScanSpec(pluginName, name, tableName, plugin.getConfig()))); } return null; }

Target:
Can never get here given the logic flow above.
Source:
public int getMaxParallelizationWidth() { return 0; }

Target:
I suspect this must be at least 1. We can't read much data from 0 worker threads.
Source:
public void registerSchemas(SchemaConfig schemaConfig, SchemaPlus parent) throws IOException { HttpSchema schema = new HttpSchema(getName()); logger.debug("Registering {}", schema.getName(), schema.toString()); SchemaPlus schemaPlus = parent.add(getName(), schema); schema.setHolder(schemaPlus); }

Target:
Isn't this redundant with the `HttpAPIConnectionSchema` class above? Do we need two? Which one should we review?
Source:
public SubScan getSpecificScan(int minorFragmentId) { logger.debug("HttpGroupScan getSpecificScan"); return new HttpSubScan(config, httpScanSpec, columns); }

Target:
Unless you debug by reading logs, no need for these debug statements. These methods are called when needed.
Source:
public AbstractSchema getSubSchema(String name) { try { if (!plugin.getConfig().connections().containsKey(name)) { throw UserException .connectionError() .message("API '{}' does not exist in HTTP Storage plugin '{}'", name, getName()) .build(logger); } return getSubSchemaKnownExists(name); } catch (Exception e) { throw new DrillRuntimeException(e); } }

Target:
Was this a copy/paste? If we go to the trouble of throwing a `UserException`, we should throw it, not catch it and wrap it in another kind of exception (which will, later be wrapped in a `UserException`.) Just let the `UserException` be thrown. Also, nit, reverse polarity: `if (...containsKey...) { return get... } else { throw ... }`
Source:
public BasicAuthInterceptor(String user, String password) { credentials = Credentials.basic(user, password); logger.debug("Intercepting request adding creds: {}", credentials); }

Target:
Please do not log credentials. Security guys (such as yourself) don't like that.
Source:
public AbstractGroupScan getPhysicalScan(String userName, JSONOptions selection) throws IOException { DruidScanSpec scanSpec = selection.getListWith(new ObjectMapper(), new TypeReference<DruidScanSpec>() {}); return new DruidGroupScan(userName, this, scanSpec, null); }

Target:
Was there a reason why this is `AbstractGroupScan` instead of `DruidGroupScan`?
Source:
DruidScanSpec build(String dataSourceName, String functionName, SchemaPath field, Object fieldValue) throws IOException { // extract the field name String fieldName = field.getAsNamePart().getName(); DruidFilter filter = translateFilter(functionName, fieldName, String.valueOf(fieldValue)); logger.debug("createDruidScanSpec called. FunctionName - " + functionName + ", field - " + fieldName + ", fieldValue - " + fieldValue); DruidScanSpec scanSpec = new DruidScanSpec(dataSourceName, filter); logger.debug("Created new DruidScanSpec with filter - " + filter + " for DataSource - " + dataSourceName); return scanSpec; }

Target:
If this method doesn't throw IOException, please remove.
Source:
public boolean matches(RelOptRuleCall call) { final ScanPrel scan = (ScanPrel) call.rel(1); if (scan.getGroupScan() instanceof DruidGroupScan) { return super.matches(call); } return false; }

Target:
One more redundant cast...
Source:
public DruidScanSpec parseTree() throws JsonProcessingException { logger.debug("DruidScanSpec parseTree() called."); DruidScanSpec parsedSpec = le.accept(this, null); if (parsedSpec != null) { parsedSpec = mergeScanSpecs( FunctionNames.AND, this.groupScan.getScanSpec(), parsedSpec ); } return parsedSpec; }

Target:
If this doesn't throw an exception, please remove the `throws` clause.
Source:
public DruidDataSources(String name) { super(ImmutableList.<String>of(), name); this.tableNames = this.getTableNames(); }

Target:
nit: `String` is not necessary here.
Source:
public void clearStack() { super.clearStack(); localVariablesSet.clear(); labelsStack.clear(); }

Target:
Consider nullification or empty collections re-assignement
Source:
private static Map<Class<? extends RecordBatch>, CheckMode> buildRules() { Map<Class<? extends RecordBatch>, CheckMode> rules = new IdentityHashMap<>(); rules.put(OperatorRecordBatch.class, CheckMode.ALL); return rules; }

Target:
```suggestion private final Map<Class<? extends RecordBatch>, CheckMode> rules = new IdentityHashMap<>(); ```
Source:
public List<String> getExtensions() { if (extensions == null) { return DEFAULT_EXTS; } return extensions; }

Target:
Nit: `return extensions == null ? DEFAULT_EXTS : extensions`
Source:
public List<String> getExtensions() { if (extensions == null) { return DEFAULT_EXTS; } return extensions; }

Target:
Nit: `return extensions == null ? DEFAULT_EXTS ? extensions;`
Source:
public boolean next() { if (fileReaderShp == null) { return false; } Geometry geom = null; while( !rowWriter.isFull()){ Object[] dbfRow = dbfReader.nextRecord(); geom = geomCursor.next(); if(geom == null) { return false; } processShapefileSet(rowWriter, geomCursor.getGeometryID(), geom, dbfRow); } return true; }

Target:
Should this ever happen? The EVF will ensure that the following order occurs: * `open()` * `next()` (until `false` is returned, or an error) * `close()` (exactly once, only if `open()` succeeds) So, when would the file be null?
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } ShpFormatConfig other = (ShpFormatConfig)obj; return Objects.equal(extensions, other.getExtensions() ); }

Target:
Is there an analog method not from Guava? We should try to use build-in Java methods when possible... ```suggestion return Objects.equal(extensions, other.getExtensions()); ```
Source:
public IcebergMetastore(DrillConfig config) { this.config = config; Configuration configuration = configuration(config); this.tables = new HadoopTables(new Configuration(configuration)); this.baseLocation = baseLocation(config, new Configuration(configuration)); this.commonProperties = properties(config, IcebergConfigConstants.COMPONENTS_COMMON_PROPERTIES); this.expirationHandler = new ExpirationHandler(config, new Configuration(configuration)); }

Target:
looks like there is no need to pass ```config``` into ```configuration(config)``` , ```baseLocation(config, ...);``` and ```properties(config, ...)``` because it's usage of field set at first line in constructor.
Source:
public ColumnMetadata_v4(String[] name, PrimitiveType.PrimitiveTypeName primitiveType, Object minValue, Object maxValue, Long nulls) { this(name, primitiveType, minValue, maxValue, nulls, new ArrayList<>()); }

Target:
Collections.emptyList()?
Source:
public static boolean isSortable(MinorType type) { // Currently only map, list and dict columns are not sortable. return type != MinorType.MAP && type != MinorType.LIST && type != MinorType.DICT; }

Target:
Please rewrite method body to: ```java switch (type) { case MAP: case DICT: case LIST: return false; default: return true; } ``` Also I suspect that UNION also is not sortable, need to check this.
Source:
public void clear() { getMutator().reset(); offsets.clear(); for(final ValueVector vector : getChildren()) { vector.clear(); } }

Target:
```suggestion for (ValueVector vector : getChildren()) { ```
Source:
public void testUnionSchema() { thrown.expect(UnsupportedOperationException.class); thrown.expectMessage(containsString("Unsupported data type")); convertType("uniontype<int,double>"); }

Target:
Nit: checking exception message is brittle. I would say checking that we receive `UnsupportedOperationException` is enough.
Source:
private static void verifyConversion(String hiveType, TypeProtos.MajorType type) { assertEquals(new PrimitiveColumnMetadata("a", type).columnString(), convertType(hiveType).columnString()); }

Target:
Why three below methods are static?
Source:
@Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { // REVIEW jvs 9-Apr-2006: Just for now... return planner.getCostFactory().makeTinyCost(); }

Target:
Please use "Drill" code style - move `@Override` in a separate line.
Source:
public static List<StatisticsHolder> getEstimatedTableStats(DrillStatsTable statsProvider) { if (statsProvider != null && statsProvider.isMaterialized()) { List<StatisticsHolder> tableStatistics = new ArrayList<>(); tableStatistics.add(new StatisticsHolder<>(statsProvider.getRowCount(), TableStatisticsKind.EST_ROW_COUNT)); tableStatistics.add(new StatisticsHolder<>(Boolean.TRUE, TableStatisticsKind.HAS_DESCRIPTIVE_STATISTICS)); return tableStatistics; } return Collections.emptyList(); }

Target:
```java return Arrays.asList( new StatisticsHolder<>(statsProvider.getRowCount(), TableStatisticsKind.EST_ROW_COUNT), new StatisticsHolder<>(Boolean.TRUE, TableStatisticsKind.HAS_DESCRIPTIVE_STATISTICS) ); ```
Source:
protected CalciteSchema getImplicitSubSchema(String schemaName, boolean caseSensitive) { // Drill registers schemas in lower case, see AbstractSchema constructor schemaName = schemaName != null ? schemaName.toLowerCase() : null; CalciteSchema retSchema = getSubSchemaMap().get(schemaName); if (retSchema != null) { return retSchema; } loadSchemaFactory(schemaName, caseSensitive); retSchema = getSubSchemaMap().get(schemaName); return retSchema; }

Target:
Not critical, but maybe it's better to invert: `schemaName == null ? ...`
Source:
protected SchemaNegotiatorImpl newNegotiator() { SchemaNegotiatorImpl nego = new FileSchemaNegotiatorImpl(this); String tableName = Path.getPathWithoutSchemeAndAuthority(currentSplit.getPath()).toString(); if (currentSplit.getStart() != 0) { tableName += String.format(", offset %,d", currentSplit.getStart()); } nego.setTableName(tableName); return nego; }

Target:
Not quite sure what table name this will be, why you need offset etc. Can you please give an example?
Source:
public HDF5DataWriter(IHDF5Reader reader, RowSetLoader columnWriter, String datapath) { this.reader = reader; this.columnWriter = columnWriter; this.datapath = datapath; counter = 0; }

Target:
Nit: not necessary. Java guarantees to initialize int fields and variables to 0.
Source:
MinorType getDataType(){ return dataType; }

Target:
public
Source:
String getDataType() { return dataType; }

Target:
Please make methods public