auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static List<ACL> supervisorZkAcls() { List<ACL> acls = new ArrayList<>(); acls.add(ZooDefs.Ids.CREATOR_ALL_ACL.get(0)); acls.add(new ACL((ZooDefs.Perms.READ ^ ZooDefs.Perms.CREATE), ZooDefs.Ids.ANYONE_ID_UNSAFE)); return acls; }

Target:
In the original code this was a static final const value. It is probably not that big of a deal, but it would be nice to keep it the same if possible.
Source:
private void registerWorkerNumGauge(String name, final Map conf) { StormMetricsRegistry.registerGauge("supervisor:num-slots-used-gauge", new Callable<Integer>() { @Override public Integer call() throws Exception { Collection<String> pids = SupervisorUtils.supervisorWorkerIds(conf); return pids.size(); } }); }

Target:
name argument is not used.
Source:
private static Server removeNonSslConnector(Server server) { for (Connector c : server.getConnectors()) { if (c != null && c instanceof SslSocketConnector) { server.removeConnector(c); } } return server; }

Target:
connector should be removed if it is not a SslSocketConnector
Source:
public void isZkAuthenticationConfiguredStormServerWithPropertyTest() { String key = "java.security.auth.login.config"; String oldValue = System.getProperty(key); try { System.setProperty("java.security.auth.login.config", "anything"); Assert.assertTrue(Utils.isZkAuthenticationConfiguredStormServer(emptyMockMap())); } catch (Exception ignore) { } finally { // reset property if (oldValue == null) { System.clearProperty(key); } else { System.setProperty(key, oldValue); } } }

Target:
We don't want to ignore this exception. Let it fail the test if need be.
Source:
public void isSimulatingReturnsTrueDuringSimulationTest() { Assert.assertFalse(Time.isSimulating()); Time.startSimulating(); Assert.assertTrue(Time.isSimulating()); Time.stopSimulating(); }

Target:
Lets put this in a finally so we are sure we always stop simulating time. ``` Assert.assertFalse(Time.isSimulating()); Time.startSimulating(); try { Assert.assertTrue(Time.isSimulating()); } finally { Time.stopSimulating(); } ```
Source:
public void checkActive() { if (!this.task.isActive()) { throw new IllegalStateException("Timer is not active"); } }

Target:
This should probably not be public. It was private in the original code.
Source:
public static Object newInstance(String klass) { try { LOG.info("Creating new instance for class {}", klass); return newInstance(Class.forName(klass)); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
Please remove or make this debug
Source:
public static String eventLogsFilename(String stormId, int port) { return stormId + FILE_PATH_SEPARATOR + Integer.toString(port) + FILE_PATH_SEPARATOR + "events.log"; }

Target:
In both of these we don't need to do an Integer.toString. + will handle doing that for you.
Source:
public static Map redactValue(Map<Object, String> m, Object key) { if(m.containsKey(key)) { HashMap<Object, String> newMap = new HashMap<>(m); String value = newMap.get(key); String redacted = new String(new char[value.length()]).replace("\0", "#"); newMap.put(key, redacted); return newMap; } return m; }

Target:
I think we want to preserve the type in the return, but the passed in type is actually wrong, the value does not have to be a String, it can be anything.
Source:
public static String processPid() throws RuntimeException { String name = ManagementFactory.getRuntimeMXBean().getName(); String[] split = name.split("@"); if (split.length != 2) { throw new RuntimeException("Got unexpected process name: " + name); } return split[0]; }

Target:
RuntimeExceptions we don't need to declare that they are thrown.
Source:
public static int forceKillProcess (String pid) { return sendSignalToProcess(Long.parseLong(pid), SIGKILL); }

Target:
When is this ever a string? We only call it from one place.
Source:
public static String shellCmd (List<String> command) { List<String> changedCommands = new LinkedList<>(); for (String str: command) { if (str == null) { continue; } changedCommands.add("'" + str.replaceAll("'", "'\"'\"'") + "'"); } return StringUtils.join(changedCommands, " "); }

Target:
Can we make this an ArrayList and pre allocate the same number of arguments as command? Very minor nit.
Source:
public void shutdown() { try { log.info("window manager is being shutdown", windowManager); windowManager.shutdown(); } finally { log.info("window store is being shutdown", windowStore); windowStore.shutdown(); } }

Target:
shouldn't we log an exception why the shutdown didn't happened properly.
Source:
public boolean equals(Object object) { boolean ret = false; if (object != null && object instanceof SubSystem) { ret = (this.type.equals(((SubSystem)object).getType()) && this.hierarchyID == ((SubSystem)object).getHierarchyID()); } return ret; }

Target:
Cant enums be compared with `==` as well? Might be clearer to read. Also if you split this line up at the `&&`.
Source:
public synchronized static CgroupCenter getInstance() { if (instance == null) { instance = new CgroupCenter(); } return CgroupUtils.enabled() ? instance : null; }

Target:
should this be the first line in function instead?
Source:
public boolean isMounted(Hierarchy hierarchy) { List<Hierarchy> hierarchies = this.getHierarchies(); if (Utils.CheckDirExists(hierarchy.getDir())) { for (Hierarchy h : hierarchies) { if (h.equals(hierarchy)) { return true; } } } return false; }

Target:
Also, getHierarchies is going and reading from the file system. If getHierarchies is being called too often, you should consider caching.
Source:
public static void deleteDir(String dir) { File d = new File(dir); if (d.exists()) { if (d.isDirectory()) { if (!d.delete()) { throw new RuntimeException("Cannot delete dir " + dir); } } else { throw new RuntimeException("dir " + dir + " is not a directory!"); } } else { LOG.warn("dir does not exist!", dir); } }

Target:
There are already utility methods for doing this.
Source:
public static SubSystemType getSubSystem(String str) { switch (str) { case "blkio": return blkio; case "cpu": return cpu; case "cpuacct": return cpuacct; case "devices": return devices; case "freezer": return freezer; case "memory": return memory; case "perf_event": return perf_event; case "net_cls": return net_cls; case "net_prio": return net_prio; default: return null; } }

Target:
SubSystemType.valueOf(str) will do the exact same thing.
Source:
public void prepare(Map conf) { LOG.info("no-op for zookeeper implementation"); }

Target:
Never mind I see in the code it does the same thing.
Source:
public void removeFromLeaderLockQueue() { if (LeaderLatch.State.STARTED.equals(leaderLatch.get().getState())) { try { leaderLatch.get().close(); LOG.info("Removed from leader lock queue."); } catch (IOException e) { LOG.warn("failed to close leaderLatch!!"); } } else { LOG.info("leader latch is not started so no removeFromLeaderLockQueue needed."); } }

Target:
Here too, lets not eat the exception. At least wrap it and rethrow it, but preferably update the Interface to allow us to throw it as is.
Source:
public static String absoluteHealthCheckDir(Map conf) { String stormHome = System.getProperty("storm.home"); String healthCheckDir = String.valueOf(conf.get(Config.STORM_HEALTH_CHECK_DIR)); if (healthCheckDir.equals("null")) { return (stormHome + FILE_SEPARATOR + "healthchecks"); } else { if (new File(healthCheckDir).isAbsolute()) { return healthCheckDir; } else { return (stormHome + FILE_SEPARATOR + healthCheckDir); } } }

Target:
Why the string "null" here and an actual null in absoluteStormLocalDir?
Source:
public static String masterLocalDir(Map conf) throws IOException { String ret = String.valueOf(conf.get(Config.STORM_LOCAL_DIR)) + FILE_SEPARATOR + "nimbus"; try { FileUtils.forceMkdir(new File(ret)); } catch (IOException e) { LOG.error("Failed to create dir " + ret, e); throw e; } return ret; }

Target:
Catching an exception to log it an rethrow it is not typically good practice. Could we remove the catch/rethrow? I also am confused why we do a mkdir here, but that is what the original code did so it is a good translation. Could we file a JIRA to clean this up later? Creating directories does not feel like something ConfigUtils should be doing.
Source:
public static String supervisorIsupervisorDir(Map conf) throws IOException { return ((supervisorLocalDir(conf) + FILE_SEPARATOR + "isupervisor")); }

Target:
Double parens?
Source:
public String getId() { return this.getNodeId() + ":" + this.getPort(); }

Target:
minor: Do not need `this.` when calling methods.
Source:
public double getMemoryUsedByWorker(WorkerSlot ws) { TopologyDetails topo = findTopologyUsingWorker(ws); if (topo == null) { return 0.0; } Collection<ExecutorDetails> execs = getExecutors(ws, _cluster); LOG.info("getMemoryUsedByWorker executors: {}", execs); double totalMemoryUsed = 0.0; for (ExecutorDetails exec : execs) { totalMemoryUsed += topo.getTotalMemReqTask(exec); } return totalMemoryUsed; }

Target:
Is it useful for this to be INFO level? This could be a lot of text to log.
Source:
public void initState(KeyValueState<String, Long> state) { this.state = state; sum = state.get("sum", 0L); System.out.println("initState with state [" + state + "] current sum [" + sum + "]"); }

Target:
Could we use slf4j here instead of `System.out`?
Source:
private void setupCommitElapseTimer() { if(commitFrequencySec<=0) return; TimerTask timerTask = new TimerTask() { @Override public void run() { commitTimeElapsed.set(false); } }; commitTimer.schedule(timerTask, commitFrequencySec * 1000); }

Target:
Should not commitTimeElapsed be set to true?
Source:
public String toString() { String ret = "Topologies:\n"; for (TopologyDetails td : this.getTopologies()) { ret += td.toString() + "\n"; } return ret; }

Target:
Can we use a StringBuilder here instead? ``` StringBuilder ret = new StringBuilder(); ret.append("Topologies:\n"); for (TopologyDetails td : this.getTopologies()) { ret.append(td).append('\n'); } return ret.toString(); ``` (Also minor)
Source:
public String toString() { String ret = ""; if(this.isSuccess()) { ret += "Status: " + this.getStatus() + " message: " + this.getMessage() + " scheduling: " + this.getSchedulingResultMap().toString(); } else { ret += "Status: " + this.getStatus() + " error message: " + this.getErrorMessage(); } return ret; }

Target:
Don't need the .toString here at the end.
Source:
public void setAssignments(Map<String, SchedulerAssignment> newAssignments) { this.assignments = new HashMap<String, SchedulerAssignmentImpl>(); for (Map.Entry<String, SchedulerAssignment> entry : newAssignments.entrySet()) { this.assignments.put(entry.getKey(), new SchedulerAssignmentImpl(entry.getValue().getTopologyId(), entry.getValue().getExecutorToSlot())); } }

Target:
Looking at this snippet of code, it is not clear what the entry's key contains. We just learn that it is a String, and is put in the assignments map as a key again. This is why I like the other style of looping: for (String representativeNameOfTheKeyString: newAssignments.keySet()) { String representativeNameOfTheValueString: newAssignments.get(representativeNameOfTheKeyString); //do something with key and value
Source:
public void setStatusMap(Map<String, String> statusMap) { this.status.putAll(statusMap); }

Target:
This is named like a setter method, but it does not set the status map to what is in `statusMap`, it overrides any entries present in both. Suggest we rename it or change it to replace the current map.
Source:
public Double getTotalCPU() { Double totalCPU = getTotalResource(Config.SUPERVISOR_CPU_CAPACITY); if (totalCPU == null) { throw new IllegalStateException("default value for supervisor.cpu.capacity is not set!"); } return totalCPU; }

Target:
Do we want to throw exceptions here? It is unclear to me that this means the default was not set. If we need a default value, then we should add `@NotNull` to the validators for these configs. Then we will see the error earlier.
Source:
public TopologyDetails(String topologyId, Map topologyConf, StormTopology topology, int numWorkers, Map<ExecutorDetails, String> executorToComponents) { this(topologyId, topologyConf, topology, numWorkers); this.executorToComponent = new HashMap<>(0); if (executorToComponents != null) { this.executorToComponent.putAll(executorToComponents); } this.initResourceList(); this.initConfigs(); }

Target:
Revert?
Source:
public Map<WorkerSlot, Collection<ExecutorDetails>> getSchedulingResultMap() { return schedulingResultMap; }

Target:
`return this.schedulingResultMap` just for consistency
Source:
public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { this.windowedOutputCollector = new WindowedOutputCollector(collector); bolt.prepare(stormConf, context, windowedOutputCollector); this.listener = newWindowLifecycleListener(); this.windowManager = initWindowManager(listener, stormConf); LOG.info("Initialized window manager ", this.windowManager); }

Target:
This looks more like a debug statement to me.
Source:
private Set<String> constructUserFromPrincipals(Subject who) { Set<String> user = new HashSet<String>(); if (who == null) { LOG.debug("in validate acl who is null"); } else { LOG.debug("in validate acl: " + who); } if (who != null) { for (Principal p : who.getPrincipals()) { user.add(_ptol.toLocal(p)); } } return user; }

Target:
We could just have an `else` where we `LOG.debug("in validate acl: {}", who);` The current code will run even when we aren't logging at DEBUG level.
Source:
public static final void validateKey(String key) throws AuthorizationException { if (key == null || key.isEmpty() || "..".equals(key) || ".".equals(key) || !KEY_PATTERN.matcher(key).matches()) { LOG.error("'{}' does not appear to be valid {}", key, KEY_PATTERN); throw new AuthorizationException(key+" does not appear to be a valid blob key"); } }

Target:
Should this be `IllegalArgumentException`?
Source:
private void incrementMaxSequenceNumber(CuratorFramework zkClient, int count) throws Exception { zkClient.setData().forPath(BLOBSTORE_MAX_KEY_SEQUENCE_SUBTREE + "/" + key, ByteBuffer.allocate(INT_CAPACITY).putInt(count++).array()); }

Target:
`count++` this is a post-increment operator. This will write `count`'s value that was given by the caller, then increment the value, then throw it away. It looks like we want `count+1` here instead.
Source:
public static final void validateKey(String key) { if (key == null || key.isEmpty() || "..".equals(key) || ".".equals(key) || !KEY_PATTERN.matcher(key).matches()) { LOG.error("'{}' does not appear to be valid {}", key, KEY_PATTERN); throw new IllegalArgumentException(key+" does not appear to be a valid blob key"); } }

Target:
use StringUtils.isEmpty from apache-commons-lang?
Source:
private static String accessToString(int access) { StringBuffer ret = new StringBuffer(); ret.append(((access & READ) > 0) ? "r" : "-"); ret.append(((access & WRITE) > 0) ? "w" : "-"); ret.append(((access & ADMIN) > 0) ? "a" : "-"); return ret.toString(); }

Target:
use StringBuilder since it's only a local param.
Source:
public boolean checkForValidUsers(Subject who, int mask) { if (isNimbus(who) || isAdmin(who) || isSupervisor(who,mask)) { return true; } return false; }

Target:
return isNimbus(who) || isAdmin(who) || isSupervisor(who,mask);
Source:
private String namedPerms(int mask) { StringBuffer b = new StringBuffer(); b.append("["); if ((mask & READ) > 0) { b.append("READ "); } if ((mask & WRITE) > 0) { b.append("WRITE "); } if ((mask & ADMIN) > 0) { b.append("ADMIN "); } b.append("]"); return b.toString(); }

Target:
use StringBuilder, same for all below if any.
Source:
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { if(server != null) server.closeChannel(e.getChannel()); }

Target:
minor: braces on `if`
Source:
public ChannelBuffer buffer() throws IOException { ChannelBufferOutputStream bout = new ChannelBufferOutputStream( ChannelBuffers.directBuffer(encodeLength())); int payload_len = 0; if (token != null) payload_len = token.length; bout.writeShort(IDENTIFIER); bout.writeInt((int) payload_len); if (payload_len > 0) { bout.write(token); } bout.close(); return bout.buffer(); }

Target:
`(int)` cast not needed.
Source:
public void add(HashMap<Integer, ArrayList<TaskMessage>> taskTupleSetMap) { for (Map.Entry<Integer, ArrayList<TaskMessage>> entry : taskTupleSetMap.entrySet()) { Integer task = entry.getKey(); addListRefToMap(this.bundles, task, entry.getValue()); } }

Target:
Unless the variable is created to make the code easier to read, this could be simplified to addListRefToMap(this.bundles, entry.getKey(), entry.getValue());
Source:
private void markBatchGroups(String component, Map<String, String> batchGroups) { for(Map.Entry<String, String> entry: batchGroups.entrySet()) { String stream = entry.getKey(); _batchIds.put(new GlobalStreamId(component, stream), entry.getValue()); } }

Target:
Unless the variable is created to make the code easier to read, this could be simplified to _batchIds.put(new GlobalStreamId(component, entry.getKey()), entry.getValue());
Source:
public void validateField(String name, boolean includeZero, Object o) { if (o == null) { return; } if (o instanceof Number) { if(includeZero == true) { if (((Number) o).doubleValue() >= 0.0) { return; } } else { if (((Number) o).doubleValue() > 0.0) { return; } } } throw new IllegalArgumentException("Field " + name + " must be a Positive Number"); }

Target:
Don't need `== true` here
Source:
public void validateField(String name, Object o) { if (o == null) { return; } if (o instanceof String) { return; } //check if iterable try { SimpleTypeValidator.validateField(name, Iterable.class, o); } catch (Exception ex) { } this.fv.validateField(name, o); }

Target:
Why are we ignoring the exception?
Source:
private static void validateConfs(Map stormConf, StormTopology topology) throws IllegalArgumentException { LOG.info("Validating storm Confs..."); double largestMemReq = getMaxExecutorMemoryUsageForTopo(topology, stormConf); Double topologyWorkerMaxHeapSize = Utils.getDouble(stormConf.get(Config.TOPOLOGY_WORKER_MAX_HEAP_SIZE_MB)); if(topologyWorkerMaxHeapSize < largestMemReq) { throw new IllegalArgumentException("Topology will not be able to be successfully scheduled: Config TOPOLOGY_WORKER_MAX_HEAP_SIZE_MB=" +Utils.getDouble(stormConf.get(Config.TOPOLOGY_WORKER_MAX_HEAP_SIZE_MB)) + " < " + largestMemReq + " (Largest memory requirement of a component in the topology). Perhaps set TOPOLOGY_WORKER_MAX_HEAP_SIZE_MB to a larger amount"); } }

Target:
I don't think we need this log message.
Source:
public Double getTotalMemReqTask(ExecutorDetails exec) { if (hasExecInTopo(exec)) { return getOffHeapMemoryRequirement(exec) + getOnHeapMemoryRequirement(exec); } LOG.info("cannot find {}", exec); return null; }

Target:
Why does this need a log message? Does not seem to add much.
Source:
public GraphGrouper(DirectedGraph<Node, IndexedEdge> graph, Collection<Group> initialGroups) { this.graph = graph; this.currGroups = new LinkedHashSet(initialGroups); reindex(); }

Target:
Could you put the `<>` characters back at the end of the LinkedHashSet?
Source:
private void ack(Tuple tuple) throws SolrServerException, IOException { if (commitStgy == null) { collector.ack(tuple); } else { synchronized(ackFailLock) { toCommitTuples.add(tuple); commitStgy.update(); } if (commitStgy.commit()) { solrClient.commit(solrMapper.getCollection()); ackCommittedTuples(); } } }

Target:
don't think we need a synchronized block for this. Since there won't be any other threads trying modify toCommitTupes
Source:
private static Config getConfig(String brokerConnectionString) { Config conf = new Config(); Map config = new HashMap(); Properties props = new Properties(); props.put("metadata.broker.list", brokerConnectionString); props.put("request.required.acks", "1"); props.put("serializer.class", "kafka.serializer.StringEncoder"); conf.put(TridentKafkaState.KAFKA_BROKER_PROPERTIES, props); conf.put(TridentKafkaState.TOPIC, "test"); return conf; }

Target:
is this really required? we are using a topic selector in the state factory. (as far as i can see we don't even need the constant in TridentKafkaState anymore)
Source:
void closeOutputFile() throws IOException { this.writer.hsync(); this.writer.close(); }

Target:
I'm not sure this is needed. Close is supposed to block until the data is in HDFS, not necessarily on disk.
Source:
public long nextPoll() { long now = System.currentTimeMillis(); long cycle = (now - startTime) / pollMs; long wakeupTime = startTime + (pollMs * (cycle + 1)); long sleepTime = wakeupTime - now; if (sleepTime > 0) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } } now = System.currentTimeMillis(); return now; }

Target:
Probably want better logging here.
Source:
public CommandResult execute(CommandInvocation commandInvocation) throws IOException { if (help) { commandInvocation.getShell().out().print(commandInvocation.getHelpInfo("pwd")); } commandInvocation.getShell().out().print(commandInvocation.getAeshContext().getCurrentWorkingDirectory()); return CommandResult.SUCCESS; }

Target:
i think we should have a else here so we dont print the cwd if the user has enabled the help option.
Source:
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { MigrationResponse response = _imageStoreService.migrateData(this); response.setObjectName("imagestore"); this.setResponseObject(response); }

Target:
Why throw so many different exceptions? we can catch most of them and give nice consise error messages in a ServerApiException, right? Most of these are Runtime exception. Mentioning them here is also redundant as they are declared in BaseCmd as well.
Source:
protected void createFolder(String path) { try { Files.createDirectories(Paths.get(path)); } catch (IOException e) { s_logger.error(String.format("Unable to create directory %s for template %s: %s%n", path, getTemplate().getUrl(), e.toString())); throw new CloudRuntimeException(e); } }

Target:
please reconsider this log message `s_logger.error(String.format("Unable to create directory %s for template %s: %s%n", path, getTemplate().getUrl(), e.toString()))` especially the %s%n part of it, logging an exception as string with newline semms not what we want. I would like a stack trace or a message, or both.
Source:
private void umount(String localRootPath) { if (!mountExists(localRootPath)) { return; } Script command = new Script(true, "umount", timeout, s_logger); command.add(localRootPath); String result = command.execute(); if (result != null) { // Fedora Core 12 errors out with any -o option executed from java String errMsg = "Unable to umount " + localRootPath + " due to " + result; s_logger.error(errMsg); throw new CloudRuntimeException(errMsg); } deleteMountPath(localRootPath); s_logger.debug("Successfully umounted " + localRootPath); }

Target:
should be info, not debug
Source:
public HttpDirectDownloadCommand(String url, Long templateId, PrimaryDataStoreTO destPool, String checksum, Map<String, String> headers, int connectTimeout, int soTimeout) { super(url, templateId, destPool, checksum, headers); setConnectTimeout(connectTimeout); setSoTimeout(soTimeout); }

Target:
Can these be set on the DrectDownloadCommand constructor?
Source:
public boolean removeVMFromBackupOffering(VirtualMachine vm) { s_logger.debug("Removing VM ID " + vm.getUuid() + " from backup offering by the Dummy Backup Provider"); final List<Backup> backups = backupDao.listByVmId(null, vm.getId()); for (final Backup backup : backups) { backupDao.remove(backup.getId()); } return true; }

Target:
If assignVMToBackupOffering does nothing then why we try to remove the VM here? Can we just return true as well?
Source:
public List<VlanVO> listVlansForPod(long podId) { //FIXME: use a join statement to improve the performance (should be minor since we expect only one or two List<PodVlanMapVO> vlanMaps = _podVlanMapDao.listPodVlanMapsByPod(podId); List<VlanVO> result = new ArrayList<VlanVO>(); for (PodVlanMapVO pvmvo : vlanMaps) { VlanVO vlanByPodId = findById(pvmvo.getVlanDbId()); if (vlanByPodId != null && vlanByPodId.getRemoved() == null) { result.add(vlanByPodId); } } return result; }

Target:
a null check is enough, removed items are not returned by `GenericDaoBase::findById()`
Source:
private long executeSqlCountComputingResourcesForAccount(long accountId, String sqlCountComputingResourcesAllocatedToAccount) { TransactionLegacy tx = TransactionLegacy.currentTxn() try { PreparedStatement pstmt = tx.prepareAutoCloseStatement(sqlCountComputingResourcesAllocatedToAccount); pstmt.setLong(1, accountId); ResultSet rs = pstmt.executeQuery(); if (!rs.next()) { return 0L; } return rs.getLong("total"); } catch (SQLException e) { throw new CloudRuntimeException(e); } }

Target:
@DaanHoogland you missed ";" at the end of line 269.
Source:
public String getSyncObjType() { if (getSyncObjId() != null) { return BaseAsyncCmd.migrationSyncObject; } return null; }

Target:
Why did you need to implemente these `getSyncObjType` and `getSyncObjId`? Could you explain this a little bit further?
Source:
public void processHostVmStateReport(long hostId, Map<String, HostVmStateReportEntry> report) { if (s_logger.isDebugEnabled()) s_logger.debug("Process host VM state report. host: " + hostId); Map<Long, VirtualMachine.PowerState> translatedInfo = convertVmStateReport(report); processReport(hostId, translatedInfo); }

Target:
Can you remove this IF condition as well?
Source:
public Volume detachVolumeViaDestroyVM(long vmId, long volumeId) { Volume result = orchestrateDetachVolumeFromVM(vmId, volumeId); return result; }

Target:
Extra new line can be removed here and other places.
Source:
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { try { vlanMgr.deleteRct(this); SuccessResponse response = new SuccessResponse(getCommandName()); setResponseObject(response); } catch (Exception e) { s_logger.warn(String.format("unable to delete baremetal RCT[%s]", getId()), e); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } }

Target:
The same thing here regarding the passing of exception to the new one that is thrown.
Source:
public Boolean getMakeRedundant() { if (makeRedundant != null) { return makeRedundant; } return true; }

Target:
If we don't pass anything, I think it should be false, it would continue with normal restart instead of this blue-green deployment.
Source:
public Boolean getMakeredundant() { if (makeredundant != null) { return makeredundant; } return false; }

Target:
Is there is a default value, why not use a primitive value with a default of `false`? Then, you do not need these logics in a POJO get method.
Source:
public void zonedTimeFormatLegacy() throws ParseException { Date time = new Date(); DateFormat dfDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'Z"); String str = dfDate.format(time); Date dtParsed = DateUtil.parseTZDateString(str); assertEquals(time, dtParsed); }

Target:
I don't think these will be the same objects only representing the same date but as one is created from a string it would not include microseconds. This is why i compared the string representations.
Source:
public String getHost() { String[] hosts = _host.split(","); if (_hostCounter >= hosts.length) { _hostCounter = 0; } s_logger.info("Connecting to host: " + hosts[_hostCounter % hosts.length]); return hosts[_hostCounter++ % hosts.length]; }

Target:
this log message might be a bit deceiving. I think the ++ from the return statement should be moved here or just above. Also the text is deceiving; the connection is not actually made in this method. On the other hand the method name might have to change to getNextHost()...
Source:
public static String[] getRecommendedProtocols() { String[] supportedProtocols = { "TLSv1", "TLSv1.1", "TLSv1.2" }; return supportedProtocols; }

Target:
This is a little cosmetic, but, how about returning directly the array? Instead of assigning it to a variable first? Also, what about test cases? I mean, if someone starts using this method because it expected the behavior of returning { "TLSv1", "TLSv1.1", "TLSv1.2" }, but later some other person changes it to return only { "TLSv1.1", "TLSv1.2" }, this might affect people using this method
Source:
public void setCpuMaxDeviation(final Double maxCpuUsagePercentage, final Double totalCpuUsedPercentage, final Long totalHosts) { if (maxCpuUsagePercentage != null && totalCpuUsedPercentage != null && totalHosts != null && totalHosts != 0) { final Double averageCpuUsagePercentage = totalCpuUsedPercentage / totalHosts; this.cpuMaxDeviation = String.format("%.2f%%", (maxCpuUsagePercentage - averageCpuUsagePercentage) * 1.0 / averageCpuUsagePercentage); } }

Target:
is the '* 1.0' needed when it is devided next? I would rather see a cast if it is, in this case
Source:
public void testFailRemoveOperation() { try { domainManager.failRemoveOperation(domain, domainAccountsForCleanup, domainNetworkIds, true); } catch (Exception e) { Assert.assertEquals(CloudRuntimeException.class, e.getClass()); } }

Target:
Now that you removed the use of `rollBackState`, made the method last problematic to test. Therefore, you can use the `@Test(expected=...)`, instead of this very unusual construction here.
Source:
public void testReplaceNicsMacSequenceInBootArgs() throws Exception { String bootArgs = "nic_macs=02:00:65:b5:00:03|7C02:00:4f:1b:00:15|7C1e:00:54:00:00:0f|7C02:00:35:fa:00:11|7C02:00:47:40:00:12"; doReturn(bootArgs).when(vmSpec).getBootArgs(); String oldMacSequence = "7C02:00:35:fa:00:11|7C02:00:47:40:00:12"; String newMacSequence = "7C02:00:0c:1d:00:1d|7C02:00:68:0f:00:1e"; String updatedBootArgs = _resource.replaceNicsMacSequenceInBootArgs(oldMacSequence, newMacSequence, vmSpec); String newBootArgs = "nic_macs=02:00:65:b5:00:03|7C02:00:4f:1b:00:15|7C1e:00:54:00:00:0f|7C02:00:0c:1d:00:1d|7C02:00:68:0f:00:1e"; assertEquals(newBootArgs, updatedBootArgs); }

Target:
Do you need this `throws Exception` here? It does not seem o be required by any of the method calls you have here.
Source:
private boolean checkOvsNetwork(final String networkName) { s_logger.debug("Checking if network " + networkName + " exists as openvswitch bridge"); if (networkName == null) { return true; } final Script command = new Script("/bin/sh", _timeout.getMillis()); command.add("-c"); command.add("ovs-vsctl br-exists " + networkName); return "0".equals(command.execute(null)); }

Target:
Please consider adding an overridden version of the `Script(String, int)` constructor that accepts `Duration` to encapsulate this type conversion.
Source:
public synchronized boolean destroyTunnelNetwork(final String bridge) { findOrCreateTunnelNetwork(bridge); final Script cmd = new Script(_ovsTunnelPath, _timeout.getMillis(), s_logger); cmd.add("destroy_ovs_bridge"); cmd.add("--bridge", bridge); final String result = cmd.execute(); if (result != null) { s_logger.debug("OVS Bridge could not be destroyed due to error ==> " + result); return false; } return true; }

Target:
Please consider adding an overridden version of the `Script(String, int, Logger)` constructor that accepts `Duration` to encapsulate this type conversion.
Source:
private Map<String, String> getVersionStrings() { final Script command = new Script(_versionstringpath, _timeout.getMillis(), s_logger); final KeyValueInterpreter kvi = new KeyValueInterpreter(); final String result = command.execute(kvi); if (result == null) { return kvi.getKeyValues(); } else { return new HashMap<String, String>(1); } }

Target:
Please consider adding an overridden version of the `Script(String, int, Logger)` constructor that accepts `Duration` to encapsulate this type conversion.
Source:
private String executeBashScript(final String script) { final Script command = new Script("/bin/bash", _timeout.getMillis(), s_logger); command.add("-c"); command.add(script); return command.execute(); }

Target:
Please consider adding an overridden version of the `Script(String, int, Logger)` constructor that accepts `Duration` to encapsulate this type conversion.
Source:
private boolean canBridgeFirewall(final String prvNic) { final Script cmd = new Script(_securityGroupPath, _timeout.getMillis(), s_logger); cmd.add("can_bridge_firewall"); cmd.add(prvNic); final String result = cmd.execute(); if (result != null) { return false; } return true; }

Target:
Please consider adding an overridden version of the `Script(String, int, Logger)` constructor that accepts `Duration` to encapsulate this type conversion.
Source:
public boolean cleanupRules() { if (!_canBridgeFirewall) { return false; } final Script cmd = new Script(_securityGroupPath, _timeout.getMillis(), s_logger); cmd.add("cleanup_rules"); final String result = cmd.execute(); if (result != null) { return false; } return true; }

Target:
Please consider adding an overridden version of the `Script(String, int, Logger)` constructor that accepts `Duration` to encapsulate this type conversion.
Source:
private void verifyNotEmpty(String name, String value) throws ConfigurationException { if (org.apache.commons.lang.StringUtils.isEmpty(value)) { throw new ConfigurationException("Unable to find " + name); } }

Target:
Why not import the `org.apache.commons.lang` package and avoid some clutter?
Source:
private NetworkVO getDefaultNetwork (long vmId) { NicVO defaultNic = _nicDao.findDefaultNicForVM(vmId); if (defaultNic != null ) return _networkDao.findById(_nicDao.findById(defaultNic.getId()).getNetworkId()); return null; }

Target:
Not necessary to fetch the nic from DB twice.
Source:
private Long getDefaultNetwork(long vmId) { NicVO defaultNic = _nicDao.findDefaultNicForVM(vmId); if (defaultNic != null) return defaultNic.getNetworkId(); return null; }

Target:
Per our coding standards, please wrap all `if` blocks in curly braces.
Source:
public boolean configDnsSupportForSubnet(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { // Ignore if virtual router is already dhcp provider if (_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Dhcp, getProvider())) { return true; } else { return configureDhcpSupport(network, nic, vm, dest, Service.Dns); } }

Target:
This `else` block is unnecessary since the `if` block returns. Please remove it.
Source:
protected VirtualMachineMO findVmOnDatacenter(VmwareContext context, VmwareHypervisorHost hyperHost, VolumeTO vol) throws Exception { DatacenterMO dcMo = new DatacenterMO(context, hyperHost.getHyperHostDatacenter()); if (dcMo.getMor() == null) { String msg = "Unable to find VMware DC"; s_logger.error(msg); throw new CloudRuntimeException(msg); } VirtualMachineMO vmMo = dcMo.findVm(vol.getPath()); return vmMo; }

Target:
What about using here: `return dcMo.findVm(vol.getPath());` then, we could save 1 line of code ;)
Source:
public T findById(final ID id) { T result = null; if (_cache != null) { final Element element = _cache.get(id); if (element == null) { result = lockRow(id, null); } else { result = (T)element.getObjectValue(); } } else { result = lockRow(id, null); } return result }

Target:
a ';' missing :(
Source:
public void testGetOutOfBandManagementOptionsInvalid() { try { oobmService.getOptions(null); Assert.fail("CloudRuntimeException was expected for finding options of host with out-of-band management configuration"); } catch (CloudRuntimeException e) { } }

Target:
This `try` block and `fail` construct is unnecessary. Changing `@Test` to `@Test(expected = CloudRuntimeException.class)` accomplishes the same thing.
Source:
public void testSetIdsListToSearchCriteria(){ mgr.setIdsListToSearchCriteria(sc, idsList); Mockito.verify(sc, times(1)).setParameters(Mockito.same("idIN"), Mockito.same(id1), Mockito.same(id2)); }

Target:
the default of Mockito.verify already uses "times(1)"; so, there is no need to inform it.
Source:
public void testGetIdsListId(){ List<Long> result = mgr.getIdsListFromCmd(id1, idsEmptyList); assertEquals(result, expectedListId); }

Target:
This is more a question of philosophy, but the assertEquals should be: assertEquals(expected, actual). You are doing the opposite. It does not mean that the way it is coded now is wrong, it is just not the normal way (at least that I am used).
Source:
public static ByteBuffer enlargeBuffer(ByteBuffer buffer, final int sessionProposedCapacity) { if (sessionProposedCapacity > buffer.capacity()) { buffer = ByteBuffer.allocate(sessionProposedCapacity); } else { buffer = ByteBuffer.allocate(buffer.capacity() * 2); } return buffer; }

Target:
Add `Preconditions.checkArgument` checks to verify that the passed `buffer` is not `null` and that `sessionProposedCapacity` is greater than zero.
Source:
private boolean canCloneVolume() { return new Boolean(getDriver().getCapabilities().get(DataStoreCapabilities.CAN_CREATE_VOLUME_FROM_VOLUME.toString())); }

Target:
`new Boolean` skips the constant pool -- placing unnecessary pressure on the garbage collector. Please use `Boolean.valueOf` instead.
Source:
public boolean isDisplay() { if (displayNetwork == null) return true; else return displayNetwork; }

Target:
Either add the curly braces per coding conventions or reduce a ternary.
Source:
public void testProjectLockableAccount() { AccountVO accountVO = new AccountVO(); accountVO.setId(7L); accountVO.setDomainId(1L); accountVO.setType(Account.ACCOUNT_TYPE_PROJECT); assertFalse(quotaManager.isLockable(accountVO)); }

Target:
@abhinandanprateek We can actually remove the setId and setDomainId in all the testxxxLockableAccounts; create like a single class leve AccountVO and then in each of the testxxxLockableAccounts methods simply call the setType method and then call assert on them.
Source:
public String getDetail(String name) { assert (details != null) : "Did you forget to load the details?"; return details.get(name); }

Target:
I would have solved this one by removing the assert. Do we even run any tests with asserts enabled? (no :-1: intended!)
Source:
private void setEncodeApiResponse(final boolean encodeApiResponse) { ApiServer.encodeApiResponse = encodeApiResponse; }

Target:
What is this for? It seems like a strange thing to do
Source:
public String toString() { StringBuilder fsBuilder = new StringBuilder(); for (Map.Entry<String, String> address : addresses.entrySet()) { fsBuilder.append("<nuage-extension>\n"); fsBuilder.append(" <interface mac='" + address.getKey() + "' vsp-vr-ip='" + address.getValue() + "'></interface>\n"); fsBuilder.append("</nuage-extension>\n"); } return fsBuilder.toString(); }

Target:
Performing string append operations when using a `StringBuilder` defeats purpose of the class. Please change to the following to avoid unnecessary string re-allocation: ``` fsBuilder.append(" <interface mac='") .append(address.getKey() ) .append("' vsp-vr-ip='") .append(address.getValue()) .append("'></interface>\n"); ```
Source:
public boolean updateVolumeId(long srcVolId, long destVolId) { TransactionLegacy txn = TransactionLegacy.currentTxn(); try { VolumeDataStoreVO volumeDataStoreVO = findByVolume(srcVolId); if(volumeDataStoreVO != null) { txn.start(); volumeDataStoreVO.setVolumeId(destVolId); update(volumeDataStoreVO.getId(), volumeDataStoreVO); txn.commit(); } } catch (Exception e) { throw new CloudRuntimeException("Unable to update the volume id for volume store ref"); } return true; }

Target:
please catch more specific/explicit exceptions. In this case the original exception is not passed through or embedded so it is totally lost.
Source:
private NuageVspPluginClientLoader(String nuagePluginClientJarLocation) { try { _loader = URLClassLoader.newInstance(new URL[] {new URL("jar:file:" + nuagePluginClientJarLocation + "!/")}, getClass().getClassLoader()); } catch (MalformedURLException e) { e.printStackTrace(); } }

Target:
`printStackTrace()` emits to stdout which will result in this stack trace being lost due to redirection. Log the exception instead with a message explaining what operation was being performed. Also, should the exception be swallowed or should an `IllegalStateException` be thrown?
Source:
public int hashCode() { int result = _currentApiVersion != null ? _currentApiVersion.hashCode() : 0; result = 31 * result + (_apiRetryCount != null ? _apiRetryCount.hashCode() : 0); result = 31 * result + (_apiRetryInterval != null ? _apiRetryInterval.hashCode() : 0); return result; }

Target:
I think we can un-final it
Source:
public int hashCode() { int result = _syncType != null ? _syncType.hashCode() : 0; result = 31 * result + (_nuageVspCmsId != null ? _nuageVspCmsId.hashCode() : 0); return result; }

Target:
@nlivens Looking at the `Command.toString()` implementation, I see no reason for it to be `final`. I will open a thread on dev@ to determine if there is a good reason for it. If not, I think we should change it, and update these command classes to more detailed information about their state.
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PingNuageVspCommand that = (PingNuageVspCommand) o; if (shouldAudit != that.shouldAudit) return false; return true; }

Target:
This `equals` implementation should include attributes from the `PingCommand` super class.
Source:
public QuotaTypes(Integer quotaType, String name, String unit, String description) { this.quotaType = quotaType; this.description = description; this.quotaName = name; this.quotaUnit = unit; this.discriminator = "None"; }

Target:
Should any user of this class be able to instantiate it? It seems like this constructor should be `private`.
Source:
public long getEntityOwnerId() { Long accountId = _accountService.getActiveAccountByName(accountName, domainId).getAccountId(); if (accountId == null) { return CallContext.current().getCallingAccount().getId(); } return Account.ACCOUNT_ID_SYSTEM; }

Target:
This doesn't seem right. What are you trying to do here?
Source:
public ServiceOfferingVO findById(Long vmId, long serviceOfferingId) { ServiceOfferingVO offering = super.findById(serviceOfferingId); if (offering.isDynamic()) { offering.setDynamicFlag(true); if (vmId == null) { throw new CloudRuntimeException("missing argument vmId"); } Map<String, String> dynamicOffering = userVmDetailsDao.listDetailsKeyPairs(vmId); return getcomputeOffering(offering, dynamicOffering); } return offering; }

Target:
Move to the top of the method and consider using `com.google.common.base.Preconditions#checkArgument` to check the argument.
Source:
public UsageReporter() { s_instance = this; }

Target:
A public (instance) constructor writes to a static variable. I think you can make the constructor private and assign the static from getInstance(). First check for null and then assign if needed or return the existing object. public static UsageReporter getInstance(Map<String, String> configs) { if (s_instance == null) { s_instance = new UsageReporter(); //make sure it is private so it can only be called from here s_instance.init(configs); } return s_instance; }
Source:
protected void setSchema(final String schema) throws DatabaseEngineException { try { this.conn.setSchema(schema); } catch (Exception e) { throw new DatabaseEngineException(String.format("Could not set current schema to '%s'", schema), e); } }

Target:
final missing. Same for the other ones.
Source:
private Object ensureNoUnderflow(Object val) { if (val instanceof Double) { if (Math.abs((Double) val) <= 1.0e-131) { return ZERO; } } return val; }

Target:
Why not: ```java if (val instanceof Double && Math.abs((Double) val) <= 1.0e-131) { return ZERO; } return val; ```
Source:
public void connect() throws Exception { super.connect(); if (properties.getSchema() != null && properties.getSchema().length() > 0 && !properties.getUsername().equals(properties.getSchema())) { // Set connection schema if one is defined and not the same as the user name final Statement stmt = conn.createStatement(); stmt.execute("ALTER SESSION SET CURRENT_SCHEMA=" + properties.getSchema()); stmt.close(); } }

Target:
how about a try-with-resources, and drop the _stmt.close();_ below?
Source:
private void dropAllEntities() { for (MappedEntity mappedEntity : ImmutableList.copyOf(entities.values())) { try { dropEntity(mappedEntity.getEntity()); } catch (final DatabaseEngineException ex) { logger.debug(String.format("Failed to drop entity '%s'", mappedEntity.getEntity().getName()), ex); } } }

Target:
`mappedEntity` can be final, and you have a few blank lines in this method that don't really improve legibility.
Source:
protected Object processObject(Object o) { if (o != null && o instanceof PGobject && ((PGobject)o).getType().equals("jsonb")) { return ((PGobject) o).getValue(); } return super.processObject(o); }

Target:
null check is not needed, instanceof will return false if the left operand is null.
Source:
private void updateThreadParent() throws NodeStoreException { if (null == inReplyTo) return; channelManager.updateThreadParent(node, inReplyTo); }

Target:
Should we avoid blocks with no braces?
Source:
public AccurevSCM(String serverName, String depot, String stream) { this.depot = depot; this.stream = stream; AccurevServer server = getDescriptor().getServer(serverName); if (server != null) { setServerName(server.getName()); setServerUUID(server.getUuid()); } updateMode(); }

Target:
Why is this change needed? if so should the deprecated method not call this one.
Source:
private static void handleConsoleMessage(TaskListener listener, boolean isValidCommand, String path) { boolean isValidPath = false; isValidPath = path!=null && (path.isEmpty() || path.equals("accurev")); if(isValidCommand && isValidPath) { listener.getLogger().println( String.format( "No AccuRev tool configured, using default" ) ); } }

Target:
This has several formatting issues
Source:
private static void handleConsoleMessage(TaskListener listener, boolean isValidCommand, String path) { boolean isValidPath = false; isValidPath = (path != null && (path.isEmpty() || path.equals("accurev"))); if (isValidCommand && isValidPath) { listener.getLogger().println(String.format("No AccuRev tool configured, using default")); } }

Target:
Think we can skip the String.format here
Source:
public BundleGroupExtractor(Map<String, BundleInfo> bundles, String version) { this.bundles = bundles; this.version = version; for (BundleInfo bundle : bundles.values()) { registerBundle(bundle); } generateGroups(version); }

Target:
Could be `bundles.values().forEach(this::registerBundle)`
Source:
public void checkHeader(String distribId) { if (distribId != null) { assertEquals(String.format("Browsing Distribution '%s'", distribId), header.getText()); } else { assertTrue(header.getText(), header.getText().startsWith("Browsing Distribution")); } }

Target:
Could put `header.getText()` (used 3 times) in a local variable
Source:
public void run(String step, MigrationContext migrationContext) { TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); state = "after"; }

Target:
Missing `@Override`.
Source:
public String toString() { return new ToStringBuilder(this).append("id", getId()) .append("author", getAuthor()) .append("text", getText()) .toString(); }

Target:
I am wondering if we should add the `author` and `text` to `toString` method in the case where we log a sensitive data I mean. what each person says :)
Source:
public void testFailingBulkAction() throws Exception { String result = async.newRequest(BulkRunAction.ID) // .set("action", AutomationBulkAction.ACTION_NAME) .set("query", "SELECT * FROM Folder") .set("bucketSize", "10") .set("batchSize", "5") .set("parameters", MAPPER.writeValueAsString("{}")) .executeReturningExceptionEntity(SC_INTERNAL_SERVER_ERROR); assertTrue( result.startsWith("Unknown operation id null in command: org.nuxeo.ecm.core.bulk.message.BulkCommand")); }

Target:
Can we just put `"{}"` without calling the MAPPER? `writeValueAsString` is used to serialize an object to JSON (or other), here you're giving to it a String. My first thought is: writing a string as string will return the input string. If it's not the case, having the final value in the test will help us to understand what makes it fail and what we want to control/catch.
Source:
public void setMaxWait(int num) { blockingTimeoutMillis = num; log.warn( "maxWait deprecated dbcp pool attribute usage, should use blockingTimeoutMillis geronimo pool attribute instead"); }

Target:
Wrong log message stating about geronimo which is removed in this PR.