auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean handleNetworkException(VDSNetworkException ex, VDS vds) { if (vds.getStatus() != VDSStatus.Down) { long timeoutToFence = calcTimeoutToFence(vds.getVmCount(), vds.getSpmStatus()); if (mUnrespondedAttempts.get() < Config.<Integer> GetValue(ConfigValues.VDSAttemptsToResetCount) || (lastUpdate + timeoutToFence) > System.currentTimeMillis()) { boolean result = false; if (vds.getStatus() != VDSStatus.Connecting && vds.getStatus() != VDSStatus.PreparingForMaintenance && vds.getStatus() != VDSStatus.NonResponsive) { setStatus(VDSStatus.Connecting, vds); result = true; } mUnrespondedAttempts.incrementAndGet(); return result; } if (vds.getStatus() == VDSStatus.NonResponsive || vds.getStatus() == VDSStatus.Maintenance) { setStatus(VDSStatus.NonResponsive, vds); return true; } setStatus(VDSStatus.NonResponsive, vds); log.infoFormat( "Server failed to respond, vds_id = {0}, vds_name = {1}, vm_count = {2}, " + <START> "spm_status = {3}, non-responsive_timeout = {4}, error = {5}", <END> vds.getId(), vds.getName(), vds.getVmCount(), vds.getSpmStatus(), TimeUnit.MILLISECONDS.toSeconds(timeoutToFence), ex.getMessage()); AuditLogableBase logable = new AuditLogableBase(vds.getId()); AuditLogDirector.log(logable, AuditLogType.VDS_FAILURE); ResourceManager.getInstance().getEventListener().vdsNotResponding(vds); } return true; }</code><technical_language>Please add proper time unit log print, clear</technical_language>

Target:
public boolean handleNetworkException(VDSNetworkException ex, VDS vds) { if (vds.getStatus() != VDSStatus.Down) { long timeoutToFence = calcTimeoutToFence(vds.getVmCount(), vds.getSpmStatus()); if (mUnrespondedAttempts.get() < Config.<Integer> GetValue(ConfigValues.VDSAttemptsToResetCount) || (lastUpdate + timeoutToFence) > System.currentTimeMillis()) { boolean result = false; if (vds.getStatus() != VDSStatus.Connecting && vds.getStatus() != VDSStatus.PreparingForMaintenance && vds.getStatus() != VDSStatus.NonResponsive) { setStatus(VDSStatus.Connecting, vds); result = true; } mUnrespondedAttempts.incrementAndGet(); return result; } if (vds.getStatus() == VDSStatus.NonResponsive || vds.getStatus() == VDSStatus.Maintenance) { setStatus(VDSStatus.NonResponsive, vds); return true; } setStatus(VDSStatus.NonResponsive, vds); log.infoFormat( "Server failed to respond, vds_id = {0}, vds_name = {1}, vm_count = {2}, " + "spm_status = {3}, non-responsive_seconds = {4}, error = {5}", vds.getId(), vds.getName(), vds.getVmCount(), vds.getSpmStatus(), TimeUnit.MILLISECONDS.toSeconds(timeoutToFence), ex.getMessage()); AuditLogableBase logable = new AuditLogableBase(vds.getId()); AuditLogDirector.log(logable, AuditLogType.VDS_FAILURE); ResourceManager.getInstance().getEventListener().vdsNotResponding(vds); } return true; }
Source:
<code>public void testAddWithParameterUpdate() throws Exception { <START> assertTrue(new File(db.getWorkTree(), "sub").mkdir()); <END> File file = new File(db.getWorkTree(), "sub/a.txt"); FileUtils.createNewFile(file); PrintWriter writer = new PrintWriter(file); writer.print("content"); writer.close(); File file2 = new File(db.getWorkTree(), "sub/b.txt"); FileUtils.createNewFile(file2); writer = new PrintWriter(file2); writer.print("content b"); writer.close(); Git git = new Git(db); git.add().addFilepattern("sub").call(); assertEquals( "[sub/a.txt, mode:100644, content:content]" + "[sub/b.txt, mode:100644, content:content b]", indexState(CONTENT)); git.commit().setMessage("commit").call(); File file3 = new File(db.getWorkTree(), "sub/c.txt"); FileUtils.createNewFile(file3); writer = new PrintWriter(file3); writer.print("content c"); writer.close(); writer = new PrintWriter(file); writer.print("modified content"); writer.close(); FileUtils.delete(file2); git.add().addFilepattern("sub").setUpdate(true).call(); assertEquals( "[sub/a.txt, mode:100644, content:modified content]", indexState(CONTENT)); }</code><technical_language>FileUtils.mkdirs</technical_language>

Target:
public void testAddWithParameterUpdate() throws Exception { FileUtils.mkdir(new File(db.getWorkTree(), "sub")); File file = new File(db.getWorkTree(), "sub/a.txt"); FileUtils.createNewFile(file); PrintWriter writer = new PrintWriter(file); writer.print("content"); writer.close(); File file2 = new File(db.getWorkTree(), "sub/b.txt"); FileUtils.createNewFile(file2); writer = new PrintWriter(file2); writer.print("content b"); writer.close(); Git git = new Git(db); git.add().addFilepattern("sub").call(); assertEquals( "[sub/a.txt, mode:100644, content:content]" + "[sub/b.txt, mode:100644, content:content b]", indexState(CONTENT)); git.commit().setMessage("commit").call(); File file3 = new File(db.getWorkTree(), "sub/c.txt"); FileUtils.createNewFile(file3); writer = new PrintWriter(file3); writer.print("content c"); writer.close(); writer = new PrintWriter(file); writer.print("modified content"); writer.close(); FileUtils.delete(file2); git.add().addFilepattern("sub").setUpdate(true).call(); assertEquals( "[sub/a.txt, mode:100644, content:modified content]", indexState(CONTENT)); }
Source:
<code>public void appendConstraints(AllocationAttempt attempt, AllocationLog log, List<Constraint> constraints) { for (Instance instance : attempt.getInstances()) { List<Volume> volumes = InstanceHelpers.extractVolumesFromMounts(instance, objectManager); for (Volume v : volumes) { if (VolumeConstants.ACCESS_MODE_SINGLE_HOST_RW.equals(v.getAccessMode())) { Long hostID = null; Object hostIdObject = DataAccessor.fromDataFieldOf(v).withKey(VolumeConstants.FIELD_LAST_ALLOCATED_HOST_ID).get(); if ( hostIdObject != null) { hostID = Long.parseLong(hostIdObject.toString()); } Set<Long> hostIds = allocatorDao.findHostsWithVolumeInUse(v.getId()); boolean hardConstraint = false; if (hostIds.size() == 0) { hardConstraint = false; } else if (hostIds.size() == 1) { hardConstraint = true; for(Long id: hostIds) { hostID = id; } } else { throw new FailedToAllocate("SingleHostRW volume is used by mutiple hosts"); } if (hostID != null) { <START> constraints.add(new VolumeAccessModeSingleHostConstraint(hostID, v.getId(), v.getName(), hardConstraint)); <END> } } else if (VolumeConstants.ACCESS_MODE_SINGLE_INSTANCE_RW.equals(v.getAccessMode())) { List<Long> currentlyUsedBy = allocatorDao.getInstancesWithVolumeMounted(v.getId(), instance.getId()); if (currentlyUsedBy.size() > 0) { constraints.add(new VolumeAccessModeSingleInstanceConstraint(v.getId(), v.getAccessMode(), currentlyUsedBy)); } } } } }</code><technical_language>Lookup host add host name too. objectManager</technical_language>

Target:
public void appendConstraints(AllocationAttempt attempt, AllocationLog log, List<Constraint> constraints) { for (Instance instance : attempt.getInstances()) { List<Volume> volumes = InstanceHelpers.extractVolumesFromMounts(instance, objectManager); for (Volume v : volumes) { if (VolumeConstants.ACCESS_MODE_SINGLE_HOST_RW.equals(v.getAccessMode())) { Long hostID = null; Object hostIdObject = DataAccessor.fromDataFieldOf(v).withKey(VolumeConstants.FIELD_LAST_ALLOCATED_HOST_ID).get(); if ( hostIdObject != null) { hostID = Long.parseLong(hostIdObject.toString()); } Set<Long> hostIds = allocatorDao.findHostsWithVolumeInUse(v.getId()); boolean hardConstraint = false; if (hostIds.size() == 0) { hardConstraint = false; } else if (hostIds.size() == 1) { hardConstraint = true; for(Long id: hostIds) { hostID = id; } } else { throw new FailedToAllocate("SingleHostRW volume is used by mutiple hosts"); } if (hostID != null) { Host host = objectManager.loadResource(Host.class, hostID); String hostName = DataAccessor.fieldString(host, HostConstants.FIELD_HOSTNAME); constraints.add(new VolumeAccessModeSingleHostConstraint(hostID, v.getId(), v.getName(), hostName, hardConstraint)); } } else if (VolumeConstants.ACCESS_MODE_SINGLE_INSTANCE_RW.equals(v.getAccessMode())) { List<Long> currentlyUsedBy = allocatorDao.getInstancesWithVolumeMounted(v.getId(), instance.getId()); if (currentlyUsedBy.size() > 0) { constraints.add(new VolumeAccessModeSingleInstanceConstraint(v.getId(), v.getAccessMode(), currentlyUsedBy)); } } } } }
Source:
<code><START> default Function<KeyType, Integer> hashFunction() <END> { return Groupers::hash; }</code><technical_language>ToIntFunction, consider designing this system array-based aggregation avoid boxing of key also</technical_language>

Target:
default ToIntFunction<KeyType> hashFunction() { return Groupers::hash; }
Source:
<code>public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity) throws InfrastructureException { final String workspaceId = identity.getWorkspaceId(); if (EphemeralWorkspaceAdapter.isEphemeral(k8sEnv.getAttributes())) { ephemeralWorkspaceAdapter.provision(k8sEnv, identity); return; } final Set<String> subPaths = new HashSet<>(); final PersistentVolumeClaim pvc = newPVC(pvcName, pvcAccessMode, pvcQuantity); k8sEnv.getPersistentVolumeClaims().put(pvcName, pvc); for (Pod pod : k8sEnv.getPods().values()) { PodSpec podSpec = pod.getSpec(); List<Container> containers = new ArrayList<>(); containers.addAll(podSpec.getContainers()); containers.addAll(podSpec.getInitContainers()); for (Container container : podSpec.getContainers()) { <START> String machineName = Names.machineName(pod, container); <END> InternalMachineConfig machineConfig = k8sEnv.getMachines().get(machineName); addMachineVolumes(workspaceId, subPaths, pod, container, machineConfig.getVolumes()); } } if (preCreateDirs && !subPaths.isEmpty()) { pvc.setAdditionalProperty( format(SUBPATHS_PROPERTY_FMT, workspaceId), subPaths.toArray(new String[subPaths.size()])); } }</code><technical_language>I is</technical_language>

Target:
public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity) throws InfrastructureException { final String workspaceId = identity.getWorkspaceId(); if (EphemeralWorkspaceUtility.isEphemeral(k8sEnv.getAttributes())) { ephemeralWorkspaceAdapter.provision(k8sEnv, identity); return; } LOG.debug("Provisioning PVC strategy for workspace '{}'", workspaceId); final Set<String> subPaths = new HashSet<>(); final PersistentVolumeClaim pvc = newPVC(pvcName, pvcAccessMode, pvcQuantity); k8sEnv.getPersistentVolumeClaims().put(pvcName, pvc); for (Pod pod : k8sEnv.getPods().values()) { PodSpec podSpec = pod.getSpec(); List<Container> containers = new ArrayList<>(); containers.addAll(podSpec.getContainers()); containers.addAll(podSpec.getInitContainers()); for (Container container : containers) { String machineName = Names.machineName(pod, container); InternalMachineConfig machineConfig = k8sEnv.getMachines().get(machineName); addMachineVolumes(workspaceId, subPaths, pod, container, machineConfig.getVolumes()); } } if (preCreateDirs && !subPaths.isEmpty()) { pvc.setAdditionalProperty( format(SUBPATHS_PROPERTY_FMT, workspaceId), subPaths.toArray(new String[subPaths.size()])); } LOG.debug("PVC strategy provisioning done for workspace '{}'", workspaceId); }
Source:
<code>public DiagnosticsPlugin(int diagnosticsPort, int httpPort, String projectName, String workingDirectory) throws IOException { try { serverSocket = new ServerSocket(diagnosticsPort, SERVER_SOCKET_BACKLOG, InetAddress.getLoopbackAddress()); } catch (IOException | IllegalArgumentException | SecurityException ex) { Logger.sys.error("Problem creating server socket: " + ex); throw ex; } modelMapper = new ModelMapper(projectName); instanceRegister = new InstanceRegister(); animator = new Animator(instanceRegister, modelMapper); server = new DiagnosticsServer(this); try { server.start(httpPort); } catch (IOException e) { Logger.sys.error("Couldn't start HTTP server on port " + httpPort + " in service instance 0x", e); return; } <START> Logger.sys.info("txtUML diagnostics connection is set on HTTP port " + httpPort ); <END> thread = new Thread(this, "txtUMLDiagnosticsPlugin"); thread.start(); }</code><technical_language>This user, honestly this is redirected to</technical_language>

Target:
public DiagnosticsPlugin(int diagnosticsPort, int httpPort, String projectName, String workingDirectory) throws IOException { try { serverSocket = new ServerSocket(diagnosticsPort, SERVER_SOCKET_BACKLOG, InetAddress.getLoopbackAddress()); } catch (IOException | IllegalArgumentException | SecurityException ex) { Logger.sys.error("Problem creating server socket: " + ex); throw ex; } modelMapper = new ModelMapper(projectName); instanceRegister = new InstanceRegister(); animator = new Animator(instanceRegister, modelMapper); server = new DiagnosticsServer(this); try { server.start(httpPort); } catch (IOException e) { Logger.sys.error("Couldn't start HTTP server on port " + httpPort + " in service instance 0x", e); return; } thread = new Thread(this, "txtUMLDiagnosticsPlugin"); thread.start(); }
Source:
<code>public void eventOccured(String message) { StringTokenizer strTok = new StringTokenizer(message, "\n"); String data = null; int i = 0; while (strTok.hasMoreTokens()) { String s = strTok.nextToken(); if (s.contains(SHCMessage.DATA_FLAG)) { data = s; <START> logger.debug("<BaseStation data>[" + (i) + "]: " + data); <END> } } if (data != null) { SHCMessage shcMessage = new SHCMessage(data, packet); SHCHeader shcHeader = shcMessage.getHeader(); logger.debug("BaseStation SenderID: " + shcHeader.getSenderID() + " MsgType: " + shcHeader.getMessageType() + " MsgGroupID:" + shcHeader.getMessageGroupID() + " MsgID: " + shcHeader.getMessageID() + " MsgData: " + shcHeader.getMessageData()); SHCData info = shcMessage.getData(); if (info != null) { logger.debug(info.toString()); } for (SmarthomaticBindingProvider provider : this.providers) { for (String itemName : provider.getItemNames()) { if (shcHeader.getSenderID() == provider.getDeviceId(itemName) && shcHeader.getMessageGroupID() == provider.getMessageGroupId(itemName) && shcHeader.getMessageID() == provider.getMessageId(itemName)) { Type type = shcMessage.openHABStateFromSHCMessage(provider.getItem(itemName)) .get(provider.getMessagePartId(itemName)); String transformed = processTransformation(provider.getConfigParam(itemName, "transformation"), type.toString()); if (type instanceof DecimalType) { type = DecimalType.valueOf(transformed); } if (isDataTypeSupported(provider.getItem(itemName), type)) { eventPublisher.postUpdate(itemName, (State) type); } } } } } }</code><technical_language>Please slf4j parametrization instead of string concatenation</technical_language>

Target:
public void eventOccured(String message) { StringTokenizer strTok = new StringTokenizer(message, "\n"); String data = null; int i = 0; while (strTok.hasMoreTokens()) { String s = strTok.nextToken(); if (s.contains(SHCMessage.DATA_FLAG)) { data = s; logger.debug("<BaseStation data>[{}]: {}", i, data); } } if (data != null) { SHCMessage shcMessage = new SHCMessage(data, packet); SHCHeader shcHeader = shcMessage.getHeader(); logger.debug("BaseStation SenderID: MsgType: MsgGroupID: MsgID: MsgData: {}", shcHeader.getSenderID(), shcHeader.getMessageType(), shcHeader.getMessageGroupID(), shcHeader.getMessageID(), shcHeader.getMessageData()); SHCData info = shcMessage.getData(); if (info != null) { logger.debug(info.toString()); } for (SmarthomaticBindingProvider provider : this.providers) { for (String itemName : provider.getItemNames()) { if (shcHeader.getSenderID() == provider.getDeviceId(itemName) && shcHeader.getMessageGroupID() == provider.getMessageGroupId(itemName) && shcHeader.getMessageID() == provider.getMessageId(itemName)) { Type type = shcMessage.openHABStateFromSHCMessage(provider.getItem(itemName)) .get(provider.getMessagePartId(itemName)); String transformed = processTransformation(provider.getConfigParam(itemName, "transformation"), type.toString()); if (type instanceof DecimalType) { type = DecimalType.valueOf(transformed); } if (isDataTypeSupported(provider.getItem(itemName), type)) { eventPublisher.postUpdate(itemName, (State) type); } } } } } }
Source:
<code>public MiniEditorComponentObject triggerEditCommentArea() { jsActions.scrollToElement(allCommentsArea); WebElement mostRecentComment = articleComments.get(0); PageObjectLogging.log("First check",mostRecentComment.getText(), true); JavascriptExecutor js = (JavascriptExecutor) driver; WebElement editButton = mostRecentComment.findElement(By.cssSelector(EDIT_BUTTON_SELECTOR)); <START> Actions actions = new Actions(driver); <END> actions.moveToElement(editButton).perform(); js.executeScript("arguments[0].querySelector(arguments[1]).click()", mostRecentComment, EDIT_BUTTON_SELECTOR); return new MiniEditorComponentObject(driver); }</code><technical_language>merge line</technical_language>

Target:
public MiniEditorComponentObject triggerEditCommentArea() { jsActions.scrollToElement(allCommentsArea); WebElement mostRecentComment = articleComments.get(0); PageObjectLogging.log("First check",mostRecentComment.getText(), true); JavascriptExecutor js = (JavascriptExecutor) driver; WebElement editButton = mostRecentComment.findElement(By.cssSelector(EDIT_BUTTON_SELECTOR)); new Actions(driver).moveToElement(editButton).perform(); js.executeScript("arguments[0].querySelector(arguments[1]).click()", mostRecentComment, EDIT_BUTTON_SELECTOR); return new MiniEditorComponentObject(driver); }
Source:
<code>private URI createURI(String query, Collection<? extends NameValuePair> origParams) { final List<NameValuePair> params = new ArrayList<>( origParams); if (apiAccessKey != null) { params.add(new BasicNameValuePair("key", apiAccessKey)); } try { final URIBuilder builder = new URIBuilder(baseURL.toURI()); builder.addParameters(new ArrayList<>(origParams)); if (apiAccessKey != null) { builder.addParameter("key", apiAccessKey); } if (!query.isEmpty()) { String builderPath = builder.getPath(); if (null == builderPath) { builderPath = ""; } <START> builder.setPath(builderPath + "/" + query); <END> } return builder.build(); } catch (URISyntaxException e) { throw new RedmineInternalError(e); } }</code><technical_language>builder.getPath() == null? "" : builder.getPath()</technical_language>

Target:
private URI createURI(String query, Collection<? extends NameValuePair> origParams) { final List<NameValuePair> params = new ArrayList<>( origParams); if (apiAccessKey != null) { params.add(new BasicNameValuePair("key", apiAccessKey)); } try { final URIBuilder builder = new URIBuilder(baseURL.toURI()); builder.addParameters(new ArrayList<>(origParams)); if (apiAccessKey != null) { builder.addParameter("key", apiAccessKey); } if (!query.isEmpty()) { builder.setPath((builder.getPath() == null? "" : builder.getPath()) + "/" + query); } return builder.build(); } catch (URISyntaxException e) { throw new RedmineInternalError(e); } }
Source:
<code>private Set<GlusterServerInfo> fetchServers(VDSGroup cluster, VDS upServer, List<VDS> existingServers) { Set<GlusterServerInfo> fetchedServers; GlusterServersListVDSCommand<VdsIdVDSCommandParametersBase> serversListCommand = <START> createServersListCommand(upServer); <END> fetchedServers = (Set<GlusterServerInfo>)serversListCommand.ExecuteWithReturnValue(); if(fetchedServers.size() == 1 && existingServers.size() > 2) { GlusterServerInfo server = fetchedServers.iterator().next(); if(server.getHostnameOrIp().equals(upServer.gethost_name()) || server.getHostnameOrIp().equals(upServer.getManagmentIp())) { upServer = getNewUpServer(existingServers, upServer); if (upServer == null) { log.warnFormat("The only UP server in cluster {0} seems to have been removed from it using gluster CLI. " + "Can't refresh it's data at this point.", cluster.getname()); return null; } fetchedServers = (Set<GlusterServerInfo>)serversListCommand.ExecuteWithReturnValue(); } } return fetchedServers; }</code><technical_language>create commands yourself, is a factory for it. in order run VDSCommands use: Backend.getInstance().getResourceManager() .RunVdsCommand(VDSCommandType.GlusterServersList, new VdsIdVDSCommandParametersBase(upServer.getId()));</technical_language>

Target:
private Set<GlusterServerInfo> fetchServers(VDSGroup cluster, VDS upServer, List<VDS> existingServers) { Set<GlusterServerInfo> fetchedServers; GlusterServersListVDSCommand<VdsIdVDSCommandParametersBase> serversListCommand = createServersListCommand(upServer); fetchedServers = (Set<GlusterServerInfo>)serversListCommand.ExecuteWithReturnValue(); if (fetchedServers != null && fetchedServers.size() == 1 && existingServers.size() > 2) { GlusterServerInfo server = fetchedServers.iterator().next(); if(server.getHostnameOrIp().equals(upServer.gethost_name()) || server.getHostnameOrIp().equals(upServer.getManagmentIp())) { upServer = getNewUpServer(existingServers, upServer); if (upServer == null) { log.warnFormat("The only UP server in cluster {0} seems to have been removed from it using gluster CLI. " + "Can't refresh it's data at this point.", cluster.getname()); return null; } fetchedServers = (Set<GlusterServerInfo>)serversListCommand.ExecuteWithReturnValue(); } } return fetchedServers; }
Source:
<code>private void adjustOpeningAndClosingAndVisibleTimeForPrivateSessions() { if (getStartTime() == null) { setStartTime(getCreatedTime()); } if (getEndTime() == null) { setEndTime(TimeHelper.parseInstant("2118-01-01 12:00 AM +0000")); } if ("PRIVATE".equals(feedbackSessionType)) { <START> setSessionVisibleFromTime(TimeHelper.parseInstant("2118-01-01 12:00 AM +0000")); <END> } }</code><technical_language>I realised session visible time is supposed session start time: <img width="940" alt="screen shot 2018-04-04 4 58 11 pm" src="<LINK_0>"> Hence, is start time need set a years later. visible time set TIME_REPRESENTS_FOLLOW_OPENING start time</technical_language>

Target:
private void adjustOpeningAndClosingAndVisibleTimeForPrivateSessions() { if ("PRIVATE".equals(feedbackSessionType)) { setStartTime(TimeHelper.parseInstant("2118-01-01 12:00 AM +0000")); setSessionVisibleFromTime(Const.TIME_REPRESENTS_FOLLOW_OPENING); setEndTime(TimeHelper.parseInstant("2118-01-01 12:00 AM +0000")); } }
Source:
<code>public void kill() throws IOException, InterruptedException { <START> this.action("kill-server"); <END> }</code><technical_language>redundant this qualifier</technical_language>

Target:
public void kill() throws IOException, InterruptedException { executeAdb("kill-server"); }
Source:
<code>public void init() { this.addParameter("name", this.name); this.addParameter("context", this.context); this.addParameter("visibility", this.visibility); this.addParameter("version", this.version); this.addParameter("swagger", this.swagger); <START> this.addParameter("tags", this.tags); <END> this.addParameter("description", this.description); }</code><technical_language>passing tags, description arguments in this constructor. initializing here</technical_language>

Target:
public void init() { this.addParameter("name", this.name); this.addParameter("context", this.context); this.addParameter("visibility", this.visibility); this.addParameter("version", this.version); this.addParameter("swagger", this.swagger); }
Source:
<code><START> public NamedConfig setName(String name) { <END> this.name = name; return this; }</code><technical_language>this ClientReliableTopicConfig (similar done for FlakeIdGeneratorConfig)</technical_language>

Target:
public ClientReliableTopicConfig setName(String name) { this.name = name; return this; }
Source:
<code>public Path rename(final Path pathToPomXML, final String newName, final String comment) { try { final org.uberfire.java.nio.file.Path projectDirectory = Paths.convert(pathToPomXML).getParent(); final org.uberfire.java.nio.file.Path newModulePath = projectDirectory.resolveSibling(newName); final POM content = pomService.load(pathToPomXML); if (newModulePath.equals(projectDirectory)) { return pathToPomXML; } if (ioService.exists(newModulePath)) { throw new FileAlreadyExistsException(newModulePath.toString()); } final Path oldModuleDir = Paths.convert(projectDirectory); final Module oldModule = resourceResolver.resolveModule(oldModuleDir); content.setName(newName); final Path newPathToPomXML = Paths.convert(newModulePath.resolve(POM_PATH)); try { ioService.startBatch(newModulePath.getFileSystem()); ioService.move(projectDirectory, newModulePath, commentedOptionFactory.makeCommentedOption(comment)); pomService.save(newPathToPomXML, content, <START> null, <END> comment); } catch (final Exception e) { throw e; } finally { final Module newModule = resourceResolver.resolveModule(Paths.convert(newModulePath)); renameModuleEvent.fire(new RenameModuleEvent(oldModule, newModule)); ioService.endBatch(); } invalidateDMOCache.fire(new InvalidateDMOModuleCacheEvent(sessionInfo, oldModule, oldModuleDir)); return newPathToPomXML; } catch (final Exception e) { throw ExceptionUtilities.handleException(e); } }</code><technical_language>Firing event in finally block? if inService.move in try block fails. fire event in try block move succeeds</technical_language>

Target:
public Path rename(final Path pathToPomXML, final String newName, final String comment) { try { final org.uberfire.java.nio.file.Path projectDirectory = Paths.convert(pathToPomXML).getParent(); final org.uberfire.java.nio.file.Path newModulePath = projectDirectory.resolveSibling(newName); final POM content = pomService.load(pathToPomXML); if (newModulePath.equals(projectDirectory)) { return pathToPomXML; } if (ioService.exists(newModulePath)) { throw new FileAlreadyExistsException(newModulePath.toString()); } final Path oldModuleDir = Paths.convert(projectDirectory); final Module oldModule = resourceResolver.resolveModule(oldModuleDir); content.setName(newName); final Path newPathToPomXML = Paths.convert(newModulePath.resolve(POM_PATH)); try { ioService.startBatch(newModulePath.getFileSystem()); ioService.move(projectDirectory, newModulePath, commentedOptionFactory.makeCommentedOption(comment)); pomService.save(newPathToPomXML, content, null, comment); final Module newModule = resourceResolver.resolveModule(Paths.convert(newModulePath)); renameModuleEvent.fire(new RenameModuleEvent(oldModule, newModule)); } catch (final Exception e) { throw e; } finally { ioService.endBatch(); } invalidateDMOCache.fire(new InvalidateDMOModuleCacheEvent(sessionInfo, oldModule, oldModuleDir)); return newPathToPomXML; } catch (final Exception e) { throw ExceptionUtilities.handleException(e); } }
Source:
<code>public void testFindScriptResources() throws Exception { TestApplication app = new TestApplication(); String targetId1 = this.mngr.createTarget( "id: tid1\nhandler: h" ); String targetId2 = this.mngr.createTarget( "id: tid2\nhandler: h" ); this.mngr.associateTargetWith( targetId1, app, null ); this.mngr.associateTargetWith( targetId2, app, null ); File dir1 = new File( this.configurationMngr.getWorkingDirectory(), ConfigurationUtils.TARGETS + "/" + targetId1 ); File dir2 = new File( this.configurationMngr.getWorkingDirectory(), ConfigurationUtils.TARGETS + "/" + targetId2 ); Utils.createDirectory( dir1 ); Utils.createDirectory( dir2 ); Utils.writeStringInto( "#!/bin/bash\necho Bonjour le monde cruel > toto.txt", new File( dir1, "tott.script" )); Utils.writeStringInto( "#!/bin/bash\necho touch toto.txt", new File( dir2, "titi.script" )); <START> Assert.assertNotNull( this.mngr.findScriptResources(targetId1) ); <END> Assert.assertNotNull( this.mngr.findScriptResources(targetId2) ); }</code><technical_language>method return null, empty map in worst case. So, test map size key</technical_language>

Target:
public void testFindScriptResources() throws Exception { TestApplication app = new TestApplication(); String targetId1 = this.mngr.createTarget( "id: tid1\nhandler: h" ); String targetId2 = this.mngr.createTarget( "id: tid2\nhandler: h" ); this.mngr.associateTargetWith( targetId1, app, null ); this.mngr.associateTargetWith( targetId2, app, null ); File dir1 = new File( this.configurationMngr.getWorkingDirectory(), ConfigurationUtils.TARGETS + "/" + targetId1 ); File dir2 = new File( this.configurationMngr.getWorkingDirectory(), ConfigurationUtils.TARGETS + "/" + targetId2 ); Utils.createDirectory( dir1 ); Utils.createDirectory( dir2 ); Utils.writeStringInto( "#!/bin/bash\necho Bonjour le monde cruel > toto.txt", new File( dir1, "target-script.sh" )); Utils.writeStringInto( "#!/bin/bash\necho touch toto.txt", new File( dir2, "target-script.py" )); Assert.assertEquals( 1, this.mngr.findScriptResources(targetId1).size() ); Assert.assertEquals( 1, this.mngr.findScriptResources( app, app.getMySql()).size()); }
Source:
<code>protected void declareConstraintsAndOr(final List<KiePMMLFieldOperatorValue> orConstraints, final CEDescrBuilder<?, ?> andOrBuilder) { for (KiePMMLFieldOperatorValue kiePMMLOperatorValue : orConstraints) { if (kiePMMLOperatorValue.getName() != null) { commonDeclarePatternWithConstraint(andOrBuilder, kiePMMLOperatorValue.getName(), kiePMMLOperatorValue.getConstraintsAsString()); } if (kiePMMLOperatorValue.getNestedKiePMMLFieldOperatorValues() != null) { switch (kiePMMLOperatorValue.getOperator()) { <START> case "||": <END> declareConstraintsAndOr(kiePMMLOperatorValue.getNestedKiePMMLFieldOperatorValues(), andOrBuilder.or()); break; case "&&": declareConstraintsAndOr(kiePMMLOperatorValue.getNestedKiePMMLFieldOperatorValues(), andOrBuilder.and()); break; default: throw new KiePMMLException(String.format("Operator %s not managed inside declareConstraintsAndOr, yet", kiePMMLOperatorValue.getOperator())); } } } }</code><technical_language>enum instead of a string for operator? Is custom operators</technical_language>

Target:
protected void declareConstraintsAndOr(final List<KiePMMLFieldOperatorValue> orConstraints, final CEDescrBuilder<?, ?> andOrBuilder) { for (KiePMMLFieldOperatorValue kiePMMLFieldOperatorValue : orConstraints) { if (kiePMMLFieldOperatorValue.getName() != null) { commonDeclarePatternWithConstraint(andOrBuilder, kiePMMLFieldOperatorValue.getName(), kiePMMLFieldOperatorValue.getConstraintsAsString()); } if (kiePMMLFieldOperatorValue.getNestedKiePMMLFieldOperatorValues() != null) { switch (kiePMMLFieldOperatorValue.getOperator()) { case OR: declareConstraintsAndOr(kiePMMLFieldOperatorValue.getNestedKiePMMLFieldOperatorValues(), andOrBuilder.or()); break; case AND: declareConstraintsAndOr(kiePMMLFieldOperatorValue.getNestedKiePMMLFieldOperatorValues(), andOrBuilder.and()); break; default: throw new KiePMMLException(String.format("Operator %s not managed inside declareConstraintsAndOr, yet", kiePMMLFieldOperatorValue.getOperator())); } } } }
Source:
<code>protected void executeQueryCommand() { <START> getQueryReturnValue().setSucceeded(true); <END> if (getVdsStaticDao().getByHostName(getParameters().getServerName()) != null || getVdsStaticDao().getAllWithIpAddress(getParameters().getServerName()).size() > 0) { setErrorMessage(VdcBllMessages.SERVER_ALREADY_EXISTS_IN_ANOTHER_CLUSTER.toString()); return; } SSHClient client = null; try { Map<String, String> serverFingerPrintMap = getGlusterUtil().getPeers(getParameters().getServerName(), getParameters().getPassword(), getParameters().getFingerprint()); if (!validateServers(serverFingerPrintMap.keySet())) { setErrorMessage(VdcBllMessages.SERVER_ALREADY_EXISTS_IN_ANOTHER_CLUSTER.toString()); } serverFingerPrintMap.put(getParameters().getServerName(), getParameters().getFingerprint()); getQueryReturnValue().setReturnValue(serverFingerPrintMap); } catch (AuthenticationException ae) { setErrorMessage(VdcBllMessages.SSH_AUTHENTICATION_FAILED.toString()); } catch (Exception e) { throw new RuntimeException(e); } finally { if (client != null) { client.disconnect(); } } }</code><technical_language>setting this true anyway, if exceptions thrown</technical_language>

Target:
protected void executeQueryCommand() { if (getVdsStaticDao().getByHostName(getParameters().getServerName()) != null || getVdsStaticDao().getAllWithIpAddress(getParameters().getServerName()).size() > 0) { throw new RuntimeException(VdcBllMessages.SERVER_ALREADY_EXISTS_IN_ANOTHER_CLUSTER.toString()); } SSHClient client = null; try { Map<String, String> serverFingerPrintMap = getGlusterUtil().getPeers(getParameters().getServerName(), getParameters().getPassword(), getParameters().getFingerprint()); if (!validateServers(serverFingerPrintMap.keySet())) { throw new RuntimeException(VdcBllMessages.SERVER_ALREADY_EXISTS_IN_ANOTHER_CLUSTER.toString()); } serverFingerPrintMap.put(getParameters().getServerName(), getParameters().getFingerprint()); getQueryReturnValue().setReturnValue(serverFingerPrintMap); } catch (AuthenticationException ae) { throw new RuntimeException(VdcBllMessages.SSH_AUTHENTICATION_FAILED.toString()); } catch (RuntimeException re) { throw re; } catch (Exception e) { throw new RuntimeException(e); } finally { if (client != null) { client.disconnect(); } } }
Source:
<code><START> public Runtime build() { <END> ResourceLoader resourceLoader = this.resourceLoader != null ? this.resourceLoader : new MultiLoader(this.classLoader); ClassFinder classFinder = this.classFinder != null ? this.classFinder : new ResourceLoaderClassFinder(resourceLoader, this.classLoader); BackendSupplier backendSupplier = this.backendSupplier != null ? this.backendSupplier : new BackendModuleBackendSupplier(resourceLoader, classFinder, this.runtimeOptions); final Plugins plugins = new Plugins(this.classLoader, new PluginFactory(), this.eventBus, this.runtimeOptions); for (final Plugin plugin : additionalPlugins) { plugins.addPlugin(plugin); } final RunnerSupplier runnerSupplier = new ThreadLocalRunnerSupplier(this.runtimeOptions, this.eventBus, backendSupplier, this.glueSupplier); final FeatureLoader featureLoader = new FeatureLoader(resourceLoader); final FeatureSupplier featureSupplier = this.featureSupplier != null ? this.featureSupplier : new FeaturePathFeatureSupplier(featureLoader, this.runtimeOptions); final RerunFilters rerunFilters = new RerunFilters(this.runtimeOptions, featureLoader); final Filters filters = new Filters(this.runtimeOptions, rerunFilters); return new Runtime(plugins, this.runtimeOptions, this.eventBus, filters, runnerSupplier, featureSupplier); }</code><technical_language>This is a good idea</technical_language>

Target:
public Runtime build() { final ResourceLoader resourceLoader = this.resourceLoader != null ? this.resourceLoader : new MultiLoader(this.classLoader); final ClassFinder classFinder = this.classFinder != null ? this.classFinder : new ResourceLoaderClassFinder(resourceLoader, this.classLoader); final BackendSupplier backendSupplier = this.backendSupplier != null ? this.backendSupplier : new BackendModuleBackendSupplier(resourceLoader, classFinder, this.runtimeOptions); final Plugins plugins = new Plugins(this.classLoader, new PluginFactory(), this.eventBus, this.runtimeOptions); for (final Plugin plugin : additionalPlugins) { plugins.addPlugin(plugin); } final RunnerSupplier runnerSupplier = runtimeOptions.isMultiThreaded() ? new ThreadLocalRunnerSupplier(this.runtimeOptions, eventBus, backendSupplier, this.glueSupplier) : new SingletonRunnerSupplier(this.runtimeOptions, eventBus, backendSupplier, this.glueSupplier); final ExecutorService executor = runtimeOptions.isMultiThreaded() ? Executors.newFixedThreadPool(runtimeOptions.getThreads()) : new SameThreadExecutorService(); final FeatureLoader featureLoader = new FeatureLoader(resourceLoader); final FeatureSupplier featureSupplier = this.featureSupplier != null ? this.featureSupplier : new FeaturePathFeatureSupplier(featureLoader, this.runtimeOptions); final RerunFilters rerunFilters = new RerunFilters(this.runtimeOptions, featureLoader); final Filters filters = new Filters(this.runtimeOptions, rerunFilters); return new Runtime(plugins, this.runtimeOptions, eventBus, filters, runnerSupplier, featureSupplier, executor); }
Source:
<code>private void callCheckTaintTag(int tagIdx, int primitiveIdx, Type primitiveType) { super.visitFieldInsn(GETSTATIC, Type.getInternalName(Configuration.class), "autoTainter", Type.getDescriptor(TaintSourceWrapper.class)); super.visitVarInsn(ALOAD, tagIdx); super.visitVarInsn(primitiveType.getOpcode(ILOAD), primitiveIdx); <START> boxPrimitive(primitiveType); <END> super.visitLdcInsn(baseSink); super.visitLdcInsn(owner+"."+name+desc); super.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(TaintSourceWrapper.class), "checkTaint", "("+Configuration.TAINT_TAG_DESC+"Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;)V", false); }</code><technical_language>Instead of boxing java.lang.WrapperType, pass primitives a phosphor wrapper? java.lang wrappers introduce a higher overhead risk of taint tag loss, some of classes modified phosphor (e.g. java.lang.character) - in case store taint tag for object in a hash map, is a lot slower. phosphor wrapper type guarantees taint together</technical_language>

Target:
private void callCheckTaintTag(int tagIdx, int primitiveIdx, Type primitiveType) { super.visitFieldInsn(GETSTATIC, Type.getInternalName(Configuration.class), "autoTainter", Type.getDescriptor(TaintSourceWrapper.class)); Type containerType = TaintUtils.getContainerReturnType(primitiveType); mv.visitTypeInsn(NEW, containerType.getInternalName()); mv.visitInsn(DUP); super.visitVarInsn(ALOAD, tagIdx); super.visitVarInsn(primitiveType.getOpcode(ILOAD), primitiveIdx); mv.visitMethodInsn(INVOKESPECIAL, containerType.getInternalName(), "<init>", "("+Configuration.TAINT_TAG_DESC+ primitiveType.getDescriptor()+")V", false); super.visitLdcInsn(baseSink); super.visitLdcInsn(owner+"."+name+desc); super.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(TaintSourceWrapper.class), "checkTaint", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;)V", false); }
Source:
<code>static void updateSubstitutionCodes(final List<CramCompressionRecord> records, final SubstitutionMatrix substitutionMatrix) { for (final CramCompressionRecord record : records) { if (record.readFeatures != null) { for (final ReadFeature recordFeature : record.readFeatures) { if (recordFeature.getOperator() == Substitution.operator) { final Substitution substitution = ((Substitution) recordFeature); <START> if (substitution.getCode() == -1) { <END> final byte refBase = substitution.getReferenceBase(); final byte base = substitution.getBase(); substitution.setCode(substitutionMatrix.code(refBase, base)); } } } } } }</code><technical_language>a symbolic constant here</technical_language>

Target:
static void updateSubstitutionCodes(final List<CramCompressionRecord> records, final SubstitutionMatrix substitutionMatrix) { for (final CramCompressionRecord record : records) { if (record.readFeatures != null) { for (final ReadFeature recordFeature : record.readFeatures) { if (recordFeature.getOperator() == Substitution.operator) { final Substitution substitution = ((Substitution) recordFeature); if (substitution.getCode() == Substitution.NO_CODE) { final byte refBase = substitution.getReferenceBase(); final byte base = substitution.getBase(); substitution.setCode(substitutionMatrix.code(refBase, base)); } } } } } }
Source:
<code>public void create() { ResourceManager.getInstance().init(); AsyncTaskManager.getInstance().InitAsyncTaskManager(); OvfDataUpdater.getInstance().initOvfDataUpdater(); <START> VdsLoadBalancer.getInstance().setMigrationHandler(new MigrationHandler() { <END> @Override public void migrateVMs(List<Pair<Guid, Guid>> list) { for (Pair<Guid, Guid> pair : list) { MigrateVmToServerParameters parameters = new MigrateVmToServerParameters(false, pair.getFirst(), pair.getSecond()); Backend.getInstance().runInternalAction(VdcActionType.MigrateVmToServer, parameters, ExecutionHandler.createInternalJobContext()); } } }); ThreadPoolUtil.execute(new Runnable() { @Override public void run() { MacPoolManager.getInstance().initialize(); } }); StoragePoolStatusHandler.Init(); GlusterJobsManager.init(); try { log.info("Init VM custom properties utilities"); VmPropertiesUtils.getInstance().init(); } catch (InitializationException e) { log.error("Initialization of vm custom properties failed.",e); } }</code><technical_language>more implementation of MigrationHandler interface</technical_language>

Target:
public void create() { ResourceManager.getInstance().init(); AsyncTaskManager.getInstance().InitAsyncTaskManager(); OvfDataUpdater.getInstance().initOvfDataUpdater(); VdsLoadBalancer.getInstance().setMigrationHandler(new MigrationHandler() { @Override public void migrateVMs(List<Pair<Guid, Guid>> list) { for (Pair<Guid, Guid> pair : list) { MigrateVmToServerParameters parameters = new MigrateVmToServerParameters(false, pair.getFirst(), pair.getSecond()); Backend.getInstance().runInternalAction(VdcActionType.MigrateVmToServer, parameters, ExecutionHandler.createInternalJobContext()); } } }); ThreadPoolUtil.execute(new Runnable() { @Override public void run() { MacPoolManager.getInstance().initialize(); } }); StoragePoolStatusHandler.Init(); GlusterJobsManager.init(); try { log.info("Init VM custom properties utilities"); VmPropertiesUtils.getInstance().init(); } catch (InitializationException e) { log.error("Initialization of vm custom properties failed.",e); } try { log.info("Init device custom properties utilities"); DevicePropertiesUtils.getInstance().init(); } catch (InitializationException e) { log.error("Initialization of device custom properties failed.",e); } }
Source:
<code>public void refresh() { boolean releaseLock = true; if (lockManager.acquireLock(monitoringLock).getFirst()) { try { setIsSetNonOperationalExecuted(false); synchronized (this) { refreshCachedVds(); if (cachedVds == null) { log.error("VdsManager::refreshVdsRunTimeInfo - refresh is NULL for '{}'", getVdsId()); return; } try { updateIteration(); if (isMonitoringNeeded()) { setStartTime(); releaseLock = false; hostMonitoring = Injector.injectMembers( new HostMonitoring(this, cachedVds, monitoringStrategy)); hostMonitoring.refresh(); unrespondedAttempts.set(0); setLastUpdate(); } } catch (VDSNetworkException e) { logNetworkException(e); } catch (VDSRecoveringException ex) { handleVdsRecoveringException(ex); } catch (RuntimeException ex) { logFailureMessage(ex); } } } catch (Throwable t) { releaseLock = true; log.error("Timer update runtime info failed. Exception:", ExceptionUtils.getRootCauseMessage(t)); log.debug("Exception:", t); } finally { if (releaseLock) { <START> lockManager.releaseLock(monitoringLock); <END> } } } }</code><technical_language>Tracking flows in lock is acquired exiting this method is pretty complex. Eventually return VdsManager.afterRefreshTreatment() in order release lock, happen a result of flows. In cases is a callback passes a callback responsible release monitoring lock. This is done passing VdsManager callbacks chain. clear 'flow' figure out is action performed in system. I hard maintain, in case of a bug, back-track entire sequence figure out exact flow triggered steps. callbacks executed in threads, more complexity is added flow. Passing VdsManager ResourceManager flows allowing influence state of host monitoring result decrease maintainability of code: callbacks responsible for calling postRefresh(), while other don't. leads ambiguity of callback is responsible terminate flow callback controls it. In case, a callback receive callback implementation (depending flow). prefer a separation of flows/monitoring actions. existing implementation more actions callbacks async engine <--> vdsm interaction. async interaction is done, return response main flow instead of letting callback flow point</technical_language>

Target:
public void refresh() { boolean releaseLock = true; if (lockManager.acquireLock(monitoringLock).getFirst()) { try { setIsSetNonOperationalExecuted(false); synchronized (this) { refreshCachedVds(); if (cachedVds == null) { log.error("VdsManager::refreshVdsRunTimeInfo - onTimer is NULL for '{}'", getVdsId()); return; } try { updateIteration(); if (isMonitoringNeeded()) { setStartTime(); releaseLock = false; hostMonitoring = new HostMonitoring(this, cachedVds, monitoringStrategy, resourceManager, dbFacade, auditLogDirector); hostMonitoring.refresh(); } } catch (VDSNetworkException e) { logNetworkException(e); } catch (VDSRecoveringException ex) { handleVdsRecoveringException(ex); } catch (RuntimeException ex) { logFailureMessage(ex); } } } catch (Throwable e) { releaseLock = true; log.error("Timer update runtime info failed. Exception:", ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception:", e); } finally { if (releaseLock) { lockManager.releaseLock(monitoringLock); } } } }
Source:
<code>public ProcessLocation createProcessLocation(String processId) throws IOException { File processRootDirectory = new File( (Config.getConfig().getString(METADATA_DIRECTORY) + File.separator + processId)); if (!processRootDirectory.mkdir()) { <START> throw new IOException(); <END> } File processImageDirectory = new File(processRootDirectory.getPath() + File.separator + "images"); if (!processImageDirectory.mkdir()) { throw new IOException(); } URI processMetaFile = createResource(processRootDirectory.toURI(), "meta.xml"); return new ProcessLocation(processRootDirectory.toURI(), processImageDirectory.toURI(), processMetaFile); }</code><technical_language>Throwing exception a message is a good idea or</technical_language>

Target:
public ProcessLocation createProcessLocation(String processId) throws IOException { File processRootDirectory = new File( (Config.getConfig().getString(METADATA_DIRECTORY) + File.separator + processId)); if (!processRootDirectory.mkdir()) { throw new IOException("Could not create processRoot directory."); } File processImageDirectory = new File(processRootDirectory.getPath() + File.separator + "images"); if (!processImageDirectory.mkdir()) { throw new IOException("Could not create image directory"); } URI processMetaFile = createResource(processRootDirectory.toURI(), "meta.xml"); return new ProcessLocation(processRootDirectory.toURI(), processImageDirectory.toURI(), processMetaFile); }
Source:
<code>public void accept(final Socket socket) throws IOException { final InputStream input = socket.getInputStream(); final RqLive req = new RqLive(input); boolean keep = false; final Iterator<String> values = new RqHeaders.Base(req) <START> .header(CONNECTION).iterator(); <END> if (values.hasNext()) { do { keep = KEEP_ALIVE.equals(values.next()); } while (!keep && values.hasNext()); } try { this.print( BkBasic.addSocketHeaders( req, socket ), new BufferedOutputStream(socket.getOutputStream()), keep ); } finally { if (!keep) { input.close(); } } }</code><technical_language>@lautarobock BkBasic.CONNECTION</technical_language>

Target:
public void accept(final Socket socket) throws IOException { final InputStream input = socket.getInputStream(); try { this.print( BkBasic.addSocketHeaders( new RqLive(input), socket ), new BufferedOutputStream(socket.getOutputStream()) ); } finally { input.close(); } }
Source:
<code>private void test(String[] original, String[] compiled, DiagnosticType warning) { Compiler compiler = compile(original); assertThat(exitCodes).isNotEmpty(); <START> assertThat(exitCodes.get(exitCodes.size() - 1)).isEqualTo(0); <END> if (warning == null) { assertEquals("Expected no warnings or errors\n" + "Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) + "Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()), 0, compiler.getErrors().length + compiler.getWarnings().length); } else { assertThat(compiler.getWarnings()).hasLength(1); assertThat(compiler.getWarnings()[0].getType()).isEqualTo(warning); } Node root = compiler.getRoot().getLastChild(); if (useStringComparison) { assertThat(compiler.toSource()).isEqualTo(Joiner.on("").join(compiled)); } else { Node expectedRoot = parse(compiled); String explanation = expectedRoot.checkTreeEquals(root); assertNull("\nExpected: " + compiler.toSource(expectedRoot) + "\nResult: " + compiler.toSource(root) + "\n" + explanation, explanation); } }</code><technical_language>I exitCodes length 1 write assertThat(exitCodes).containsExactly(0) (if remembering Truth methods right) I totally wrong</technical_language>

Target:
private void test(String[] original, String[] compiled, DiagnosticType warning) { exitCodes.clear(); Compiler compiler = compile(original); assertThat(exitCodes).containsExactly(0); if (warning == null) { assertEquals("Expected no warnings or errors\n" + "Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) + "Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()), 0, compiler.getErrors().length + compiler.getWarnings().length); } else { assertThat(compiler.getWarnings()).hasLength(1); assertThat(compiler.getWarnings()[0].getType()).isEqualTo(warning); } Node root = compiler.getRoot().getLastChild(); if (useStringComparison) { assertThat(compiler.toSource()).isEqualTo(Joiner.on("").join(compiled)); } else { Node expectedRoot = parse(compiled); String explanation = expectedRoot.checkTreeEquals(root); assertNull("\nExpected: " + compiler.toSource(expectedRoot) + "\nResult: " + compiler.toSource(root) + "\n" + explanation, explanation); } }