auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public MotionEventHandler() { if (Context.getConfig() != null) { tripsConfig = ReportUtils.initTripsConfig(); } }

Target:
Is there any case when we don't have config?
Source:
public Response update(Attribute entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkPermission("attribute", getUserId(), entity.getId()); Context.getAttributesManager().updateItem(entity); return Response.ok(entity).build(); }

Target:
I think it would make sense to use some constant for type names.
Source:
public AttributesManager(DataManager dataManager) { super(dataManager, Attribute.class, AttributePermission.class, DeviceAttribute.class, GroupAttribute.class); refreshItems(); refreshExtendedPermissions(); }

Target:
It seems like we refresh everything. Do you think there will be a performance issues with it?
Source:
protected Object encodeCommand(Command command) { initDevicePassword(command, ""); switch (command.getType()) { case Command.TYPE_CUSTOM: return encodeContent(command.getString(Command.KEY_DATA)); case Command.TYPE_ENGINE_STOP: return encodeContent("AT$IOGP3=1"); case Command.TYPE_ENGINE_RESUME: return encodeContent("AT$IOGP3=0"); default: Log.warning(new UnsupportedOperationException(command.getType())); break; } return null; }

Target:
Why do we need this line? I think it should be removed.
Source:
public void setTimezone(String timezone) { if (timezone != null) { this.timezone = TimeZone.getTimeZone(timezone).getID(); } else { this.timezone = null; } }

Target:
Use ternary operator here. It should make code easier to read in this case.
Source:
public Response add(Command entity) throws RecoverablePduException, UnrecoverablePduException, SmppTimeoutException, SmppChannelException, InterruptedException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); Context.getDeviceManager().sendCommand(entity); return Response.ok(entity).build(); }

Target:
Maybe we should just declare generic exception here.
Source:
public void run() { SmppSession smppSession = smppClient.getSession(); if (smppSession != null && smppSession.isBound()) { try { smppSession.enquireLink(new EnquireLink(), enquireLinkTimeout); } catch (SmppTimeoutException | SmppChannelException | RecoverablePduException | UnrecoverablePduException error) { Log.warning("Enquire link failed, executing reconnect: " + error); smppClient.reconnect(); } catch (InterruptedException error) { Log.info("Enquire link interrupted, probably killed by reconnecting"); } } else { Log.error("Enquire link running while session is not connected"); } }

Target:
Exception can be included as a separate parameter.
Source:
private String decodeAlarm(int value) { switch (value) { case 1: return Position.ALARM_SOS; case 2: return null; case 3: return Position.ALARM_GEOFENCE; case 4: return Position.ALARM_POWER_CUT; case 5: return null; case 6: return null; default: return null; } }

Target:
Remove all "null" cases. There is a default case for that.
Source:
public DeviceManager(DataManager dataManager) { this.dataManager = dataManager; this.config = Context.getConfig(); dataRefreshDelay = config.getLong("database.refreshDelay", DEFAULT_REFRESH_DELAY) * 1000; if (dataManager != null) { try { updateDeviceCache(true); updateGroupCache(true); for (Position position : dataManager.getLatestPositions()) { positions.put(position.getDeviceId(), position); } } catch (SQLException error) { Log.warning(error); } } }

Target:
Should we init group cache first? Because devices reference it...
Source:
public QueryBuilder setLong(String name, long value) throws SQLException { for (int i : indexes(name)) { try { if (value == 0) { statement.setNull(i, Types.INTEGER); } else { statement.setLong(i, value); } } catch (SQLException error) { statement.close(); connection.close(); throw error; } } return this; }

Target:
Replace tab with spaces.
Source:
public void onWebSocketConnect(Session session) { super.onWebSocketConnect(session); Map<String, Collection<?>> data = new HashMap<String, Collection<?>>(); data.put(KEY_POSITIONS, Context.getConnectionManager().getInitialState(userId)); sendData(data); Context.getConnectionManager().addListener(userId, this); }

Target:
Traccar targets Java 7 and higher, so you can use diamond operator on the right hand side.
Source:
SendThread(ClientCnxnSocket clientCnxnSocket) { super(makeThreadName("-SendThread()")); try { changeZkState(States.CONNECTING); } catch (IOException e) { throw new RuntimeException("Connection setup failed when migrate state to CONNECTING"); } this.clientCnxnSocket = clientCnxnSocket; setDaemon(true); }

Target:
Throwing a RuntimeException may lead to unexpected behaviour. So we have a way to throw a checked exception and deal explicitly with this case?
Source:
public boolean truncateLog(long zxid) { try { // close the existing txnLog and snapLog close(); // truncate it FileTxnLog truncLog = new FileTxnLog(dataDir); boolean truncated = truncLog.truncate(zxid); truncLog.close(); // re-open the txnLog and snapLog // I'd rather just close/reopen this object itself, however that // would have a big impact outside ZKDatabase as there are other // objects holding a reference to this object. txnLog = new FileTxnLog(dataDir); snapLog = new FileSnap(snapDir); return truncated; } catch (IOException e) { LOG.error("Unable to truncate Txn log", e); return false; } }

Target:
I'm wondering if IOException is sufficient. If you look at https://github.com/apache/zookeeper/blob/c234848caef0cc920f19befd1b0b14251b17da92/zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/Follower.java#L128 It's catching an Exception, so basically any exception other than IOException occurring here, could kick us back into the same situation. In fact, even the caller of Follower.followLeader() catches Exception. They're all over QuorumPeer, with "Unexpected exception" log warnings. I think as part of the same fix, these "Unexpected exception" errors should also take down the process. wdyt?
Source:
public void close() throws IOException { txnLog.close(); txnLog = null; snapLog.close(); snapLog = null; }

Target:
if you set this variable to null then calling twice this method will result in an ugly NullPointerException what about ``` try { if (txnLog != null) { txnLog.close(); } } finally { txnLog = null; } ```
Source:
public void testBooleanRetrievalFromProperty() { boolean value = true; boolean defaultValue = false; x509Util = new ClientX509Util(); System.setProperty(x509Util.getSslProtocolProperty(), Boolean.toString(value)); ZKConfig conf = new ZKConfig(); boolean result = conf.getBoolean(x509Util.getSslProtocolProperty(), defaultValue); assertEquals(value, result); System.clearProperty(x509Util.getSslProtocolProperty()); }

Target:
Clear properties in tearDown method @After public void tearDown() throws Exception { }
Source:
public ContainerManager(ZKDatabase zkDb, RequestProcessor requestProcessor, int checkIntervalMs, int maxPerMinute) { this(zkDb, requestProcessor, checkIntervalMs, maxPerMinute, Integer.MAX_VALUE); }

Target:
Long.MAX_VALUE ?
Source:
public void addEntry(FieldName fieldName, String value) { if (value != null) { logEntries.put(fieldName.name().toLowerCase(), value); } }

Target:
package-private ?
Source:
void closeSockSync() { try { long startTime = Time.currentElapsedTime(); sock.close(); ServerMetrics.getMetrics().SOCKET_CLOSING_TIME.add(Time.currentElapsedTime() - startTime); } catch (IOException e) { LOG.warn("Ignoring error closing connection to leader", e); } }

Target:
You might want to add 2 more things here: - double check if sock is still not `null` - make sock = null after the close to prevent further usage of the object and let GC collect it
Source:
public ClientCnxn( String chrootPath, HostProvider hostProvider, int sessionTimeout, ZKClientConfig clientConfig, Watcher defaultWatcher, ClientCnxnSocket clientCnxnSocket, boolean canBeReadOnly ) { this( chrootPath, hostProvider, sessionTimeout, clientConfig, defaultWatcher, clientCnxnSocket, 0, new byte[16], canBeReadOnly); }

Target:
On first glance it doesn't look like it conflicts with Curator. But, maybe @TisonKun can test with Curator locally. As an aside, I wonder if we shouldn't include some Curator test in ZooKeeper in the future - i.e. validate that new changes don't break Curator.
Source:
public void testRestoreWithTrustedEmptySnapFiles() throws Exception { FileTxnSnapLog.setTrustEmptySnapshotFlag(true); runTest(false, true); assertFalse("Trust empty snapshot flag should be reset after first use.", FileTxnSnapLog.getTrustEmptySnapshotFlag()); }

Target:
what about resetting the value to "false" in a finally block, this way if the test fails we will be sure that the rest of the tests are executed with the default value
Source:
public synchronized void startup() { if (sessionTracker == null) { createSessionTracker(); } startSessionTracker(); setupRequestProcessors(); startRequestThrottler(); registerJMX(); startJvmPauseMonitor(); registerMetrics(); setState(State.RUNNING); requestPathMetricsCollector.start(); localSessionEnabled = sessionTracker instanceof UpgradeableSessionTracker && ((UpgradeableSessionTracker) sessionTracker).isLocalSessionsEnabled(); notifyAll(); }

Target:
this 'instanceof' looks like a 'code smell' what about adding a isLocalSessionsEnabled method to the base class (SessionTracker) with a default return value of 'false' ?
Source:
public void trackSent(long timestamp) { if (enabled) sentBuffer.write(new BufferedMessage(timestamp)); }

Target:
Should we keep the same coding format and change it to: if (enabled) { ... }
Source:
protected abstract KeyStore keyStoreInstance() throws KeyStoreException; private char[] passwordStringToCharArray(String password) { return password == null ? EMPTY_CHAR_ARRAY : password.toCharArray(); }

Target:
Nit: static
Source:
void closeSocket() { try { if (sock != null && !sock.isClosed()) { sock.close(); } } catch (IOException e) { LOG.warn("Ignoring error closing connection to leader", e); } }

Target:
Just curious: why checking 'isClosed' ? Can't we call 'close' multiple times?
Source:
public int requestThrottleInflight() { if (requestThrottler != null) { return requestThrottler.getInflight(); } return 0; }

Target:
consider make this private as it's not called elsewhere.
Source:
public void tearDown() throws Exception { zkClient.close(); zkClientB.close(); super.tearDown(); }

Target:
Please add null check for the case when `setUp()` fails early.
Source:
static void waitForReconnectDelay() { Observer.waitForReconnectDelayHelper(reconnectDelayMs); }

Target:
Nit: no need to call Observer explicitly
Source:
public int getCount() { return (int) getValue(countStr); }

Target:
why are we casting to "int" ? it the value is a "long" we must return a "long" or we have to handle the overflow some way
Source:
public int hashCode() { return Objects.hash(super.hashCode(), time); }

Target:
This is a private class used for tracking, won't change super fields, time is the only changing variable here, so only need to hash time here.
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MarkerQuorumPacket that = (MarkerQuorumPacket) o; return time == that.time; }

Target:
Don't need to compare super as what I mentioned above.
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ErrorResult that = (ErrorResult) o; return err == that.err && Objects.equals(path, that.path); }

Target:
why are you changing this line ?
Source:
public void start() { if (listenBacklog > 0) { bootstrap.option(ChannelOption.SO_BACKLOG, listenBacklog); } LOG.info("binding to port {}", localAddress); parentChannel = bootstrap.bind(localAddress).syncUninterruptibly().channel(); // Port changes after bind() if the original port was 0, update // localAddress to get the real port. localAddress = (InetSocketAddress) parentChannel.localAddress(); LOG.info("bound to port " + getLocalPort()); }

Target:
It doesn't make any difference, but it would nice for this condition to be consistent with the NIO implementation. e.g. `listenBacklog != -1` or something similar
Source:
public void setClientPortListenBacklog(int backlog) { LOG.info("clientPortListenBacklog set to " + backlog); this.listenBacklog = backlog; }

Target:
nit: I would do the action first, than the log the fact it happened.
Source:
public SSLContext get() { try { return SSLContext.getDefault(); } catch (NoSuchAlgorithmException e) { return null; } }

Target:
nit: `throw new RuntimeException(e);` so if this ever happens (unlikely), the error will be more obvious in the test
Source:
public void testWriteBool() { final boolean expected = false; final String tag = "tag1"; checkWriterAndReader( (oa) -> oa.writeBool(expected, tag), (ia) -> { boolean actual = ia.readBool(tag); Assert.assertEquals(expected, actual); } ); }

Target:
Sorry, last nit: any reason for not using static imports?
Source:
public Boolean serializeZxidDigest(OutputArchive oa) throws IOException { if (!DigestCalculator.digestEnabled()) { return false; } ZxidDigest zxidDigest = lastProcessedZxidDigest; if (zxidDigest == null) { // write an empty digest zxidDigest = new ZxidDigest(); } zxidDigest.serialize(oa); return true; }

Target:
Nit: boolean not Boolean
Source:
public Boolean deserializeZxidDigest(InputArchive ia) throws IOException { if (!DigestCalculator.digestEnabled()) { return false; } try { ZxidDigest zxidDigest = new ZxidDigest(); zxidDigest.deserialize(ia); if (zxidDigest.zxid > 0) { digestFromLoadedSnapshot = zxidDigest; } return true; } catch (EOFException e) { LOG.warn("Got EOF exception while reading the digest, " + "likely due to the reading an older snapshot."); return false; } }

Target:
Nit: boolean
Source:
public default void inc() { inc(1); }

Target:
public keyword is not needed in interfaces. All of them are public by default
Source:
public void testOrderWithDifferentPrefixes() throws Exception { String[] names = { "r-3", "r-2", "r-1", "w-2", "w-1" }; // names with duplicated sequence numbers are not included in the result String[] expected = { "r-1", "r-2", "r-3" }; assertOrderedNodeNames(names, expected); }

Target:
Why have you removed "w-1" and "w-2" elements from here? I think the expected list could be: `String[] expected = { "r-1", "w-1", "r-2", "w-2", "r-3"};`
Source:
public boolean close(int waitForShutdownTimeoutMs) throws InterruptedException { close(); if (waitForShutdownTimeoutMs > 0) { return testableWaitForShutdown(waitForShutdownTimeoutMs); } return false; }

Target:
I don't think this check is needed - actually, it sounds better to remove this check so a negative value will trigger illegal argument exception indicates something is wrong in upstream code, because it's hard to know if the negative value is passed on purpose, or is an accident.
Source:
private void createSocket() throws X509Exception, IOException { if (self.isSslQuorum()) { if (x509Util == null) { x509Util = new QuorumX509Util(); } sock = x509Util.createSSLSocket(); } else { sock = new Socket(); } sock.setSoTimeout(self.tickTime * self.initLimit); }

Target:
minor style nit: prefer you return the socket from this method and assign to `sock` in the caller.
Source:
private void configureSSLServerSocket(SSLServerSocket sslServerSocket) { SSLParameters sslParameters = sslServerSocket.getSSLParameters(); sslParameters.setNeedClientAuth(true); if (cipherSuites != null) { LOG.debug("Setup cipher suites for server socket: {}", Arrays.toString(cipherSuites)); sslParameters.setCipherSuites(cipherSuites); } sslServerSocket.setSSLParameters(sslParameters); }

Target:
do we need this check here? `cipherSuites` should not be null when we reach here.
Source:
private void configureSSLSocket(SSLSocket sslSocket) { if (cipherSuites != null) { SSLParameters sslParameters = sslSocket.getSSLParameters(); LOG.debug("Setup cipher suites for client socket: {}", Arrays.toString(cipherSuites)); sslParameters.setCipherSuites(cipherSuites); sslSocket.setSSLParameters(sslParameters); } }

Target:
do we need this check here? cipherSuites should not be null when we reach here.
Source:
public void testFourLetterWordsAllDisabledByDefault() throws Exception { stopServer(); FourLetterCommands.resetWhiteList(); System.setProperty("zookeeper.4lw.commands.whitelist", "stat"); startServer(); // Default white list for 3.5.x is empty, so all command should fail. verifyAllCommandsFail(); TestableZooKeeper zk = createClient(); String sid = getHexSessionId(zk.getSessionId()); verifyAllCommandsFail(); zk.getData("/", true, null); verifyAllCommandsFail(); zk.close(); verifyFuzzyMatch("stat", "Outstanding"); verifyAllCommandsFail(); }

Target:
sid is not used
Source:
public void testBasic() throws IOException, InterruptedException, KeeperException { ZooKeeper zk = null; try { zk = createClient(new CountdownWatcher(), hostPort); zk.addPersistentWatch("/a/b", persistentWatcher); internalTestBasic(zk); } finally { if (zk != null) { zk.close(); } } }

Target:
ZooKeeper supports try-with-resources so using that may make this code cleaner
Source:
private boolean shouldAllowSaslFailedClientsConnect() { return Boolean.getBoolean(ALLOW_SASL_FAILED_CLIENTS); }

Target:
Last nit: static
Source:
public void setup() throws InterruptedException, KeeperException.NoNodeException { System.setProperty(authProvider, superDigest); QuorumPeerConfig.setReconfigEnabled(false); // Get a three server quorum. qu = new QuorumUtil(1); qu.disableJMXTest = true; try { qu.startAll(); } catch (IOException e) { Assert.fail("Fail to start quorum servers."); } resetZKAdmin(); }

Target:
we don't throw NoNodeException anymore
Source:
public ClientCnxnSocketNIO(ZKClientConfig clientConfig) throws IOException { this.clientConfig = clientConfig; initProperties(); }

Target:
You're probably making this public for test purposes. Instead of making such methods public, we should be having the tests in the appropriate package so that we don't need to use the access modifiers inappropriately. I say inappropriately because this method shouldn't really be exposed to applications, it should not be public.
Source:
public static boolean isTransactionFile(String file) throws IOException { try { RandomAccessFileReader reader = new RandomAccessFileReader(new File(file)); BinaryInputArchive logStream = new BinaryInputArchive(reader); FileHeader fhdr = new FileHeader(); fhdr.deserialize(logStream, "fileheader"); } finally { reader.close(); } return fhdr.getMagic() == FileTxnLog.TXNLOG_MAGIC; }

Target:
Mixture of spaces and tab on this line and several others. Do we enforce any sort of consistency when it comes to formatting in this project? I seem to see both.
Source:
public void fireEventListeners(final Event event) { final ArrayList<EventListener> listeners = new ArrayList<>(this.listeners); for (final EventListener listener : listeners) { try { listener.handleEvent(event); } catch (Exception e) { logger.warn("Error while calling handleEvent for: " + listener.getClass()); logger.warn(e.getMessage(), e); } } }

Target:
If you use java.lang.RuntimeException and java.lang.Error, please include those here.
Source:
public static DateTimeZone getTimeZone(String timezoneParam) { try { return DateTimeZone.forID(timezoneParam); } catch (final IllegalArgumentException e) { TimeZone zone = ZoneInfo.getTimeZone(timezoneParam); if(null == zone) return null; try { return DateTimeZone.forTimeZone(zone); } catch (final IllegalArgumentException e1) { return null; } } }

Target:
Can you write this in curly braces block instead of 1 line?
Source:
public void tearDown() throws Exception { if (this.fileWatcher != null) { this.fileWatcher.close(); } // Cleanup directories final Path workDir = PATH.getParent(); if (Files.exists(workDir)) { Files.deleteIfExists(PATH); Files.delete(workDir); } }

Target:
How about using a `TemporaryFolder` `@Rule` for the workDir to simplify code? For example here: https://github.com/azkaban/azkaban/blob/7efe67b0602fdc65f18fc0e2f91e14a57c2d845e/azkaban-exec-server/src/test/java/azkaban/execapp/event/LocalFlowWatcherTest.java#L31-L32
Source:
public void shutdown() { if(null != this.queueProcessor) this.queueProcessor.shutdown(); if(null != this.updaterThread) this.updaterThread.shutdown(); }

Target:
Can you please follow coding guidelines and put the code in curly braces?
Source:
private static FileSystem getCachedHttpFileSystem(final Configuration conf, final AzkabanCommonModuleConfig azConfig) { // Ensure the necessary props are not specified to enable CachedHttpFileSystem if (azConfig.getOriginDependencyRootUri() == null) return null; else validateURI(azConfig.getOriginDependencyRootUri(), CHTTP_SCHEME); try { return FileSystem.get(azConfig.getOriginDependencyRootUri(), conf); } catch (final IOException e) { log.error("Unable to initialize CachedHttpFileSystem.", e); throw new AzkabanException(e); } }

Target:
Please follow the style guide mentioned in CONTRIBUTING.md, use braces for if/else statements, https://google.github.io/styleguide/javaguide.html#s4-formatting
Source:
public String getFileName() { return fileName; }

Target:
use keyword "this" in these methods before member names.
Source:
public List<String> getGroupsWithPermission(final Type type) { final ArrayList<String> groups = new ArrayList<>(); for (final Map.Entry<String, Permission> entry : this.groupPermissionMap.entrySet()) { final Permission perm = entry.getValue(); if (perm.isPermissionSet(type)) { groups.add(entry.getKey()); } } return groups; }

Target:
Use " List<String>" instead of ArrayList<String> in declaration.
Source:
private void setNeedsMoreUsersIfAppropriate(final Page page, final Project project, final Session session) { // See if the project has only one admin user with no admin groups. // If it does AND the forceMultipleUsers flag is set AND the current user has the ability to add // an admin, let's force the user to do so before allowing any execution or scheduling of flows. boolean hasEnoughUsersGroups = project.getUsersWithPermission(Type.ADMIN).size() > 1 || project.getGroupsWithPermission(Type.ADMIN).size() > 0 || !hasPermission(session.getUser(), Type.ADMIN) || !this.forceMultipleUsers; page.add("hasEnoughUsersGroups", hasEnoughUsersGroups); }

Target:
nitpick : move this.forceMultipleUsers to the front, if the config is off, we fallback to existing logic.
Source:
public Object isSlaFailed() { final ExecutableFlow flow; try { flow = this.executorLoader.fetchExecutableFlow(this.execId); logger.info("Flow for execid " + this.execId + " is " + flow.toString()); } catch (final ExecutorManagerException e) { logger.error("Can't get executable flow.", e); // something wrong, send out alerts return true; } return isSlaMissed(flow); }

Target:
Why to you need to print out `flow.toString()`? Would `flow.getId()` be better?
Source:
public static State createInstance(long startTime, long endTime, long lastUpdatedTime, int numTrail, int numSuccess, int numFailure, int numIgnored, boolean isPaused, int rampStage, boolean isActive) { return new State() .setStartTime(startTime) .setEndTime(endTime) .setLastUpdatedTime(lastUpdatedTime) .setNumOfTrail(numTrail) .setNumOfSuccess(numSuccess) .setNumOfFailure(numFailure) .setNumOfIgnored(numIgnored) .setPaused(isPaused) .setRampStage(rampStage) .setActive(isActive); }

Target:
Add `final` keyword? Also other places when necessary.
Source:
public void setLocked(boolean locked) { isLocked = locked; }

Target:
Please follow the style guide in CONTRIBUTING.md to add `this` to field access. You can turn on > save action .
Source:
public double getCpuLoad() { if (this.collectedCpuStats.isEmpty()) { return -1; } final CpuStats oldestCpuStats = this.collectedCpuStats.pollLast(); final CpuStats newestCpuStats = getCpuStats(); this.collectedCpuStats.push(newestCpuStats); return calcCpuLoad(oldestCpuStats, newestCpuStats); }

Target:
Is calculating the newest and oldest data points the right way to get CPU load? Let's discuss more about it.
Source:
public String getRunningFlowIds() { final List<Integer> allIds = new ArrayList<>(); try { getExecutionIdsHelper(allIds, this.executorLoader.fetchUnfinishedFlows().values()); } catch (final ExecutorManagerException e) { this.logger.error("Failed to get running flow ids.", e); } return allIds.toString(); }

Target:
why returning a string instead of a list?
Source:
public String getQueuedFlowIds() { final List<Integer> allIds = new ArrayList<>(); try { getExecutionIdsHelper(allIds, this.executorLoader.fetchQueuedFlows()); } catch (final ExecutorManagerException e) { this.logger.error("Failed to get queued flow ids.", e); } return allIds.toString(); }

Target:
same question as above.
Source:
public int getDisplayExecutionPageSize() { return displayExecutionPageSize; }

Target:
We may don't need to introduce `public` here? package-access is good enough?
Source:
public static void setupFolder() { workingDirString = currentDirString + "/../temp/TestHadoopSpark"; workingDirFile = new File(workingDirString); libFolderFile = new File(workingDirFile, "lib"); libFolderFile = new File(workingDirFile, "lib"); executionJarFile = new File(libFolderFile, "hadoop-spark-job-test-execution-x.y.z-a.b.c" + ".jar"); libraryJarFile = new File(libFolderFile, "library.jar"); }

Target:
duplicate?
Source:
public boolean containsKey(final String key) { return super.get(key.toLowerCase()) != null; }

Target:
super.containsKey(key.toLowerCase()) ? given ConcurrentHashMap already provides containsKey
Source:
private void write(final String string) { // If logs are looping, write message to system's stderr then rebind. if (logIsLooping()) { unbindStdOutAndErrToLog(); System.err.println(string); bindStdOutAndErrToLog(); } else { logger.log(this.level, string); } }

Target:
How big is the overhead to do this check on every log?
Source:
public List<byte[]> handle(final ResultSet rs) throws SQLException { if (!rs.next()) { return Collections.emptyList(); } final ArrayList<byte[]> data = new ArrayList<>(); do { final byte[] bytes = rs.getBytes(1); data.add(bytes); } while (rs.next()); return data; }

Target:
List<byte[]> ?
Source:
public void start() { try { this.scheduler.start(); } catch (final SchedulerException e) { logger.warn("Error starting Quartz scheduler: ", e); } logger.info("Quartz Scheduler started."); }

Target:
warn seems too relaxing for this kind of exception. maybe error?
Source:
Scheduler getScheduler() { return this.scheduler; }

Target:
access modifiers?
Source:
public void shutdownNow() { logger.warn("Shutting down FlowRunnerManager now..."); this.executorService.shutdownNow(); this.triggerManager.shutdown(); deleteExecutionDirectory(); }

Target:
My mistake, I mis-interpreted the call to the shotdown method for the triggerManager as the call for the FlowRunnerManager.
Source:
public void testInjection() throws Exception { props .put(Constants.ConfigurationKeys.AZKABAN_STORAGE_LOCAL_BASEDIR, AZKABAN_LOCAL_TEST_STORAGE); final Injector injector = Guice.createInjector( new AzkabanCommonModule(props), new AzkabanExecServerModule() ); SERVICE_PROVIDER.unsetInjector(); SERVICE_PROVIDER.setInjector(injector); assertNotNull(SERVICE_PROVIDER.getInstance(AzkabanExecutorServer.class)); }

Target:
Why is this change necessary?
Source:
public void doAction() throws Exception { logger.info("ready to do action " + getDescription()); FlowRunnerManager flowRunnerManager = ServiceProvider.SERVICE_PROVIDER.getInstance(FlowRunnerManager.class); flowRunnerManager.cancelJobBySLA(execId, jobId); }

Target:
Should `flowRunnerManager ` be initialized in the body of constructor?
Source:
private static String getSqlScriptsDir() throws IOException { // Dummy because any resource file works. final String dummyResourcePath = getUserManagerXmlFile(); Path resources = Paths.get(dummyResourcePath).getParent(); Path azkabanRoot = resources.getParent().getParent().getParent().getParent(); File sqlScriptDir = Paths.get(azkabanRoot.toString(), AZKABAN_DB_SQL_PATH).toFile(); return props.getString(AzkabanDatabaseSetup.DATABASE_SQL_SCRIPT_DIR, sqlScriptDir.getCanonicalPath()); }

Target:
Why do you need to care about what the entry is in the props? The test is in full control of what's in the props. Right?
Source:
public DatabaseOperatorImpl(QueryRunner queryRunner){ this.queryRunner = queryRunner; requireNonNull(queryRunner.getDataSource(), "data source must not be null."); }

Target:
i think it's better to put requireNonNull(queryRunner.getDataSource(), "data source must not be null.") before this.queryRunner = queryRunner.
Source:
public Boolean isActiveProject(int id) { Project project = getProject(id); return project != null; }

Target:
getProject(id) != null simpler
Source:
public void testRemovingExecutor() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); Executor executor = loader.addExecutor("localhost1", 12345); loader.removeExecutor("localhost1", 12345); Executor fetchedExecutor = loader.fetchExecutor("localhost1", 12345); Assert.assertNull(fetchedExecutor); }

Target:
May be its safer to assert that it exists before and then assert that is doesn't after delete.
Source:
private void attachKafkaAppender(KafkaLog4jAppender appender) { // If present, remove the existing kafka appender if (kafkaAppender.isPresent()) { removeAppender(kafkaAppender); flowLogger.info("Removed old Kafka appender for job " + this.jobId); } kafkaAppender = Optional.of(appender); logger.addAppender(kafkaAppender.get()); logger.setAdditivity(false); flowLogger.info("Attached new Kafka appender for job " + this.jobId); }

Target:
If you are sure and expect this should not happen, may be change it to an assert?
Source:
private void removeAppender(Optional<Appender> appender) { removeAppender(appender.get()); appender = Optional.empty(); }

Target:
Is this step necessary? I thought it would only affect the reference in this method's scope.
Source:
public static boolean isCronExpressionValid(String cronExpression, DateTimeZone timezone) { if (!CronExpression.isValidExpression(cronExpression)) { return false; } else { CronExpression cronExecutionTime = parseCronExpression(cronExpression, timezone); if (cronExecutionTime == null || cronExecutionTime.getNextValidTimeAfter(new Date()) == null) { return false; } return true; } }

Target:
so we are trying to avoid scheduling flows in the past. right ? Can you please add a small note. nit: else statement is not required.
Source:
public boolean isRecurring() { return period == null && cronExpression == null ? false : true; }

Target:
can simply to `return period != null || cronExpression != null;` If you use IntelliJ, it automatically suggests these refactors.
Source:
public ExecutorSelector(List<String> filterList, Map<String,Integer> comparatorList) { super(null == filterList || filterList.size() == 0 ? null : new ExecutorFilter(filterList), null == comparatorList || comparatorList.size() == 0 ? null : new ExecutorComparator(comparatorList)); }

Target:
small thing - filterList.isEmpty() is shorter
Source:
public static ExecutorApiClient getInstance() { if (null == instance) { synchronized (ExecutorApiClient.class) { if (null == instance) { instance = new ExecutorApiClient(); } } } return instance; }

Target:
Since the constructor doesn't do much, another way to initialize an instance of this class w/o doing any synchronization is: private static ExecutorApiClient instance = new ExecutorApiClient();
Source:
protected synchronized void preTrackingEventMethod() { // nothing to finalize value is already updated }

Target:
Why do you have `synchronized` on an empty method?
Source:
public void addPassMsgs(Set<String> msgs) { _passMsgs.addAll(msgs); }

Target:
This will throw a NPE if msgs is null. You probably want to add a null check. Same thing for the other methods.
Source:
private void insertJVMAargs() { String flowName = node.getParentFlow().getFlowId(); String jobId = node.getId(); String jobJVMArgs = String.format( "-Dazkaban.flowid=%s -Dazkaban.execid=%s -Dazkaban.jobid=%s", flowName, executionId, jobId); String previousJVMArgs = props.get(JavaProcessJob.JVM_PARAMS); if (previousJVMArgs == null) { previousJVMArgs = jobJVMArgs; } else { previousJVMArgs += " " + jobJVMArgs; } logger.info("job JVM args: " + previousJVMArgs); props.put(JavaProcessJob.JVM_PARAMS, previousJVMArgs); }

Target:
I think it would be easier to read if you just combined all this into ``` jobJVMArgs += (previousJVMArgs == null) ? "" : " " + previousJVMArgs ``` and then used jobJVMArgs below instead of previousJVMArgs. I think it'll also think the "ps -ef" output will be easier to read if you put the -Dazkaban... JVM params first, before the previousJVMArgs.
Source:
public void handleEvent(Event event) { if (event.getType() == Event.Type.FLOW_FINISHED) { FlowRunner flowRunner = (FlowRunner) event.getRunner(); ExecutableFlow flow = flowRunner.getExecutableFlow(); recentlyFinishedFlows.put(flow.getExecutionId(), flow); logger.info("Flow " + flow.getExecutionId() + " is finished. Adding it to recently finished flows list."); runningFlows.remove(flow.getExecutionId()); submittedFlows.remove(flow.getExecutionId()); } }

Target:
This is old code that should be removed. The Key in submittedFlows is no longer an Integer but a Future<?>.
Source:
private void persist(LocalDocument doc) throws IOException, JsonException { logger.debug("Saving document to RemotePipeline.."); if(!remotePipeline.save(doc)) { // TODO: Why are we cloning here? LocalDocument ld = new LocalDocument(doc); IOException e = new IOException("Unable to save changes to core"); if(!onException(ld, e)) { logger.error("Unable to persist an error to the database for doc '" + doc.getID() + "'", e); } } }

Target:
Wondering the same thing about this line. It was introduced in 5dc4438fbdcc7ad6015a9d7574e00072b0534794. I can only think of some kind of concurrency issue. With `RemotePipeline` now being immutable, I can't see what cloning would achieve.
Source:
public String getPdxDiskStoreName() { Assert.state(!StringUtils.isEmpty(pdxDiskStoreName), "The PDX Disk Store name was not properly initialized!"); return pdxDiskStoreName; }

Target:
Assert not required if field is final
Source:
public void onEditFailure(@NonNull Throwable caught) { showProgressBar(false); if (caught instanceof MwException) { handleEditingException((MwException) caught); L.e(caught); } else { showRetryDialog(caught); L.e(caught); } }

Target:
Looks like the common `L.e(caught)` can be extracted to the bottom.
Source:
void scrollToSection(@NonNull String sectionAnchor) { bridge.execute(JavaScriptActionHandler.prepareToScrollTo(sectionAnchor, "{ highlight: false }")); for (Section section : adapter.sections) { if (section.getAnchor().equals(sectionAnchor)) { scrollToSection(section); break; } } }

Target:
Do we still need this other `scrollToSection()` call, then? It sounds like we're making it scroll twice.
Source:
public Set<String> getEditRoles() { Set<String> roleSet = new HashSet<>(); roleSet.add(edit); return edit != null ? Collections.unmodifiableSet(roleSet) : Collections.emptySet(); }

Target:
The logic does not make sense to me. The `edit != null` logic should happen before creating any object, otherwise, it will be a redundant object.
Source:
ErrorType getErrorType(@Nullable Throwable caught) { if (caught != null && is404(caught)) { return ErrorType.PAGE_MISSING; } else if (caught != null && isTimeout(caught)) { return ErrorType.TIMEOUT; } else if (caught != null && isOffline(caught)) { return ErrorType.OFFLINE; } return ErrorType.GENERIC; }

Target:
Do these `caught != null` null check conditions necessary?
Source:
public void setDescription(@Nullable String text) { if (invokeSource != SUGGESTED_EDITS_ADD_CAPTION && invokeSource != SUGGESTED_EDITS_TRANSLATE_CAPTION) { pageDescriptionText.setText(text); } }

Target:
This will break the current logic of showing "added" contribution
Source:
public void setPageTitle(@NonNull PageTitle pageTitle) { this.pageTitle = pageTitle; originalDescription = pageTitle.getDescription(); setHintText(); if (invokeSource != SUGGESTED_EDITS_ADD_CAPTION && invokeSource != SUGGESTED_EDITS_TRANSLATE_CAPTION) { setDescription(originalDescription); } setReviewHeaderText(false); }

Target:
If a user added caption from the Suggested edits flow, this will break the current logic of showing the "added" caption.
Source:
public void dispose() { if (disposables != null && !disposables.isDisposed()) { disposables.clear(); } }

Target:
These checks do not need to be performed.
Source:
public String getLeadingImageEditLang() { return isTranslation ? targetSummary.getPageTitle().getWikiSite().languageCode() : sourceSummary.getPageTitle().getWikiSite().languageCode(); }

Target:
This will produce a NPE and crash the app if `sourceSummary` or `targetSummary` is null. This can happen if the activity is destroyed (e.g. "don't keep activities) and then recreated when coming back from editing.
Source:
void setFadeEnabled(boolean enabled) { fadeEnabled = enabled; // to avoid the toolbar applies the opacity before image loaded pageFragment.getWebView().postDelayed(this::update, DELAY_UPDATE_MS); }

Target:
When I see code that uses `postDelayed` to work around a problem, it usually means that there's an incomplete understanding of the underlying issue. (see below)
Source:
public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); getWindow().setStatusBarColor(Color.TRANSPARENT); // TODO: translucent status will affect the navigation bar color? getWindow().setNavigationBarColor(0); }

Target:
Fixed and done.
Source:
private void updateUI() { username.setText(AccountUtil.getUserName()); contributionsText.setText(getResources().getQuantityString(R.plurals.edit_action_contribution_count, Prefs.getTotalUserDescriptionsEdited())); requireActivity().invalidateOptionsMenu(); }

Target:
Needs to update the `contributionsText.setText()` since the `R.plurals.edit_action_contribution_count` contains a `%d`
Source:
public static String getThemePageLibClass(Theme theme) { switch (theme.getFunnelName()) { case "light": return "pagelib_theme_light"; case "dark": return "pagelib_theme_dark"; case "black": return "pagelib_theme_black"; case "sepia": return "pagelib_theme_sepia"; default: return "pagelib_theme_light"; } }

Target:
Maybe it is okay to remove the `case "light"` since it is a default case?
Source:
private String requestPath(Uri requestUri) { if (!requestUri.getPath().isEmpty()) return requestUri.getPath(); else return "/"; }

Target:
Please use ternary operator `?`.
Source:
private static String convertHost(final String host) { if (host == null) { return null; } return stripDotSuffix(host).toUpperCase(); }

Target:
Please use ? ternary operator
Source:
private static String convertDomain(final String domain) { if (domain == null) { return null; } return stripDotSuffix(domain).toUpperCase(); }

Target:
Please use ? ternary operator
Source:
private ExecutionList executionList() { for (;;) { ExecutionList executionListLocal = this.executionList; if (executionListLocal != null) { return executionListLocal; } ExecutionList r = new ExecutionList(); if (executionListField.compareAndSet(this, null, r)) { return r; } } }

Target:
Are you sure we need this?
Source:
public ClientStats getClientStats() { final ChannelManager channelManager = requestSender.getChannelManager(); final long activeConnectionCount = channelManager.getOpenChannels().stream().filter(channel -> !channel.isOpen()).count(); final long idleConnectionCount = channelManager.getOpenChannels().stream().filter(Channel::isOpen).count(); return new ClientStats(activeConnectionCount, idleConnectionCount); }

Target:
Should be declared in `AsyncHttpClient` interface. Implementation here should be flagged with @Override
Source:
private static String getPartitionId(InetAddress overrideAddress, Request request, ProxyServer proxyServer) { return overrideAddress != null ? overrideAddress.toString() + "_" : "" + request.getConnectionPoolPartitioning() .getPartitionKey(request.getUri(), proxyServer).toString(); }

Target:
is it supposed to be (overrideAddress != null ? overrideAddress.toString() + "_" : "") + request.getConnectionPoolPartitioning() .getPartitionKey(request.getUri(), proxyServer).toString(); ?
Source:
private static boolean attemptInstantiation() { if (instantiated == false) { lock.lock(); try { if (instantiated == false) { asyncHttpClientImplClass = AsyncImplHelper .getAsyncImplClass(AsyncImplHelper.ASYNC_HTTP_CLIENT_IMPL_SYSTEM_PROPERTY); instantiated = true; } } finally { lock.unlock(); } } return (asyncHttpClientImplClass != null); }

Target:
!instantiated
Source:
public boolean unRegister(String name) { if (asyncHttpClientMap.remove(name) == null) return false; else return true; }

Target:
`return asyncHttpClientMap.remove(name) != null`
Source:
@Test public void smokes() throws Exception { assertRoundTrip("test"); assertRoundTrip("."); assertRoundTrip(".."); assertRoundTrip("test/foo"); assertRoundTrip("test%bar"); assertRoundTrip("test #1"); }

Target:
```suggestion @Test public void smokes() throws Exception { ```
Source:
public List<BranchProperty> getPropertiesFor(SCMHead head) { List<BranchProperty> properties = new ArrayList<>(); for (Named named : namedExceptions) { if (named.isMatch(head)) { properties.addAll(named.getProps()); } } if (properties.isEmpty()) { // if no one defined adds default properties.addAll(defaultProperties); } return properties; }

Target:
This looks unrelated to the main purpose of the PR, and it seems like it could be a breaking change because branch jobs for existing projects could end up with different properties after the update. Why are the changes to this method needed?
Source:
private @NonNull Action[] getRevisionActions(@NonNull SCMRevision revision, String rawName) { Action[] revisionActions = new Action[0]; try { List<Action> actions = source.fetchActions(revision, event, listener); revisionActions = actions.toArray(new Action[0]); } catch (IOException | InterruptedException e) { printStackTrace(e, listener.error("Could not fetch metadata for revision %s of branch %s", revision, rawName)); } return revisionActions; }

Target:
Slight performance enhancement... ```suggestion revisionActions = actions.toArray(new Action[actions.size()]); ```
Source:
public final boolean automaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision, @CheckForNull SCMRevision prevRevision, @NonNull TaskListener listener) { return automaticBuild(source, head, currRevision, prevRevision, listener, null); }

Target:
last seen should be defaulted to lastBuilt
Source:
private static @NonNull InputStream readFilePath(@NonNull FilePath index) throws IOException, InterruptedException { InputStream stream = index.read(); assert stream != null; return stream; }

Target:
We do not use Glick-style annotations. If the method returns `@NonNull` then the `@NonNull` shall be on the line preceding the access modifiers not between the access modifiers and the return type
Source:
public synchronized void save() throws IOException { if (BulkChange.contains(this)) { return; } getStateFile().write(this); SaveableListener.fireOnChange(this, getStateFile()); }

Target:
Fire the event outside of the monitor.
Source:
public void onUpdated(Item item) { if (item instanceof SCMSourceOwner) { try { ((SCMSourceOwner) item).getSCMSources(); } catch (NullPointerException e) { check = false; throw e; } } }

Target:
:ant: not a good test style, since this will make no sense after the bug is fixed, and will not catch unrelated problems. Better to set `check` to `false` initially, then set it to `true` after calling `getSCMSources` (with no `catch` block).
Source:
public FreeStyleProject newInstance(Branch branch) { FreeStyleProject job = new FreeStyleProject(getOwner(), branch.getName()); job.onCreatedFromScratch(); FreeStyleProject spied = spy(job); // Do nothing.. Running the actual build is not desired/required (and not possible) in this tests. when(spied.scheduleBuild()).thenReturn(false); setBranch(spied, branch); return spied; }

Target:
Could do this without mocks by using a custom `Project` subclass that overrides `scheduleBuild`.
Source:
public abstract @CheckForNull MultiBranchProject<?,?> createProject(@Nonnull ItemGroup<?> parent, @Nonnull String name, @Nonnull List<? extends SCMSource> scmSources, @Nonnull Map<String,Object> attributes, @Nonnull TaskListener listener) throws IOException, InterruptedException; @Override public MultiBranchProjectFactoryDescriptor getDescriptor() { return (MultiBranchProjectFactoryDescriptor) super.getDescriptor(); }

Target:
style guide
Source:
@DataBoundSetter public final void setParameterDefinitions(List<ParameterDefinition> parameterDefinitions) { this.parameterDefinitions = parameterDefinitions; }

Target:
code style
Source:
@Override public boolean filter(Object context, Descriptor descriptor) { if (context instanceof MultiBranchProject && descriptor instanceof BranchPropertyDescriptor) { return ((BranchPropertyDescriptor) descriptor).isApplicable((MultiBranchProject) context); } else { return true; } }

Target:
code style
Source:
public @NonNull PersistedList<BranchSource> getSourcesList() { return sources; }

Target:
No way not in the middle :bug: code style
Source:
public @CheckForNull Node getBuiltOn() { Jenkins j = Jenkins.getInstance(); if (builtOn == null || builtOn.isEmpty() || j == null) { return j; } else { return j.getNode(builtOn); } }

Target:
:bug: code style
Source:
@Override protected boolean isApplicable(MultiBranchProjectDescriptor projectDescriptor) { for (BranchProjectFactoryDescriptor d : projectDescriptor.getProjectFactoryDescriptors()) { Type factoryType = Types.getBaseClass(d.clazz, BranchProjectFactory.class); Type jobType = Types.getTypeArgument(factoryType, 0, /* if using rawtypes, err on the conservative side */ Project.class); if (Project.class.isAssignableFrom(Types.erasure(jobType))) { return true; } } return false; }

Target:
code style
Source:
<T> void uninstallSubscriber(Class<T> type, Subscriber<T> subscriber) { Map<Subscriber, Subscriber> subscribers = subscribersByType.get(type); if (subscribers != null) { Subscriber original = subscribers.remove(subscriber); if (original != null) { original.invalidate(); return; } } throw new IllegalArgumentException( "Missing subscriber for an annotated method. Is " + type + " registered?"); }

Target:
`return` should be one line below. The sample app crashes (wrong missing subscriber exception) as soon as you pause the app.
Source:
private ExecutionType getRandomExecutionType(Bundle bundle) throws Exception { ExecutionType current = bundle.getProcessObject().getOrder(); Random r = new Random(); ExecutionType[] values = ExecutionType.values(); int i; do { i = r.nextInt(values.length); } while (current.equals(values[i])); return values[i]; }

Target:
it is generally recommended to use == for enums comparison
Source:
public void setup(Method method) throws Exception { Util.print("test name: " + method.getName()); bundles[0] = new Bundle(); bundles[0] = Util.readELBundles()[0][0]; bundles[0] = new Bundle(bundles[0], cluster.getEnvFileName(), cluster.getPrefix()); bundles[0].setInputFeedDataPath(feedInputPath); bundles[0].setProcessWorkflow(aggregateWorkflowDir); }

Target:
No need for bundles[0] = new Bundle();
Source:
public static void deleteDirIfExists(String hdfsPath, FileSystem fs) throws IOException { Path path = new Path(hdfsPath); if (fs.exists(path)) { System.out.println("Deleting HDFS path: "+ path + " on "+fs.getConf().get("fs.default.name")); fs.delete(path, true); } }

Target:
Use Logger.
Source:
public static boolean isIdentical(String expected, String actual) throws IOException, SAXException { XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreAttributeOrder(true); Diff diff = XMLUnit.compareXML(expected, actual); System.out.println(diff); return diff.identical(); }

Target:
Use a logger object.