auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public TopologyDetails(String topologyId, Map topologyConf, StormTopology topology, START int numWorkers, Map<ExecutorDetails, String> executorToComponents) { END this(topologyId, topologyConf, topology, numWorkers); this.executorToComponent = new HashMap<>(0); if (executorToComponents != null) { this.executorToComponent.putAll(executorToComponents); } this.initResourceList(); this.initConfigs(); } Revert?

Target:
public TopologyDetails(String topologyId, Map topologyConf, StormTopology topology, int numWorkers, Map<ExecutorDetails, String> executorToComponents) { this(topologyId, topologyConf, topology, numWorkers, executorToComponents, 0); }
Source:
public Map<WorkerSlot, Collection<ExecutorDetails>> getSchedulingResultMap() { START return schedulingResultMap; END } `return this.schedulingResultMap` just for consistency

Target:
public Map<WorkerSlot, Collection<ExecutorDetails>> getSchedulingResultMap() { return this.schedulingResultMap; }
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); START LOG.info("Initialized window manager ", this.windowManager); END } This looks more like a debug statement to me.

Target:
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.debug("Initialized window manager ", this.windowManager); }
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; START } END 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.

Target:
private Set<String> constructUserFromPrincipals(Subject who) { Set<String> user = new HashSet<String>(); if (who != null) { for (Principal p : who.getPrincipals()) { user.add(_ptol.toLocal(p)); } } return user; }
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); START throw new AuthorizationException(key+" does not appear to be a valid blob key"); END } } Should this be `IllegalArgumentException`?

Target:
public static final void validateKey(String key) { if (StringUtils.isEmpty(key) || "..".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"); } }
Source:
private void incrementMaxSequenceNumber(CuratorFramework zkClient, int count) throws Exception { zkClient.setData().forPath(BLOBSTORE_MAX_KEY_SEQUENCE_SUBTREE + "/" + key, START ByteBuffer.allocate(INT_CAPACITY).putInt(count++).array()); END } `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.

Target:
private void incrementMaxSequenceNumber(CuratorFramework zkClient, int count) throws Exception { zkClient.setData().forPath(BLOBSTORE_MAX_KEY_SEQUENCE_SUBTREE + "/" + key, ByteBuffer.allocate(INT_CAPACITY).putInt(count + 1).array()); }
Source:
public static final void validateKey(String key) { START if (key == null || key.isEmpty() || "..".equals(key) || ".".equals(key) || !KEY_PATTERN.matcher(key).matches()) { END LOG.error("'{}' does not appear to be valid {}", key, KEY_PATTERN); throw new IllegalArgumentException(key+" does not appear to be a valid blob key"); } } use StringUtils.isEmpty from apache-commons-lang?

Target:
public static final void validateKey(String key) { if (StringUtils.isEmpty(key) || "..".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"); } }
Source:
private static String accessToString(int access) { START StringBuffer ret = new StringBuffer(); END ret.append(((access & READ) > 0) ? "r" : "-"); ret.append(((access & WRITE) > 0) ? "w" : "-"); ret.append(((access & ADMIN) > 0) ? "a" : "-"); return ret.toString(); } use StringBuilder since it's only a local param.

Target:
private static String accessToString(int access) { StringBuilder ret = new StringBuilder(); ret.append(((access & READ) > 0) ? "r" : "-"); ret.append(((access & WRITE) > 0) ? "w" : "-"); ret.append(((access & ADMIN) > 0) ? "a" : "-"); return ret.toString(); }
Source:
public boolean checkForValidUsers(Subject who, int mask) { START if (isNimbus(who) || isAdmin(who) || isSupervisor(who,mask)) { END return true; } return false; } return isNimbus(who) || isAdmin(who) || isSupervisor(who,mask);

Target:
public boolean checkForValidUsers(Subject who, int mask) { return isNimbus(who) || isAdmin(who) || isSupervisor(who,mask); }
Source:
private String namedPerms(int mask) { START StringBuffer b = new StringBuffer(); END 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(); } use StringBuilder, same for all below if any.

Target:
private String namedPerms(int mask) { StringBuilder b = new StringBuilder(); 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(); }
Source:
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { START if(server != null) server.closeChannel(e.getChannel()); END } minor: braces on `if`

Target:
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { if(server != null) { server.closeChannel(e.getChannel()); } }
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); START bout.writeInt((int) payload_len); END if (payload_len > 0) { bout.write(token); } bout.close(); return bout.buffer(); } `(int)` cast not needed.

Target:
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(payload_len); if (payload_len > 0) { bout.write(token); } bout.close(); return bout.buffer(); }
Source:
public void add(HashMap<Integer, ArrayList<TaskMessage>> taskTupleSetMap) { for (Map.Entry<Integer, ArrayList<TaskMessage>> entry : taskTupleSetMap.entrySet()) { Integer task = entry.getKey(); START addListRefToMap(this.bundles, task, entry.getValue()); END } } Unless the variable is created to make the code easier to read, this could be simplified to addListRefToMap(this.bundles, entry.getKey(), entry.getValue());

Target:
public void add(HashMap<Integer, ArrayList<TaskMessage>> taskTupleSetMap) { for (Map.Entry<Integer, ArrayList<TaskMessage>> entry : taskTupleSetMap.entrySet()) { 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(); START _batchIds.put(new GlobalStreamId(component, stream), entry.getValue()); END } } 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());

Target:
private void markBatchGroups(String component, Map<String, String> batchGroups) { for(Map.Entry<String, String> entry: batchGroups.entrySet()) { _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) { START if(includeZero == true) { END 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"); } Don't need `== true` here

Target:
public static void validateField(String name, boolean includeZero, Object o) { if (o == null) { return; } if (o instanceof Number) { if(includeZero) { 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"); }
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); START } catch (Exception ex) { END } this.fv.validateField(name, o); } Why are we ignoring the exception?

Target:
public void validateField(String name, Object o) { if (o == null || o instanceof String) { // A null value or a String value is acceptable return; } this.fv.validateField(name, o); }
Source:
private static void validateConfs(Map stormConf, StormTopology topology) throws IllegalArgumentException { START LOG.info("Validating storm Confs..."); END 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"); } } I don't think we need this log message.

Target:
private static void validateConfs(Map stormConf, StormTopology topology) throws IllegalArgumentException { 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"); } }
Source:
public Double getTotalMemReqTask(ExecutorDetails exec) { if (hasExecInTopo(exec)) { return getOffHeapMemoryRequirement(exec) + getOnHeapMemoryRequirement(exec); } START LOG.info("cannot find {}", exec); END return null; } Why does this need a log message? Does not seem to add much.

Target:
public Double getTotalMemReqTask(ExecutorDetails exec) { if (hasExecInTopo(exec)) { return getOffHeapMemoryRequirement(exec) + getOnHeapMemoryRequirement(exec); } return null; }
Source:
public GraphGrouper(DirectedGraph<Node, IndexedEdge> graph, Collection<Group> initialGroups) { this.graph = graph; START this.currGroups = new LinkedHashSet(initialGroups); END reindex(); } Could you put the `<>` characters back at the end of the LinkedHashSet?

Target:
public GraphGrouper(DirectedGraph<Node, IndexedEdge> graph, Collection<Group> initialGroups) { this.graph = graph; this.currGroups = new LinkedHashSet<>(initialGroups); reindex(); }
Source:
private void ack(Tuple tuple) throws SolrServerException, IOException { if (commitStgy == null) { collector.ack(tuple); } else { START synchronized(ackFailLock) { END toCommitTuples.add(tuple); commitStgy.update(); } if (commitStgy.commit()) { solrClient.commit(solrMapper.getCollection()); ackCommittedTuples(); } } } don't think we need a synchronized block for this. Since there won't be any other threads trying modify toCommitTupes

Target:
private void ack(Tuple tuple) throws SolrServerException, IOException { if (commitStgy == null) { collector.ack(tuple); } else { toCommitTuples.add(tuple); commitStgy.update(); if (commitStgy.commit()) { solrClient.commit(solrMapper.getCollection()); ackCommittedTuples(); } } }
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); START conf.put(TridentKafkaState.TOPIC, "test"); END return conf; } 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)

Target:
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); return conf; }
Source:
void closeOutputFile() throws IOException { START this.writer.hsync(); END this.writer.close(); } I'm not sure this is needed. Close is supposed to block until the data is in HDFS, not necessarily on disk.

Target:
void closeOutputFile() throws IOException { this.writer.close(); }
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) { START e.printStackTrace(); END } } now = System.currentTimeMillis(); return now; } Probably want better logging here.

Target:
public long nextPoll() throws InterruptedException { long now = System.currentTimeMillis(); long cycle = (now - startTime) / pollMs; long wakeupTime = startTime + (pollMs * (cycle + 1)); long sleepTime = wakeupTime - now; if (sleepTime > 0) { Thread.sleep(sleepTime); } now = System.currentTimeMillis(); return now; }
Source:
public CommandResult execute(CommandInvocation commandInvocation) throws IOException { if (help) { commandInvocation.getShell().out().print(commandInvocation.getHelpInfo("pwd")); START } END commandInvocation.getShell().out().print(commandInvocation.getAeshContext().getCurrentWorkingDirectory()); return CommandResult.SUCCESS; } i think we should have a else here so we dont print the cwd if the user has enabled the help option.

Target:
public CommandResult execute(CommandInvocation commandInvocation) throws IOException { if (help) { commandInvocation.getShell().out().print(commandInvocation.getHelpInfo("pwd")); return CommandResult.SUCCESS; } commandInvocation.getShell().out().print(commandInvocation.getAeshContext().getCurrentWorkingDirectory()); return CommandResult.SUCCESS; }
Source:
START public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { END MigrationResponse response = _imageStoreService.migrateData(this); response.setObjectName("imagestore"); this.setResponseObject(response); } 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.

Target:
public void execute() { MigrationResponse response = _imageStoreService.migrateData(this); response.setObjectName("imagestore"); this.setResponseObject(response); }
Source:
protected void createFolder(String path) { try { Files.createDirectories(Paths.get(path)); } catch (IOException e) { START s_logger.error(String.format("Unable to create directory %s for template %s: %s%n", path, getTemplate().getUrl(), e.toString())); END throw new CloudRuntimeException(e); } } 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.

Target:
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()), e); throw new CloudRuntimeException(e); } }
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); START s_logger.debug("Successfully umounted " + localRootPath); END } should be info, not debug

Target:
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.info("Successfully umounted " + localRootPath); }
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); START setConnectTimeout(connectTimeout); END setSoTimeout(soTimeout); } Can these be set on the DrectDownloadCommand constructor?

Target:
public HttpDirectDownloadCommand(String url, Long templateId, PrimaryDataStoreTO destPool, String checksum, Map<String, String> headers, int connectTimeout, int soTimeout) { super(url, templateId, destPool, checksum, headers, connectTimeout, soTimeout, null); }
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) { START backupDao.remove(backup.getId()); END } return true; } If assignVMToBackupOffering does nothing then why we try to remove the VM here? Can we just return true as well?

Target:
public boolean removeVMFromBackupOffering(VirtualMachine vm) { s_logger.debug("Removing VM ID " + vm.getUuid() + " from backup offering by the Dummy Backup Provider"); return true; }
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()); START if (vlanByPodId != null && vlanByPodId.getRemoved() == null) { END result.add(vlanByPodId); } } return result; } a null check is enough, removed items are not returned by `GenericDaoBase::findById()`

Target:
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) { result.add(vlanByPodId); } } return result; }
Source:
private long executeSqlCountComputingResourcesForAccount(long accountId, String sqlCountComputingResourcesAllocatedToAccount) { START TransactionLegacy tx = TransactionLegacy.currentTxn() END 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); } } @DaanHoogland you missed ";" at the end of line 269.

Target:
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); } }
Source:
public String getSyncObjType() { if (getSyncObjId() != null) { START return BaseAsyncCmd.migrationSyncObject; END } return null; } Why did you need to implemente these `getSyncObjType` and `getSyncObjId`? Could you explain this a little bit further?

Target:
public String getSyncObjType() { return (getSyncObjId() != null) ? BaseAsyncCmd.migrationSyncObject : null; }
Source:
public void processHostVmStateReport(long hostId, Map<String, HostVmStateReportEntry> report) { START if (s_logger.isDebugEnabled()) END s_logger.debug("Process host VM state report. host: " + hostId); Map<Long, VirtualMachine.PowerState> translatedInfo = convertVmStateReport(report); processReport(hostId, translatedInfo); } Can you remove this IF condition as well?

Target:
public void processHostVmStateReport(long hostId, Map<String, HostVmStateReportEntry> report) { s_logger.debug("Process host VM state report. host: " + hostId); Map<Long, VirtualMachine.PowerState> translatedInfo = convertVmStateReport(report); processReport(hostId, translatedInfo); }
Source:
public Volume detachVolumeViaDestroyVM(long vmId, long volumeId) { START END Volume result = orchestrateDetachVolumeFromVM(vmId, volumeId); return result; } Extra new line can be removed here and other places.

Target:
public Volume detachVolumeViaDestroyVM(long vmId, long volumeId) { return orchestrateDetachVolumeFromVM(vmId, volumeId); }
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); START throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); END } } The same thing here regarding the passing of exception to the new one that is thrown.

Target:
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(), e); } }
Source:
public Boolean getMakeRedundant() { if (makeRedundant != null) { return makeRedundant; } START return true; END } If we don't pass anything, I think it should be false, it would continue with normal restart instead of this blue-green deployment.

Target:
public Boolean getMakeRedundant() { return makeRedundant; }
Source:
public Boolean getMakeredundant() { START if (makeredundant != null) { END return makeredundant; } return false; } 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.

Target:
public Boolean getMakeredundant() { return makeredundant; }
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); START assertEquals(time, dtParsed); END } 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.

Target:
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.toString(), dtParsed.toString()); }
Source:
public String getHost() { String[] hosts = _host.split(","); if (_hostCounter >= hosts.length) { _hostCounter = 0; } START s_logger.info("Connecting to host: " + hosts[_hostCounter % hosts.length]); END return hosts[_hostCounter++ % hosts.length]; } 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()...

Target:
public String getHost() { final String[] hosts = _host.split(","); if (_hostCounter >= hosts.length) { _hostCounter = 0; } final String host = hosts[_hostCounter % hosts.length]; _hostCounter++; return host; }
Source:
public static String[] getRecommendedProtocols() { START String[] supportedProtocols = { "TLSv1", "TLSv1.1", "TLSv1.2" }; END return supportedProtocols; } 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

Target:
public static String[] getRecommendedProtocols() { return new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" }; }
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; START this.cpuMaxDeviation = String.format("%.2f%%", (maxCpuUsagePercentage - averageCpuUsagePercentage) * 1.0 / averageCpuUsagePercentage); END } } is the '* 1.0' needed when it is devided next? I would rather see a cast if it is, in this case

Target:
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) / averageCpuUsagePercentage); } }
Source:
public void testFailRemoveOperation() { try { START domainManager.failRemoveOperation(domain, domainAccountsForCleanup, domainNetworkIds, true); END } catch (Exception e) { Assert.assertEquals(CloudRuntimeException.class, e.getClass()); } } 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.

Target:
public void testFailRemoveOperation() { domainManager.failRemoveOperation(domain, domainAccountsForCleanup, domainNetworkIds, true); }
Source:
START public void testReplaceNicsMacSequenceInBootArgs() throws Exception { END 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); } Do you need this `throws Exception` here? It does not seem o be required by any of the method calls you have here.

Target:
public void testReplaceNicsMacSequenceInBootArgs() { 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); }
Source:
private boolean checkOvsNetwork(final String networkName) { s_logger.debug("Checking if network " + networkName + " exists as openvswitch bridge"); if (networkName == null) { return true; } START final Script command = new Script("/bin/sh", _timeout.getMillis()); END command.add("-c"); command.add("ovs-vsctl br-exists " + networkName); return "0".equals(command.execute(null)); } Please consider adding an overridden version of the `Script(String, int)` constructor that accepts `Duration` to encapsulate this type conversion.

Target:
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); command.add("-c"); command.add("ovs-vsctl br-exists " + networkName); return "0".equals(command.execute(null)); }
Source:
public synchronized boolean destroyTunnelNetwork(final String bridge) { findOrCreateTunnelNetwork(bridge); START final Script cmd = new Script(_ovsTunnelPath, _timeout.getMillis(), s_logger); END 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; } Please consider adding an overridden version of the `Script(String, int, Logger)` constructor that accepts `Duration` to encapsulate this type conversion.

Target:
public synchronized boolean destroyTunnelNetwork(final String bridge) { findOrCreateTunnelNetwork(bridge); final Script cmd = new Script(_ovsTunnelPath, _timeout, 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; }
Source:
private Map<String, String> getVersionStrings() { START final Script command = new Script(_versionstringpath, _timeout.getMillis(), s_logger); END final KeyValueInterpreter kvi = new KeyValueInterpreter(); final String result = command.execute(kvi); if (result == null) { return kvi.getKeyValues(); } else { return new HashMap<String, String>(1); } } Please consider adding an overridden version of the `Script(String, int, Logger)` constructor that accepts `Duration` to encapsulate this type conversion.

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

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

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

Target:
public boolean cleanupRules() { if (!_canBridgeFirewall) { return false; } final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("cleanup_rules"); final String result = cmd.execute(); if (result != null) { return false; } return true; }
Source:
private void verifyNotEmpty(String name, String value) throws ConfigurationException { START if (org.apache.commons.lang.StringUtils.isEmpty(value)) { END throw new ConfigurationException("Unable to find " + name); } } Why not import the `org.apache.commons.lang` package and avoid some clutter?

Target:
private void verifyNotEmpty(String name, String value) throws ConfigurationException { if (StringUtils.isEmpty(value)) { throw new ConfigurationException("Unable to find " + name); } }
Source:
private NetworkVO getDefaultNetwork (long vmId) { NicVO defaultNic = _nicDao.findDefaultNicForVM(vmId); START if (defaultNic != null ) return _networkDao.findById(_nicDao.findById(defaultNic.getId()).getNetworkId()); END return null; } Not necessary to fetch the nic from DB twice.

Target:
private Long getDefaultNetwork(long vmId) { NicVO defaultNic = _nicDao.findDefaultNicForVM(vmId); if (defaultNic != null) { return defaultNic.getNetworkId(); } return null; }
Source:
private Long getDefaultNetwork(long vmId) { NicVO defaultNic = _nicDao.findDefaultNicForVM(vmId); START if (defaultNic != null) return defaultNic.getNetworkId(); END return null; } Per our coding standards, please wrap all `if` blocks in curly braces.

Target:
private Long getDefaultNetwork(long vmId) { NicVO defaultNic = _nicDao.findDefaultNicForVM(vmId); if (defaultNic != null) { return defaultNic.getNetworkId(); } return null; }
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; START } else { END return configureDhcpSupport(network, nic, vm, dest, Service.Dns); } } This `else` block is unnecessary since the `if` block returns. Please remove it.

Target:
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; } return configureDhcpSupport(network, nic, vm, dest, Service.Dns); }
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); } START VirtualMachineMO vmMo = dcMo.findVm(vol.getPath()); END return vmMo; } What about using here: `return dcMo.findVm(vol.getPath());` then, we could save 1 line of code ;)

Target:
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); } return dcMo.findVm(vol.getPath()); }
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); } START return result END } a ';' missing :(

Target:
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; }
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) { START } END } This `try` block and `fail` construct is unnecessary. Changing `@Test` to `@Test(expected = CloudRuntimeException.class)` accomplishes the same thing.

Target:
public void testGetOutOfBandManagementOptionsInvalid() { oobmService.getOptions(null); Assert.fail("CloudRuntimeException was expected for finding options of host with out-of-band management configuration"); }
Source:
public void testSetIdsListToSearchCriteria(){ mgr.setIdsListToSearchCriteria(sc, idsList); START Mockito.verify(sc, times(1)).setParameters(Mockito.same("idIN"), Mockito.same(id1), Mockito.same(id2)); END } the default of Mockito.verify already uses "times(1)"; so, there is no need to inform it.

Target:
public void testSetIdsListToSearchCriteria(){ mgr.setIdsListToSearchCriteria(sc, idsList); Mockito.verify(sc).setParameters(Mockito.same("idIN"), Mockito.same(id1), Mockito.same(id2)); }
Source:
public void testGetIdsListId(){ List<Long> result = mgr.getIdsListFromCmd(id1, idsEmptyList); START assertEquals(result, expectedListId); END } 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).

Target:
public void testGetIdsListId(){ List<Long> result = mgr.getIdsListFromCmd(id1, idsEmptyList); assertEquals(expectedListId, result); }
Source:
START public static ByteBuffer enlargeBuffer(ByteBuffer buffer, final int sessionProposedCapacity) { END if (sessionProposedCapacity > buffer.capacity()) { buffer = ByteBuffer.allocate(sessionProposedCapacity); } else { buffer = ByteBuffer.allocate(buffer.capacity() * 2); } return buffer; } Add `Preconditions.checkArgument` checks to verify that the passed `buffer` is not `null` and that `sessionProposedCapacity` is greater than zero.

Target:
public static ByteBuffer enlargeBuffer(ByteBuffer buffer, final int sessionProposedCapacity) { if (buffer == null || sessionProposedCapacity < 0) { return buffer; } if (sessionProposedCapacity > buffer.capacity()) { buffer = ByteBuffer.allocate(sessionProposedCapacity); } else { buffer = ByteBuffer.allocate(buffer.capacity() * 2); } return buffer; }
Source:
private boolean canCloneVolume() { START return new Boolean(getDriver().getCapabilities().get(DataStoreCapabilities.CAN_CREATE_VOLUME_FROM_VOLUME.toString())); END } `new Boolean` skips the constant pool -- placing unnecessary pressure on the garbage collector. Please use `Boolean.valueOf` instead.

Target:
private boolean canCloneVolume() { return Boolean.valueOf(getDriver().getCapabilities().get(DataStoreCapabilities.CAN_CREATE_VOLUME_FROM_VOLUME.toString())); }
Source:
public boolean isDisplay() { START if (displayNetwork == null) END return true; else return displayNetwork; } Either add the curly braces per coding conventions or reduce a ternary.

Target:
public boolean isDisplay() { if (displayNetwork == null) { return true; } else { return displayNetwork; } }
Source:
public void testProjectLockableAccount() { AccountVO accountVO = new AccountVO(); accountVO.setId(7L); accountVO.setDomainId(1L); accountVO.setType(Account.ACCOUNT_TYPE_PROJECT); START assertFalse(quotaManager.isLockable(accountVO)); END } @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.

Target:
public void testProjectLockableAccount() { accountVO.setType(Account.ACCOUNT_TYPE_PROJECT); assertFalse(quotaManager.isLockable(accountVO)); }
Source:
public String getDetail(String name) { START assert (details != null) : "Did you forget to load the details?"; END return details.get(name); } I would have solved this one by removing the assert. Do we even run any tests with asserts enabled? (no :-1: intended!)

Target:
public String getDetail(String name) { return details.get(name); }
Source:
private void setEncodeApiResponse(final boolean encodeApiResponse) { START ApiServer.encodeApiResponse = encodeApiResponse; END } What is this for? It seems like a strange thing to do

Target:
private static void setEncodeApiResponse(final boolean encodeApiResponse) { ApiServer.encodeApiResponse = encodeApiResponse; }
Source:
public String toString() { StringBuilder fsBuilder = new StringBuilder(); for (Map.Entry<String, String> address : addresses.entrySet()) { fsBuilder.append("<nuage-extension>\n"); START fsBuilder.append(" <interface mac='" + address.getKey() + "' vsp-vr-ip='" + address.getValue() + "'></interface>\n"); END fsBuilder.append("</nuage-extension>\n"); } return fsBuilder.toString(); } 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"); ```

Target:
public String toString() { StringBuilder fsBuilder = new StringBuilder(); for (Map.Entry<String, String> address : addresses.entrySet()) { fsBuilder.append("<nuage-extension>\n") .append(" <interface mac='") .append(address.getKey()) .append("' vsp-vr-ip='") .append(address.getValue()) .append("'></interface>\n") .append("</nuage-extension>\n"); } return fsBuilder.toString(); }
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(); } START } catch (Exception e) { END throw new CloudRuntimeException("Unable to update the volume id for volume store ref"); } return true; } please catch more specific/explicit exceptions. In this case the original exception is not passed through or embedded so it is totally lost.

Target:
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", e); } return true; }
Source:
private NuageVspPluginClientLoader(String nuagePluginClientJarLocation) { try { _loader = URLClassLoader.newInstance(new URL[] {new URL("jar:file:" + nuagePluginClientJarLocation + "!/")}, getClass().getClassLoader()); } catch (MalformedURLException e) { START e.printStackTrace(); END } } `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?

Target:
private NuageVspPluginClientLoader(String nuagePluginClientJarLocation) { try { _loader = URLClassLoader.newInstance(new URL[] {new URL("jar:file:" + nuagePluginClientJarLocation + "!/")}, getClass().getClassLoader()); } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } }
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; START } END I think we can un-final it

Target:
public int hashCode() { int result = super.hashCode(); result = 31 * result + (_currentApiVersion != null ? _currentApiVersion.hashCode() : 0); result = 31 * result + (_apiRetryCount != null ? _apiRetryCount.hashCode() : 0); result = 31 * result + (_apiRetryInterval != null ? _apiRetryInterval.hashCode() : 0); return result; }
Source:
public int hashCode() { int result = _syncType != null ? _syncType.hashCode() : 0; result = 31 * result + (_nuageVspCmsId != null ? _nuageVspCmsId.hashCode() : 0); return result; START } END @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.

Target:
public int hashCode() { int result = super.hashCode(); result = 31 * result + (_syncType != null ? _syncType.hashCode() : 0); result = 31 * result + (_nuageVspCmsId != null ? _nuageVspCmsId.hashCode() : 0); return result; }