auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static void expandJar(File fileToExpand, File tmpModuleDir, String name, boolean keepFullPath) throws IOException { JarFile jarFile = null; InputStream input = null; String docBase = tmpModuleDir.getAbsolutePath(); try { jarFile = new JarFile(fileToExpand); Enumeration<JarEntry> jarEntries = jarFile.entries(); boolean foundName = (name == null); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); if (name == null || jarEntry.getName().startsWith(name)) { String entryName = jarEntry.getName(); if (!keepFullPath && name != null) { if (name.equals(entryName)) { <START> int lastSlash = name.lastIndexOf('/'); <END> if (lastSlash >= 0) { entryName = entryName.replaceFirst(name.substring(0, lastSlash + 1), ""); } } else { entryName = entryName.replaceFirst(name, ""); } } int last = entryName.lastIndexOf('/'); if (last >= 0) { File parent = new File(docBase, entryName.substring(0, last)); parent.mkdirs(); log.debug("Creating parent dirs: " + parent.getAbsolutePath()); } if (entryName.endsWith("/") || "".equals(entryName)) { continue; } input = jarFile.getInputStream(jarEntry); expand(input, docBase, entryName); input.close(); input = null; foundName = true; } } if (!foundName) { log.debug("Unable to find: " + name + " in file " + fileToExpand.getAbsolutePath()); } } catch (IOException e) { log.warn("Unable to delete tmpModuleFile on error", e); throw e; } finally { try { input.close(); } catch (Exception e) { } try { jarFile.close(); } catch (Exception e) { } } }</code><technical_language>File.separator in tests hard code separator here, why</technical_language>

Target:
public static void expandJar(File fileToExpand, File tmpModuleDir, String name, boolean keepFullPath) throws IOException { JarFile jarFile = null; InputStream input = null; String docBase = tmpModuleDir.getAbsolutePath(); try { jarFile = new JarFile(fileToExpand); Enumeration<JarEntry> jarEntries = jarFile.entries(); boolean foundName = (name == null); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); if (name == null || jarEntry.getName().startsWith(name)) { String entryName = jarEntry.getName(); if (!keepFullPath && name != null) { entryName = entryName.replaceFirst(name, ""); } int last = entryName.lastIndexOf('/'); if (last >= 0) { File parent = new File(docBase, entryName.substring(0, last)); parent.mkdirs(); log.debug("Creating parent dirs: " + parent.getAbsolutePath()); } if (entryName.endsWith("/") || "".equals(entryName)) { continue; } input = jarFile.getInputStream(jarEntry); expand(input, docBase, entryName); input.close(); input = null; foundName = true; } } if (!foundName) { log.debug("Unable to find: " + name + " in file " + fileToExpand.getAbsolutePath()); } } catch (IOException e) { log.warn("Unable to delete tmpModuleFile on error", e); throw e; } finally { try { input.close(); } catch (Exception e) { } try { jarFile.close(); } catch (Exception e) { } } }
Source:
<code>public void testCompareSecondNull() throws Exception { <START> when(dso2.getName()).thenReturn("b"); <END> assertTrue(comparator.compare(dso1, null) > 0); }</code><technical_language>"dso1"? dso2 is in this test</technical_language>

Target:
public void testCompareSecondNull() throws Exception { when(dso1.getName()).thenReturn("a"); assertTrue(comparator.compare(dso1, null) > 0); }
Source:
<code>public void putWorker(MesosWorkerStore.Worker worker) throws Exception { checkNotNull(worker, "worker"); String path = getPathForWorker(worker.taskID()); synchronized (startStopLock) { verifyIsRunning(); final IntegerResourceVersion currentVersion = workersInZooKeeper.exists(path); <START> if (currentVersion.isNotExist()) { <END> workersInZooKeeper.add(path, worker); LOG.debug("Added in ZooKeeper.", worker); } else { workersInZooKeeper.replace(path, currentVersion, worker); LOG.debug("Updated in ZooKeeper.", worker); } } }</code><technical_language>doesNotExist, exists isExisting a bit</technical_language>

Target:
public void putWorker(MesosWorkerStore.Worker worker) throws Exception { checkNotNull(worker, "worker"); String path = getPathForWorker(worker.taskID()); synchronized (startStopLock) { verifyIsRunning(); final IntegerResourceVersion currentVersion = workersInZooKeeper.exists(path); if (!currentVersion.isExisting()) { workersInZooKeeper.addAndLock(path, worker); LOG.debug("Added in ZooKeeper.", worker); } else { workersInZooKeeper.replace(path, currentVersion, worker); LOG.debug("Updated in ZooKeeper.", worker); } } }
Source:
<code>public void logAddClick(AddToReadingListDialog.InvokeSource source) { log( "action", "addclick", <START> "addsource", source.ordinal() <END> ); }</code><technical_language>I recommend avoiding Enum.ordinal dependencies for more permanent marshalling event logging. easy reorder enum members refactoring expect functional difference. Unfortunately, Enum.ordinal implicitly creates a dependency order of declaration. example of avoiding this dependency keeping code flexible in org.wikipedia.page.Namespace. slightly more verbose in enum implement EnumCode of boilerplate extracted EnumCodeMap marshalling requirements explicit. A case casual Gson usage similar problems please consider this optional</technical_language>

Target:
public void logAddClick(AddToReadingListDialog.InvokeSource source) { log( "action", "addclick", "addsource", source.code() ); }
Source:
<code>private void visitPartitionedDirectory(FileSystem fs, Path stagingPath, Path outputPath, String stagingParentPathString, Map<Path, Path> renameDirs, Path oldTableDir) throws IOException { FileStatus[] files = fs.listStatus(stagingPath); for(FileStatus eachFile : files) { if (eachFile.isDirectory()) { Path oldPath = eachFile.getPath(); String recoverPathString = oldPath.toString().replaceAll(stagingParentPathString, oldTableDir.toString()); Path recoveryPath = new Path(recoverPathString); if (!fs.exists(recoveryPath)) { fs.mkdirs(recoveryPath); } visitPartitionedDirectory(fs, eachFile.getPath(), outputPath, stagingParentPathString, renameDirs, oldTableDir); String newPathString = oldPath.toString().replaceAll(stagingParentPathString, outputPath.toString()); Path newPath = new Path(newPathString); <START> if (!hasDirectory(fs, eachFile.getPath())) { <END> renameDirs.put(eachFile.getPath(), newPath); } else { if (!fs.exists(newPath)) { fs.mkdirs(newPath); } } } } }</code><technical_language>In view, isLeafDirectory() more intuitive name !hasDirectory()</technical_language>

Target:
private void visitPartitionedDirectory(FileSystem fs, Path stagingPath, Path outputPath, String stagingParentPathString, Map<Path, Path> renameDirs, Path oldTableDir) throws IOException { FileStatus[] files = fs.listStatus(stagingPath); for(FileStatus eachFile : files) { if (eachFile.isDirectory()) { Path oldPath = eachFile.getPath(); String recoverPathString = oldPath.toString().replaceAll(stagingParentPathString, oldTableDir.toString()); Path recoveryPath = new Path(recoverPathString); if (!fs.exists(recoveryPath)) { fs.mkdirs(recoveryPath); } visitPartitionedDirectory(fs, eachFile.getPath(), outputPath, stagingParentPathString, renameDirs, oldTableDir); String newPathString = oldPath.toString().replaceAll(stagingParentPathString, outputPath.toString()); Path newPath = new Path(newPathString); if (!isLeafDirectory(fs, eachFile.getPath())) { renameDirs.put(eachFile.getPath(), newPath); } else { if (!fs.exists(newPath)) { fs.mkdirs(newPath); } } } } }
Source:
<code>public HighlightingInlineHyperlink(final String text, final String token, final String toHighlight) { super(text, token); <START> highlight(text, toHighlight); <END> }</code><technical_language>highlight called setText instead? way, if text is changed construction get highlighted too</technical_language>

Target:
public HighlightingInlineHyperlink(final String text, final String token, final String toHighlight) { super(text, token); this.toHighlight = toHighlight; highlight(text, toHighlight); }
Source:
<code>public boolean checkIfNetworkLinksDeployed(String resourceGroupName, String networkId, List<AzurePrivateDnsZoneServiceEnum> services) { LOGGER.debug("Checking Network link between network and services and network link {}", networkId, services.stream() .map(AzurePrivateDnsZoneServiceEnum::getDnsZoneName) .collect(Collectors.toList())); for (AzurePrivateDnsZoneServiceEnum service : services) { String dnsZoneName = service.getDnsZoneName(); PagedList<VirtualNetworkLinkInner> virtualNetworkLinks = listNetworkLinksByPrivateDnsZoneName(resourceGroupName, dnsZoneName); <START> if (virtualNetworkLinks.size() > 0) { <END> if (!isNetworkLinkCreated(networkId, virtualNetworkLinks)) { LOGGER.info("Network link for network and DNS Zone is not provisioned successfully yet!", networkId, dnsZoneName); return false; } } else { LOGGER.info("Network link for network not found for DNS zone {}!", networkId, dnsZoneName); return false; } } return true; }</code><technical_language>isEmpty please, like: if (virtualNetworkLinks.isEmpty()) { LOGGER.info("Network link for network for DNS zone {}!", networkId, dnsZoneName); return false; } else if (!isNetworkLinkCreated(networkId, virtualNetworkLinks)) { LOGGER.info("Network link for network DNS Zone is provisioned successfully yet!", networkId, dnsZoneName); return false; }</technical_language>

Target:
public boolean checkIfNetworkLinksDeployed(String resourceGroupName, String networkId, List<AzurePrivateDnsZoneServiceEnum> services) { LOGGER.debug("Checking Network link between network and services and network link {}", networkId, services.stream() .map(AzurePrivateDnsZoneServiceEnum::getDnsZoneName) .collect(Collectors.toList())); for (AzurePrivateDnsZoneServiceEnum service : services) { String dnsZoneName = service.getDnsZoneName(); PagedList<VirtualNetworkLinkInner> virtualNetworkLinks = listNetworkLinksByPrivateDnsZoneName(resourceGroupName, dnsZoneName); if (virtualNetworkLinks.isEmpty()) { LOGGER.info("Network link for network not found for DNS zone {}!", networkId, dnsZoneName); return false; } else if (!isNetworkLinkCreated(networkId, virtualNetworkLinks)) { LOGGER.info("Network link for network and DNS Zone is not provisioned successfully yet!", networkId, dnsZoneName); return false; } } return true; }
Source:
<code>public AbnormalStatesMetricCollector(String clusterName, String stateModelDef) { super(MonitorDomainNames.Rebalancer.name(), clusterName, String.format("%s.%s", ABNORMAL_STATES_ENTITY_NAME, stateModelDef)); createMetrics(); if (clusterName != null) { try { register(); } catch (JMException e) { <START> throw new HelixException("Failed to register MBean for the AbnormalStatesMetricCollector", <END> e); } } }</code><technical_language>Hardcoded AbnormalStatesMetricCollector -> AbnormalStatesMetricCollector.class.getSimpleName()? Benefit is refactoring class name miss this</technical_language>

Target:
public AbnormalStatesMetricCollector(String clusterName, String stateModelDef) { super(MonitorDomainNames.Rebalancer.name(), clusterName, String.format("%s.%s", ABNORMAL_STATES_ENTITY_NAME, stateModelDef)); createMetrics(); if (clusterName != null) { try { register(); } catch (JMException e) { throw new HelixException( "Failed to register MBean for the " + AbnormalStatesMetricCollector.class .getSimpleName(), e); } } }
Source:
<code>public void run() { FindTarget findTarget = fFindTarget; if (findTarget == null) { return; } checkShell(findTarget); if (fDialog == null) { fDialog = new TimeGraphFindDialog(findTarget.getShell()); } if (fDialog != null) { fDialog.update(findTarget); fDialog.open(); <START> fDialog.getShell().setMinimumSize(SHELL_MINIMUM_SIZE, SHELL_MINIMUM_SIZE); <END> } }</code><technical_language>This belong in TimeGraphFindDialog.create(), a Shell is visible. Also, minimumSize set result of computeTrim() pass values. I intermittently get a minimum height is small height of trim, this reason</technical_language>

Target:
public void run() { FindTarget findTarget = fFindTarget; if (findTarget == null) { return; } checkShell(findTarget); if (fDialog == null) { fDialog = new TimeGraphFindDialog(findTarget.getShell()); } if (fDialog != null) { fDialog.update(findTarget); fDialog.open(); } }
Source:
<code>private IVariable getVariableFor(TextSelection selection) { IDocument document = getDocument(selection); if (document == null) { return null; } DSPStackFrame frame = getFrame(); if (frame == null) { return null; } try { String variableName = document.get(selection.getOffset(), selection.getLength()); if (variableName.isEmpty()) { variableName = findVariableName(document, selection.getOffset()); } if (Boolean.TRUE.equals(frame.getDebugTarget().getCapabilities().getSupportsEvaluateForHovers())) { <START> EvaluateArguments args = new EvaluateArguments(); <END> args.setContext("hover"); args.setExpression(variableName); try { EvaluateResponse res = frame.getDebugProtocolServer().evaluate(args).get(); return new DSPVariable(getFrame(), res.getVariablesReference(), variableName, res.getResult()); } catch (InterruptedException | ExecutionException e) { DSPPlugin.logError(e); } } else { try { for (IVariable scopeVariable : frame.getVariables()) { IValue scope = scopeVariable.getValue(); if (scope != null) { IVariable[] vars = scope.getVariables(); for (IVariable var : vars) { if (var.getName().equals(variableName)) { return var; } } } } } catch (DebugException de) { return null; } } } catch (BadLocationException e) { return null; } return null; }</code><technical_language>Add args.setFrameId(frame.stackFrame.getId()) evaluate in selected debug context. match context handling do in non-capable case</technical_language>

Target:
private IVariable getVariableFor(TextSelection selection) { IDocument document = getDocument(selection); if (document == null) { return null; } DSPStackFrame frame = getFrame(); if (frame == null) { return null; } try { String variableName = document.get(selection.getOffset(), selection.getLength()); if (variableName.isEmpty()) { variableName = findVariableName(document, selection.getOffset()); } if (Boolean.TRUE.equals(frame.getDebugTarget().getCapabilities().getSupportsEvaluateForHovers())) { EvaluateArguments args = new EvaluateArguments(); args.setContext(EvaluateArgumentsContext.HOVER); args.setFrameId(frame.getFrameId()); args.setExpression(variableName); try { EvaluateResponse res = frame.getDebugProtocolServer().evaluate(args).get(); return new DSPVariable(getFrame(), res.getVariablesReference(), variableName, res.getResult()); } catch (InterruptedException | ExecutionException e) { DSPPlugin.logError(e); } } else { try { for (IVariable scopeVariable : frame.getVariables()) { IValue scope = scopeVariable.getValue(); if (scope != null) { IVariable[] vars = scope.getVariables(); for (IVariable var : vars) { if (var.getName().equals(variableName)) { return var; } } } } } catch (DebugException de) { return null; } } } catch (BadLocationException e) { return null; } return null; }
Source:
<code>public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.STRING_LITERAL, ctx -> { PyStringLiteralTree stringLiteral = ((PyStringLiteralTree) ctx.syntaxNode()); if (isMultilineString(stringLiteral)) { return; <START> } else { <END> String content = stringLiteral.stringElements().get(0).trimmedQuotesValue(); Matcher matcher = IPV4_URL_REGEX.matcher(content); if (matcher.matches()) { String ip = matcher.group("ipv4"); if (isValidIPV4(ip) && !isIPV4Exception(ip)) { ctx.addIssue(stringLiteral, String.format(message, ip)); } } else { IPV6_REGEX_LIST.stream() .map(pattern -> pattern.matcher(content)) .filter(Matcher::matches) .findFirst() .map(match -> { String ipv6 = match.group("ipv6"); String ipv4 = match.group("ipv4"); return isValidIPV6(ipv6, ipv4) && !isIPV6Exception(ipv6) ? ipv6 : null; }) .ifPresent(ipv6 -> ctx.addIssue(stringLiteral, String.format(message, ipv6))); } } }); }</code><technical_language>need for else return</technical_language>

Target:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.STRING_LITERAL, ctx -> { PyStringLiteralTree stringLiteral = (PyStringLiteralTree) ctx.syntaxNode(); if (isMultilineString(stringLiteral)) { return; } String content = stringLiteral.stringElements().get(0).trimmedQuotesValue(); Matcher matcher = IPV4_URL_REGEX.matcher(content); if (matcher.matches()) { String ip = matcher.group("ipv4"); if (isValidIPV4(ip) && !isIPV4Exception(ip)) { ctx.addIssue(stringLiteral, String.format(message, ip)); } } else { IPV6_REGEX_LIST.stream() .map(pattern -> pattern.matcher(content)) .filter(Matcher::matches) .findFirst() .map(match -> { String ipv6 = match.group("ipv6"); String ipv4 = match.group("ipv4"); return isValidIPV6(ipv6, ipv4) && !isIPV6Exception(ipv6) ? ipv6 : null; }) .ifPresent(ipv6 -> ctx.addIssue(stringLiteral, String.format(message, ipv6))); } }); }
Source:
<code>protected ClientConfiguration getClientConfiguration(PluginTask task) { ClientConfiguration clientConfig = new ClientConfiguration(); <START> clientConfig.withRetryPolicy(PredefinedRetryPolicies.NO_RETRY_POLICY); <END> if (task.getHttpProxy().isPresent()) { setHttpProxyInAwsClient(clientConfig, task.getHttpProxy().get()); } return clientConfig; }</code><technical_language>Please test this setting retry policy expected effect, accidentally overridden somewhere, tests yield unexpected result here. Also, I prefer setRetryPolicy withRetryPolicy. with... is kind of ambiguous chaining calls, immutable method</technical_language>

Target:
protected ClientConfiguration getClientConfiguration(PluginTask task) { ClientConfiguration clientConfig = new ClientConfiguration(); clientConfig.setRetryPolicy(PredefinedRetryPolicies.NO_RETRY_POLICY); if (task.getHttpProxy().isPresent()) { setHttpProxyInAwsClient(clientConfig, task.getHttpProxy().get()); } return clientConfig; }
Source:
<code>public void run() { if (!shouldRunPrewarm) { if (canUseEvents) { try { <START> lastEventId = updateUsingNotificationEvents(rawStore, lastEventId); <END> } catch (Exception e) { LOG.error("failed to update cache using events ", e); } } else { update(); } } else { try { lastEventId = rawStore.getCurrentNotificationEventId().getEventId(); prewarm(rawStore); } catch (Exception e) { LOG.error("Prewarm failure", e); return; } } }</code><technical_language>this more frequent update(). set CACHED_RAW_STORE_CACHE_UPDATE_FREQUENCY 0</technical_language>

Target:
public void run() { if (!shouldRunPrewarm) { if (canUseEvents) { try { triggerUpdateUsingEvent(rawStore); } catch (Exception e) { LOG.error("failed to update cache using events ", e); } } else { update(); } } else { try { triggerPreWarm(rawStore); } catch (Exception e) { LOG.error("Prewarm failure", e); return; } } }
Source:
<code><START> public String toString() { <END> return "IdInTenant{" + "id=" + Stringifiers.toString(id) + ", tenantId=" + tenantId + '}'; }</code><technical_language>Please ToStringHelper in this case in similar cases in change set</technical_language>

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("id", id) .add("tenantId", tenantId) .toString(); }
Source:
<code>public void enableImportProject() { final MenuResourceHandlerWidget menuResourceHandlerWidget = menuResourceHandlerWidgets.get(); <START> menuResourceHandlerWidget.init(this.translationService.getTranslation("ImportProject"), <END> () -> libraryPlaces.goToImportRepositoryPopUp()); view.addNewMenuItem(menuResourceHandlerWidget); }</code><technical_language>extract "ImportProject" string a constant in LibraryConstants.java</technical_language>

Target:
public void enableImportProject() { final MenuResourceHandlerWidget menuResourceHandlerWidget = menuResourceHandlerWidgets.get(); menuResourceHandlerWidget.init(this.translationService.getTranslation(LibraryConstants.ImportProject), () -> libraryPlaces.goToImportRepositoryPopUp()); view.addNewMenuItem(menuResourceHandlerWidget); }
Source:
<code><START> protected Object getEntityObject(S object) { <END> return null; }</code><technical_language>return type S, avoid casting this method is called</technical_language>

Target:
protected S getEntityObject(S object) { return null; }
Source:
<code>public void write(Path parentPath) throws IOException { Path sdPath = parentPath.resolve(SNAPSHOT_DIRECTORY); if (!sdPath.toFile().exists()) { Files.createDirectory(sdPath); } String fileName = fSsid + FILE_SUFFIX; Path filePath = sdPath.resolve(fileName); if (filePath.toFile().exists()) { Files.delete(filePath); } Files.createFile(filePath); TmfIntervalSerializer serializer = new TmfIntervalSerializer(); GsonBuilder gb = new GsonBuilder(); gb.registerTypeAdapter(ITmfStateInterval.class, serializer); gb.setPrettyPrinting(); Gson <START> root = gb.create(); <END> try (Writer bw = Files.newBufferedWriter(filePath, Charsets.UTF_8)) { String json = root.toJson(this); bw.write(json); } }</code><technical_language>static Gsonbuilder</technical_language>

Target:
public void write(Path parentPath) throws IOException { Path sdPath = parentPath.resolve(SNAPSHOT_DIRECTORY); if (!sdPath.toFile().exists()) { Files.createDirectory(sdPath); } String fileName = fSsid + FILE_SUFFIX; Path filePath = sdPath.resolve(fileName); if (filePath.toFile().exists()) { Files.delete(filePath); } Files.createFile(filePath); try (Writer bw = Files.newBufferedWriter(filePath, Charsets.UTF_8)) { String json = GSON.toJson(this); bw.write(json); } }
Source:
<code>protected abstract DatastreamProducerRecord translate(ConsumerRecord<?, ?> fromKafka, Instant readTime) throws Exception; protected void translateAndSendBatch(ConsumerRecords<?, ?> records, Instant readTime) throws Exception { boolean shouldAddPausePartitionsTask = false; for (TopicPartition topicPartition : records.partitions()) { for (ConsumerRecord<?, ?> record : records.records(topicPartition)) { try { sendMessage(record, readTime); } catch (RuntimeException e) { _consumerMetrics.updateErrorRate(1); seekToLastCheckpoint(Collections.singleton(topicPartition)); if (_pausePartitionOnError) { _logger.warn("Got exception while sending record {}, adding topic partition to auto-pause set", record, topicPartition); Instant start = Instant.now(); <START> _autoPausedSourcePartitions.put(topicPartition, new PausedSourcePartitionMetadata(topicPartition, <END> () -> Duration.between(start, Instant.now()).compareTo(_pauseErrorPartitionDuration) > 0, PausedSourcePartitionMetadata.Reason.SEND_ERROR)); shouldAddPausePartitionsTask = true; } break; } } } if (shouldAddPausePartitionsTask) { _taskUpdates.add(DatastreamConstants.UpdateType.PAUSE_RESUME_PARTITIONS); } }</code><technical_language>I suggest create a static method in PausedSourcePartitionMetadata for creating a Metdata Record for send error. for creating a metadata record for Threshold Limit exceeded. reason is easier reuse condition in multiple places, logic located in a single file</technical_language>

Target:
protected abstract DatastreamProducerRecord translate(ConsumerRecord<?, ?> fromKafka, Instant readTime) throws Exception; protected void translateAndSendBatch(ConsumerRecords<?, ?> records, Instant readTime) throws Exception { boolean shouldAddPausePartitionsTask = false; for (TopicPartition topicPartition : records.partitions()) { for (ConsumerRecord<?, ?> record : records.records(topicPartition)) { try { sendMessage(record, readTime); } catch (RuntimeException e) { _consumerMetrics.updateErrorRate(1); seekToLastCheckpoint(Collections.singleton(topicPartition)); if (_pausePartitionOnError) { _logger.warn("Got exception while sending record {}, adding topic partition to auto-pause set", record, topicPartition); Instant start = Instant.now(); _autoPausedSourcePartitions.put(topicPartition, PausedSourcePartitionMetadata.sendError(start, _pauseErrorPartitionDuration)); shouldAddPausePartitionsTask = true; } break; } } } if (shouldAddPausePartitionsTask) { _taskUpdates.add(DatastreamConstants.UpdateType.PAUSE_RESUME_PARTITIONS); } }
Source:
<code>private BlockingChannel getBlockingChannelBasedOnPortType(String host, int port) { BlockingChannel channel = null; if (this.port.getPortType() == PortType.PLAINTEXT) { channel = new BlockingChannel(host, port, config.connectionPoolReadBufferSizeBytes, config.connectionPoolWriteBufferSizeBytes, config.connectionPoolReadTimeoutMs, config.connectionPoolConnectTimeoutMs, config.connectionPoolSocketTcpNoDelay); } else if (this.port.getPortType() == PortType.SSL) { channel = new SSLBlockingChannel(host, port, registry, config.connectionPoolReadBufferSizeBytes, config.connectionPoolWriteBufferSizeBytes, config.connectionPoolReadTimeoutMs, <START> config.connectionPoolConnectTimeoutMs, config.connectionPoolSocketTcpNoDelay, sslSocketFactory, sslConfig); <END> } return channel; }</code><technical_language>I if worthwhile pass config BlockingChannel SSLBlockingChannel constructor. Thus, configure parameters constructor function signature simpler</technical_language>

Target:
private BlockingChannel getBlockingChannelBasedOnPortType(String host, int port) { BlockingChannel channel = null; if (this.port.getPortType() == PortType.PLAINTEXT) { channel = new BlockingChannel(host, port, config); } else if (this.port.getPortType() == PortType.SSL) { channel = new SSLBlockingChannel(host, port, registry, config, sslSocketFactory, sslConfig); } return channel; }
Source:
<code>private String computeMd5DigestOfPlugins() { try { String digestOfBundledFolder = md5DigestOfFolderContent(bundledPlugins); String digestOfExternalFolder = md5DigestOfFolderContent(externalPlugins); String digestOfPlugins = digestOfBundledFolder + digestOfExternalFolder; return DigestUtils.md5Hex(digestOfPlugins); } catch (Exception e) { throw new RuntimeException(String.format("Could not compute md5 of plugins." + <START> " Exception occurred: %s", e.getStackTrace())); <END> } }</code><technical_language>replace string in String.format() line</technical_language>

Target:
private String computeMd5DigestOfPlugins() { try { String digestOfBundledFolder = md5DigestOfFolderContent(bundledPlugins); String digestOfExternalFolder = md5DigestOfFolderContent(externalPlugins); String digestOfPlugins = digestOfBundledFolder + digestOfExternalFolder; return DigestUtils.md5Hex(digestOfPlugins); } catch (Exception e) { throw new RuntimeException(String.format("Could not compute md5 of plugins. Exception occurred: %s", e.getStackTrace())); } }
Source:
<code>public DatasetSourceTarget(View<E> view, Class<E> type) { super(view.getDataset()); this.dataset = view; this.formatBundle = FormatBundle.forInput(DatasetKeyInputFormat.class); formatBundle.set(DatasetKeyInputFormat.KITE_REPOSITORY_URI, getRepositoryUri(view.getDataset())); formatBundle.set(DatasetKeyInputFormat.KITE_DATASET_NAME, view.getDataset().getName()); Configuration conf = new Configuration(); DatasetKeyInputFormat.setView(conf, view); formatBundle.set(DatasetKeyInputFormat.KITE_CONSTRAINTS, conf.get(DatasetKeyInputFormat.KITE_CONSTRAINTS)); <START> formatBundle.set(RuntimeParameters.DISABLE_COMBINE_FILE, "true"); <END> if (type.isAssignableFrom(GenericData.Record.class)) { this.avroType = (AvroType<E>) Avros.generics(dataset.getDataset().getDescriptor().getSchema()); } else { this.avroType = Avros.records(type); } }</code><technical_language>Need find a this, in this commit</technical_language>

Target:
public DatasetSourceTarget(View<E> view, Class<E> type) { super(view.getDataset()); this.view = view; this.formatBundle = FormatBundle.forInput(DatasetKeyInputFormat.class); formatBundle.set(DatasetKeyInputFormat.KITE_REPOSITORY_URI, getRepositoryUri(view.getDataset())); formatBundle.set(DatasetKeyInputFormat.KITE_DATASET_NAME, view.getDataset().getName()); Configuration conf = new Configuration(); DatasetKeyInputFormat.setView(conf, view); formatBundle.set(DatasetKeyInputFormat.KITE_CONSTRAINTS, conf.get(DatasetKeyInputFormat.KITE_CONSTRAINTS)); formatBundle.set(RuntimeParameters.DISABLE_COMBINE_FILE, "true"); if (type.isAssignableFrom(GenericData.Record.class)) { this.avroType = (AvroType<E>) Avros.generics(this.view.getDataset().getDescriptor() .getSchema()); } else { this.avroType = Avros.records(type); } }
Source:
<code>protected Handlers newHandlers(Handler[] handlers) { _singleContext = null; if (handlers == null || handlers.length == 0) return null; Map<String, Branch[]> path2Branches = new HashMap<>(); for (Handler handler : handlers) { Branch branch = new Branch(handler); for (String contextPath : branch.getContextPaths()) { Branch[] branches = path2Branches.get(contextPath); path2Branches.put(contextPath, ArrayUtil.addToArray(branches, branch, Branch.class)); } } for (Map.Entry<String, Branch[]> entry : path2Branches.entrySet()) { Branch[] branches = entry.getValue(); Branch[] sorted = new Branch[branches.length]; int i = 0; for (Branch branch : branches) { if (branch.hasVirtualHost()) sorted[i++] = branch; } for (Branch branch : branches) { if (!branch.hasVirtualHost()) sorted[i++] = branch; } entry.setValue(sorted); } int capacity = 512; Mapping mapping; loop: while (true) { mapping = new Mapping(handlers, capacity); for (Map.Entry<String, Branch[]> entry : path2Branches.entrySet()) { if (!mapping._pathBranches.put(entry.getKey().substring(1), entry)) { capacity += 512; continue loop; } } break; } if (LOG.isDebugEnabled()) { for (String ctx : mapping._pathBranches.keySet()) { LOG.debug("{}->{}", ctx, Arrays.asList(mapping._pathBranches.get(ctx).getValue())); } } for (Branch[] branches : path2Branches.values()) { for (Branch branch : branches) { for (ContextHandler context : branch.getContextHandlers()) { mapping._contextBranches.put(context, branch.getHandler()); } } } <START> if (mapping != null && mapping.getHandlers().length == 1) <END> _singleContext = mapping.getHandlers()[0]; return mapping; }</code><technical_language>mapping null here</technical_language>

Target:
protected Handlers newHandlers(Handler[] handlers) { if (handlers == null || handlers.length == 0) return null; Map<String, Branch[]> path2Branches = new HashMap<>(); for (Handler handler : handlers) { Branch branch = new Branch(handler); for (String contextPath : branch.getContextPaths()) { Branch[] branches = path2Branches.get(contextPath); path2Branches.put(contextPath, ArrayUtil.addToArray(branches, branch, Branch.class)); } } for (Map.Entry<String, Branch[]> entry : path2Branches.entrySet()) { Branch[] branches = entry.getValue(); Branch[] sorted = new Branch[branches.length]; int i = 0; for (Branch branch : branches) { if (branch.hasVirtualHost()) sorted[i++] = branch; } for (Branch branch : branches) { if (!branch.hasVirtualHost()) sorted[i++] = branch; } entry.setValue(sorted); } int capacity = 512; Mapping mapping; loop: while (true) { mapping = new Mapping(handlers, capacity); for (Map.Entry<String, Branch[]> entry : path2Branches.entrySet()) { if (!mapping._pathBranches.put(entry.getKey().substring(1), entry)) { capacity += 512; continue loop; } } break; } if (LOG.isDebugEnabled()) { for (String ctx : mapping._pathBranches.keySet()) { LOG.debug("{}->{}", ctx, Arrays.asList(mapping._pathBranches.get(ctx).getValue())); } } for (Branch[] branches : path2Branches.values()) { for (Branch branch : branches) { for (ContextHandler context : branch.getContextHandlers()) { mapping._contextBranches.put(context, branch.getHandler()); } } } return mapping; }
Source:
<code>public <T extends IAtsObject> Collection<T> getRelated(IAtsObject atsObject, RelationTypeSide relationType, DeletionFlag flag, Class<T> clazz) { List<T> results = new ArrayList<>(); Artifact useArt = getArtifact(atsObject); <START> if (atsObject == null || atsObject.isInvalid()) { return results; } <END> if (useArt != null) { for (Artifact art : useArt.getRelatedArtifacts(relationType, flag)) { IAtsObject object = AtsObjects.getAtsObject(art, atsClient); if (object != null) { results.add((T) object); } } } return results; }</code><technical_language>if protect a bad atsObject, this block moved lines 63-64? getArtifact call? is best</technical_language>

Target:
public <T extends IAtsObject> Collection<T> getRelated(IAtsObject atsObject, RelationTypeSide relationType, DeletionFlag flag, Class<T> clazz) { List<T> results = new ArrayList<>(); if (atsObject == null || atsObject.isInvalid()) { return results; } Artifact useArt = getArtifact(atsObject); if (useArt != null) { for (Artifact art : useArt.getRelatedArtifacts(relationType, flag)) { IAtsObject object = AtsObjects.getAtsObject(art, atsClient); if (object != null) { results.add((T) object); } } } return results; }
Source:
<code>public void start(Stage primaryStage) { primaryStage.setTitle("крестики-нолики"); Pane root = new Pane(); Button arrayOfButtons[][] = new Button[MAX_FIELD_SIZE][MAX_FIELD_SIZE]; GameLogic field = new GameLogic(); for (int i = 0; i < MAX_FIELD_SIZE; i++) for (int j = 0; j < MAX_FIELD_SIZE; j++) { <START> arrayOfButtons[i][j] = new Button(); arrayOfButtons[i][j].setTranslateX(j * 30); arrayOfButtons[i][j].setTranslateY(i * 30); root.getChildren().add(arrayOfButtons[i][j]); <END> } ButtonController buttons = new ButtonController(arrayOfButtons, field, primaryStage); buttons.initButtons(); UserInterface ui = new UserInterface(buttons, field, root, primaryStage); ui.init(); Scene mainScene = new Scene(root, 450, 130); primaryStage.setScene(mainScene); primaryStage.setResizable(false); primaryStage.show(); }</code><technical_language>gridPane</technical_language>

Target:
public void start(Stage primaryStage) { primaryStage.setTitle("крестики-нолики"); Pane root = new Pane(); Button arrayOfButtons[][] = new Button[MAX_FIELD_SIZE][MAX_FIELD_SIZE]; GameLogic field = new GameLogic(); for (int i = 0; i < MAX_FIELD_SIZE; i++) for (int j = 0; j < MAX_FIELD_SIZE; j++) { arrayOfButtons[i][j] = new Button(); arrayOfButtons[i][j].setTranslateX(j * 30); arrayOfButtons[i][j].setTranslateY(i * 30); root.getChildren().add(arrayOfButtons[i][j]); } ButtonController buttons = new ButtonController(arrayOfButtons, field, primaryStage); buttons.initButtons(); UserInterface ui = new UserInterface(buttons, field, root, primaryStage); ui.init(); Scene mainScene = new Scene(root, WINDOW_LENGTH, WINDOW_HEIGTH); primaryStage.setScene(mainScene); primaryStage.setResizable(false); primaryStage.show(); }
Source:
<code>public long folderSize(Context context) { long size = 0l; switch (mode){ case SFTP: return SshClientUtils.execute(new SshClientTemplate(path, false) { @Override public Long execute(SSHClient client) throws IOException { Session session = client.startSession(); String remotePath = SshClientUtils.extractRemotePathFrom(path); <START> Session.Command cmd = session.exec(String.format("du -b -s \"%s\"", remotePath)); <END> String result = new String(IOUtils.readFully(cmd.getInputStream()).toByteArray()); cmd.close(); session.close(); result = result.substring(0, result.indexOf('/') - 1).trim(); try { return Long.parseLong(result); } catch (NumberFormatException whenParseFailed){ Log.w(TAG, "Error running du, fallback to FileUtils.folderSizeSftp()"); SFTPClient sftpClient = client.newSFTPClient(); Long retval = FileUtils.folderSizeSftp(sftpClient, remotePath); sftpClient.close(); return retval; } } }); case SMB: try { size = FileUtils.folderSize(new SmbFile(path)); } catch (MalformedURLException e) { size = 0l; e.printStackTrace(); } break; case FILE: size = FileUtils.folderSize(new File(path), null); break; case ROOT: HybridFileParcelable baseFile=generateBaseFileFromParent(); if(baseFile!=null) size = baseFile.getSize(); break; case OTG: size = FileUtils.otgFolderSize(path, context); break; case DROPBOX: case BOX: case GDRIVE: case ONEDRIVE: size = FileUtils.folderSizeCloud(mode, dataUtils.getAccount(mode).getMetadata(CloudUtil.stripPath(mode, path))); break; default: return 0l; } return size; }</code><technical_language>a method command</technical_language>

Target:
public long folderSize(Context context) { long size = 0l; switch (mode){ case SFTP: return SshClientUtils.execute(new SFtpClientTemplate(path) { @Override public Long execute(SFTPClient client) throws IOException { return client.size(SshClientUtils.extractRemotePathFrom(path)); } }); case SMB: try { size = FileUtils.folderSize(new SmbFile(path)); } catch (MalformedURLException e) { size = 0l; e.printStackTrace(); } break; case FILE: size = FileUtils.folderSize(new File(path), null); break; case ROOT: HybridFileParcelable baseFile=generateBaseFileFromParent(); if(baseFile!=null) size = baseFile.getSize(); break; case OTG: size = FileUtils.otgFolderSize(path, context); break; case DROPBOX: case BOX: case GDRIVE: case ONEDRIVE: size = FileUtils.folderSizeCloud(mode, dataUtils.getAccount(mode).getMetadata(CloudUtil.stripPath(mode, path))); break; default: return 0l; } return size; }
Source:
<code>protected ByteBuffer readBuffer() { IntBuffer idBuffer = ByteBuffer.allocateDirect(4).asIntBuffer(); idBuffer.clear(); idBuffer.put(0, Integer.reverseBytes(messageID)); ByteBuffer timestamp = ByteBuffer.allocate(4); ByteBuffer response = null; try { response = CANJNI.FRCNetCommCANSessionMuxReceiveMessage(idBuffer, 0x1fffffff, timestamp); } catch (CANMessageNotFoundException e) { <START> LogKitten.w(e.getMessage()); END> } return response; }</code><technical_language>LogKitten.e appropriate? If error is, more reason err side of caution (we guarantee safe)</technical_language>

Target:
protected ByteBuffer readBuffer() throws CANMessageUnavailableException { IntBuffer idBuffer = ByteBuffer.allocateDirect(4).asIntBuffer(); idBuffer.clear(); idBuffer.put(0, Integer.reverseBytes(messageID)); ByteBuffer timestamp = ByteBuffer.allocate(4); try { return CANJNI.FRCNetCommCANSessionMuxReceiveMessage(idBuffer, 0x1fffffff, timestamp); } catch (CANMessageNotFoundException e) { throw new CANMessageUnavailableException("Unable to read CAN device " + getName() + " with ID 0x" + Integer.toHexString(messageID), e); } }
Source:
<code>private static BasicDBObject buildMongoGradeHistory(final GradeHistory gradeHistory) { <START> final BasicDBObject temp = new BasicDBObject(); <END> if (gradeHistory.hasGradeValue()) { temp.append(GRADE_VALUE, gradeHistory.getGradeValue()); } if (gradeHistory.hasComment()) { temp.append(COMMENT, gradeHistory.getComment()); } if (gradeHistory.hasGradedDate()) { temp.append(GRADED_DATE, gradeHistory.getGradedDate()); } if (gradeHistory.hasWhoChanged()) { temp.append(WHO_CHANGED, gradeHistory.getWhoChanged()); } return temp; }</code><technical_language>dont name temp</technical_language>

Target:
static BasicDBObject buildMongoGradeHistory(final GradeHistory gradeHistory) { final BasicDBObject gradeHistoryDBObject = new BasicDBObject(); if (gradeHistory.hasGradeValue()) { gradeHistoryDBObject.append(GRADE_VALUE, gradeHistory.getGradeValue()); } if (gradeHistory.hasComment()) { gradeHistoryDBObject.append(COMMENT, gradeHistory.getComment()); } if (gradeHistory.hasGradedDate()) { gradeHistoryDBObject.append(GRADED_DATE, gradeHistory.getGradedDate().getMillisecond()); } if (gradeHistory.hasWhoChanged()) { gradeHistoryDBObject.append(WHO_CHANGED, gradeHistory.getWhoChanged()); } return gradeHistoryDBObject; }
Source:
<code>private StageInfo buildStageInfo(SubPlan subPlan, Map<StageId, StageInfo> stageInfos) <START> { <END> StageInfo stageInfo = stageInfos.get(planFragmentIdToStageIdMap.get(subPlan.getFragment().getId())); checkArgument(stageInfo != null, "No stageInfo for %s", stageInfo); if (subPlan.getChildren().isEmpty()) { return stageInfo; } return new StageInfo( stageInfo.getStageId(), stageInfo.getState(), stageInfo.getSelf(), stageInfo.getPlan(), stageInfo.getTypes(), stageInfo.getStageStats(), stageInfo.getTasks(), subPlan.getChildren().stream() .map(plan -> buildStageInfo(plan, stageInfos)) .collect(toImmutableList()), stageInfo.getFailureCause()); }</code><technical_language>nice refactor</technical_language>

Target:
private StageInfo buildStageInfo(SubPlan subPlan, Map<StageId, StageInfo> stageInfos) { StageInfo stageInfo = stageInfos.get(getStageId(subPlan.getFragment().getId())); checkArgument(stageInfo != null, "No stageInfo for %s", stageInfo); if (subPlan.getChildren().isEmpty()) { return stageInfo; } return new StageInfo( stageInfo.getStageId(), stageInfo.getState(), stageInfo.getSelf(), stageInfo.getPlan(), stageInfo.getTypes(), stageInfo.getStageStats(), stageInfo.getTasks(), subPlan.getChildren().stream() .map(plan -> buildStageInfo(plan, stageInfos)) .collect(toImmutableList()), stageInfo.getFailureCause()); }
Source:
<code>public boolean allLeftOperandsContainColumnReferences() throws StandardException { CollectNodesVisitor cnv = new CollectNodesVisitor(ColumnReference.class); for (int i = 0; i < leftOperandList.size(); i++) { leftOperandList.elementAt(i).accept(cnv); <START> if (cnv.getList().isEmpty()) <END> return false; } return true; }</code><technical_language>variable declaration of cnv moved for loop, otherwise, able detect empty column references correctly for element upper</technical_language>

Target:
public boolean allLeftOperandsContainColumnReferences() throws StandardException { CollectNodesVisitor cnv = new CollectNodesVisitor(ColumnReference.class); for (int i = 0; i < leftOperandList.size(); i++) { leftOperandList.elementAt(i).accept(cnv); if (cnv.getList().isEmpty()) { return false; } cnv.getList().clear(); } return true; }
Source:
<code>public @Nullable ASTExpression getQualifier() { <START> return ASTQualifiableExpression.super.getQualifier(); <END> }</code><technical_language>I understand this: getQualifier() is executed runtime? ASTQualifiableExpression a interface, a super interface, a default implementation for getQualifier() is executed</technical_language>

Target:
public @Nullable ASTExpression getQualifier() { return QualifierOwner.super.getQualifier(); }
Source:
<code>private ProjectControl user(AccountGroup.Id... memberOf) { RefControl.Factory refControlFactory = new RefControl.Factory() { @Override public RefControl create(final ProjectControl projectControl, final String ref) { <START> return new RefControl(systemConfig, projectControl, ref, null); <END> } }; return new ProjectControl(Collections.<AccountGroup.Id> emptySet(), Collections.<AccountGroup.Id> emptySet(), refControlFactory, new MockUser(memberOf), newProjectState()); }</code><technical_language>Please implement a mock version of RegExpCache a normal HashMap</technical_language>

Target:
private ProjectControl user(AccountGroup.Id... memberOf) { RefControl.Factory refControlFactory = new RefControl.Factory() { @Override public RefControl create(final ProjectControl projectControl, final String ref) { return new RefControl(systemConfig, projectControl, ref); } }; return new ProjectControl(systemConfig, Collections.<AccountGroup.Id> emptySet(), Collections.<AccountGroup.Id> emptySet(), refControlFactory, new MockUser(memberOf), newProjectState()); }
Source:
<code>public @ResponseBody String deleteFilter(@PathVariable("filterId") final Long filterId) { try { FilterDTO filterDTO = filterManager.getByFilterId(filterId); if (filterDTO != null) { filterManager.delete(filterDTO); return "{\"success\" : true}"; } else { <START> return "{\"success\" : false}"; <END> } } catch (Exception e) { LOGGER.error("Could not delete filterId: " + filterId, e); return "{\"success\" : false}"; } }</code><technical_language>I if code executes this line filterId passed in valid I return error code in case. Bad Request? throw exception caught handled in controller advice class send Bad Request status code here</technical_language>

Target:
public @ResponseBody String deleteFilter(@PathVariable("filterId") final Long filterId) throws EntityRetrievalException, ValidationException { FilterDTO filterDTO = filterManager.getByFilterId(filterId); filterManager.delete(filterDTO); return "{\"success\" : true}"; }
Source:
<code>public synchronized void activate() { <START> OTELog.getLogger("test").debug("something"); <END> listener = new Slf4jLogListener(); logService.addLogListener(listener); }</code><technical_language>remove this line</technical_language>

Target:
public synchronized void activate() { listener = new Slf4jLogListener(); logService.addLogListener(listener); }
Source:
<code>Optional<BitSet> getRowsFromUuid(FileSystem fileSystem, Optional<UUID> deltaShardUuid) { if (!deltaShardUuid.isPresent()) { return Optional.empty(); } try (OrcDataSource dataSource = openShard(fileSystem, deltaShardUuid.get(), defaultReaderAttributes)) { AggregatedMemoryContext systemMemoryUsage = newSimpleAggregatedMemoryContext(); OrcReader reader = new OrcReader( dataSource, ORC, orcFileTailSource, new StorageStripeMetadataSource(), new OrcReaderOptions( defaultReaderAttributes.getMaxMergeDistance(), defaultReaderAttributes.getTinyStripeThreshold(), HUGE_MAX_READ_BLOCK_SIZE, false)); if (reader.getFooter().getNumberOfRows() >= Integer.MAX_VALUE) { throw new IOException("File has too many rows"); } ImmutableMap.Builder<Integer, Type> includedColumns = ImmutableMap.builder(); includedColumns.put(0, BIGINT); OrcBatchRecordReader recordReader = reader.createBatchRecordReader( includedColumns.build(), OrcPredicate.TRUE, DEFAULT_STORAGE_TIMEZONE, systemMemoryUsage, INITIAL_BATCH_SIZE); BitSet bitSet = new BitSet(); while (recordReader.nextBatch() > 0) { Block block = recordReader.readBlock(0); for (int i = 0; i < block.getPositionCount(); i++) { bitSet.set(toIntExact(block.getLong(i))); } } return Optional.of(bitSet); } catch (IOException | RuntimeException e) { throw new PrestoException(RAPTOR_ERROR, "Failed to read file: " + deltaShardUuid, e); } catch (Throwable t) { <START> throw t; <END> } }</code><technical_language>need catch Throwable if want immediately rethrow it</technical_language>

Target:
Optional<BitSet> getRowsFromUuid(FileSystem fileSystem, Optional<UUID> deltaShardUuid) { if (!deltaShardUuid.isPresent()) { return Optional.empty(); } try (OrcDataSource dataSource = openShard(fileSystem, deltaShardUuid.get(), defaultReaderAttributes)) { AggregatedMemoryContext systemMemoryUsage = newSimpleAggregatedMemoryContext(); OrcReader reader = new OrcReader( dataSource, ORC, orcFileTailSource, new StorageStripeMetadataSource(), new OrcReaderOptions( defaultReaderAttributes.getMaxMergeDistance(), defaultReaderAttributes.getTinyStripeThreshold(), HUGE_MAX_READ_BLOCK_SIZE, defaultReaderAttributes.isZstdJniDecompressionEnabled())); if (reader.getFooter().getNumberOfRows() >= Integer.MAX_VALUE) { throw new IOException("File has too many rows"); } try (OrcBatchRecordReader recordReader = reader.createBatchRecordReader( ImmutableMap.of(0, BIGINT), OrcPredicate.TRUE, DEFAULT_STORAGE_TIMEZONE, systemMemoryUsage, INITIAL_BATCH_SIZE)) { BitSet bitSet = new BitSet(); while (recordReader.nextBatch() > 0) { Block block = recordReader.readBlock(0); for (int i = 0; i < block.getPositionCount(); i++) { bitSet.set(toIntExact(block.getLong(i))); } } return Optional.of(bitSet); } } catch (IOException | RuntimeException e) { throw new PrestoException(RAPTOR_ERROR, "Failed to read file: " + deltaShardUuid, e); } }
Source:
<code>public void update() { Optional<Location> location = Iterables.tryFind(getLocations(), Predicates.instanceOf(SshMachineLocation.class)); SshMachineLocation machine = (SshMachineLocation) location.get(); <START> String[] templateList = new String[] { "domain.zone", "named.conf" }; <END> for (String fileName : templateList) { String contents = ((BindDnsServerSshDriver) getDriver()).processTemplate(RESOURCES_CLASSPATH + fileName); machine.copyTo(new ByteArrayInputStream(contents.getBytes()), "/tmp/" + fileName); } machine.execScript("update bind config", ImmutableList.of( CommonCommands.sudo("mv /tmp/named.conf /etc/named.conf"), CommonCommands.sudo("mv /tmp/domain.zone /var/named/domain.zone"), CommonCommands.sudo("service named restart"))); LOG.info("updated named configuration and zone file for '{}' on {}", getDomainName(), this); }</code><technical_language>config keys (using fully qualified names), easily replace template domain.zone file is used</technical_language>

Target:
public void update() { Optional<Location> location = Iterables.tryFind(getLocations(), Predicates.instanceOf(SshMachineLocation.class)); SshMachineLocation machine = (SshMachineLocation) location.get(); copyTemplate(getConfig(NAMED_CONF_TEMPLATE), "/etc/named.conf", machine); copyTemplate(getConfig(DOMAIN_ZONE_FILE_TEMPLATE), "/var/named/domain.zone", machine); copyTemplate(getConfig(REVERSE_ZONE_FILE_TEMPLATE), "/var/named/reverse.zone", machine); machine.execScript("restart bind", ImmutableList.of(CommonCommands.sudo("service named restart"))); LOG.info("updated named configuration and zone file for '{}' on {}", getDomainName(), this); }