auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Plugin loadPlugin(String name, File srcJar, FileSnapshot snapshot) throws IOException, ClassNotFoundException, InvalidPluginException { File tmp; FileInputStream in = new FileInputStream(srcJar); try { tmp = asTemp(in, tempNameFor(name), ".jar", tmpDir); } finally { in.close(); } JarFile jarFile = new JarFile(tmp); boolean keep = false; try { Manifest manifest = jarFile.getManifest(); Plugin.ApiType type = Plugin.getApiType(manifest); Attributes main = manifest.getMainAttributes(); String sysName = main.getValue("Gerrit-Module"); String sshName = main.getValue("Gerrit-SshModule"); String httpName = main.getValue("Gerrit-HttpModule"); <START> String webName = main.getValue("Web-HttpModule"); <END> if (!Strings.isNullOrEmpty(sshName) && type != Plugin.ApiType.PLUGIN) { throw new InvalidPluginException(String.format( "Using Gerrit-SshModule requires Gerrit-ApiType: %s", Plugin.ApiType.PLUGIN)); } URL[] urls = {tmp.toURI().toURL()}; ClassLoader parentLoader = parentFor(type); ClassLoader pluginLoader = new URLClassLoader(urls, parentLoader); cleanupHandles.put( new CleanupHandle(tmp, jarFile, pluginLoader, cleanupQueue), Boolean.TRUE); Class<? extends Module> sysModule = load(sysName, pluginLoader); Class<? extends Module> sshModule = load(sshName, pluginLoader); Class<? extends Module> httpModule = load(httpName, pluginLoader); keep = true; return new Plugin(name, srcJar, snapshot, jarFile, manifest, new File(dataDir, name), type, pluginLoader, sysModule, sshModule, httpModule); } finally { if (!keep) { jarFile.close(); } } }</code><technical_language>necessary. web plugin bound in Gerrit-HttpModule</technical_language>

Target:
private Plugin loadPlugin(String name, File srcJar, FileSnapshot snapshot) throws IOException, ClassNotFoundException, InvalidPluginException { File tmp; FileInputStream in = new FileInputStream(srcJar); try { tmp = asTemp(in, tempNameFor(name), ".jar", tmpDir); } finally { in.close(); } JarFile jarFile = new JarFile(tmp); boolean keep = false; try { Manifest manifest = jarFile.getManifest(); Plugin.ApiType type = Plugin.getApiType(manifest); Attributes main = manifest.getMainAttributes(); String sysName = main.getValue("Gerrit-Module"); String sshName = main.getValue("Gerrit-SshModule"); String httpName = main.getValue("Gerrit-HttpModule"); if (!Strings.isNullOrEmpty(sshName) && type != Plugin.ApiType.PLUGIN) { throw new InvalidPluginException(String.format( "Using Gerrit-SshModule requires Gerrit-ApiType: %s", Plugin.ApiType.PLUGIN)); } URL[] urls = {tmp.toURI().toURL()}; ClassLoader parentLoader = parentFor(type); ClassLoader pluginLoader = new URLClassLoader(urls, parentLoader); cleanupHandles.put( new CleanupHandle(tmp, jarFile, pluginLoader, cleanupQueue), Boolean.TRUE); Class<? extends Module> sysModule = load(sysName, pluginLoader); Class<? extends Module> sshModule = load(sshName, pluginLoader); Class<? extends Module> httpModule = load(httpName, pluginLoader); keep = true; return new Plugin(name, srcJar, snapshot, jarFile, manifest, new File(dataDir, name), type, pluginLoader, sysModule, sshModule, httpModule); } finally { if (!keep) { jarFile.close(); } } }
Source:
<code>public void Authenticate(String authUser, String authPassword) throws AuthenticationException { if (!userName.equals(authUser)) { <START> throw new AuthenticationException("Invalid user " + authUser); <END> } if (!password.equals(authPassword)) { throw new AuthenticationException("Invalid password " + authPassword); } LOG.info("User " + authUser + " successfully authenticated."); }</code><technical_language>dont put username password in exception ..add a debug log</technical_language>

Target:
public void Authenticate(String authUser, String authPassword) throws AuthenticationException { if (!userName.equals(authUser)) { LOG.debug("Invalid user " + authUser); throw new AuthenticationException("Invalid credentials"); } if (!password.equals(authPassword)) { LOG.debug("Invalid password for user " + authUser); throw new AuthenticationException("Invalid credentials"); } LOG.debug("User " + authUser + " successfully authenticated."); }
Source:
<code>public void apply(OnlineCommandContext ctx) throws Exception { Operations ops = new Operations(ctx.client); if(allowResourceServiceRestart) <START> ops = ops.headers(Values.of("allow-resource-service-restart", "true")); <END> ops.remove(address); }</code><technical_language>Headers class</technical_language>

Target:
public void apply(OnlineCommandContext ctx) throws Exception { Operations ops = new Operations(ctx.client); if (ctx.version.greaterThanOrEqualTo(ServerVersion.VERSION_5_0_0)) ops = ops.headers(Headers.allowResourceServiceRestart()); ops.remove(address); }
Source:
<code>public void testMakingAttachment() { <START> testMakingAttachmentFile("attachment.txt","normal text file") <END> }</code><technical_language>missing semicolon;</technical_language>

Target:
public void testMakingAttachment() { testMakingAttachmentFile("attachment.txt","normal text file"); }
Source:
<code><START> public void testCreateReadDelete() throws Exception { <END> DocumentModel userModel = userManager.getBareUserModel(); String schemaName = userManager.getUserSchemaName(); userModel.setProperty(schemaName, "username", USERNAME); userModel = userManager.createUser(userModel); DocumentModel folder = systemSession.createDocumentModel("/", "folder", "Folder"); folder = systemSession.createDocument(folder); DocumentModel doc = systemSession.createDocumentModel("/folder/", "TestFile", "File"); doc = systemSession.createDocument(doc); ACP acp = doc.getACP(); ACE grantRead = new ACE(USERNAME, SecurityConstants.READ, true); acp.addACE(ACL.LOCAL_ACL, grantRead); doc.setACP(acp, true); try (CoreSession userSession = coreFeature.openCoreSession(USERNAME)) { DocumentModel userDoc = userSession.getDocument(doc.getRef()); DocumentModel comment = userSession.createDocumentModel(CommentsConstants.COMMENT_DOC_TYPE); comment.setPropertyValue(COMMENT_CONTENT_PROPERTY_XPATH, COMMENT_CONTENT); commentManager.createComment(userDoc, comment); List<DocumentModel> dml = systemSession.query(QUERY_COMMENTS_AS_DOCUMENTS); assertEquals(1, dml.size()); dml = userSession.query(QUERY_COMMENTS_AS_DOCUMENTS); assertEquals(0, dml.size()); List<DocumentModel> comments = commentManager.getComments(userDoc); assertEquals(1, comments.size()); assertEquals(COMMENT_CONTENT, comments.get(0).getPropertyValue(COMMENT_CONTENT_PROPERTY_XPATH)); commentManager.deleteComment(userDoc, comments.get(0)); comments = commentManager.getComments(userDoc); assertEquals(0, comments.size()); } }</code><technical_language>throws Exception is needed</technical_language>

Target:
public void testCreateReadDelete() { DocumentModel userModel = userManager.getBareUserModel(); String schemaName = userManager.getUserSchemaName(); userModel.setProperty(schemaName, "username", USERNAME); DocumentModel folder = systemSession.createDocumentModel("/", "folder", "Folder"); systemSession.createDocument(folder); DocumentModel doc = systemSession.createDocumentModel("/folder/", "TestFile", "File"); doc = systemSession.createDocument(doc); ACP acp = doc.getACP(); ACE grantRead = new ACE(USERNAME, SecurityConstants.READ, true); acp.addACE(ACL.LOCAL_ACL, grantRead); doc.setACP(acp, true); try (CoreSession userSession = coreFeature.openCoreSession(USERNAME)) { DocumentModel userDoc = userSession.getDocument(doc.getRef()); DocumentModel comment = userSession.createDocumentModel(CommentsConstants.COMMENT_DOC_TYPE); comment.setPropertyValue(COMMENT_CONTENT_PROPERTY_XPATH, COMMENT_CONTENT); commentManager.createComment(userDoc, comment); List<DocumentModel> dml = systemSession.query(QUERY_COMMENTS_AS_DOCUMENTS); assertEquals(1, dml.size()); dml = userSession.query(QUERY_COMMENTS_AS_DOCUMENTS); assertEquals(0, dml.size()); List<DocumentModel> comments = commentManager.getComments(userDoc); assertEquals(1, comments.size()); assertEquals(COMMENT_CONTENT, comments.get(0).getPropertyValue(COMMENT_CONTENT_PROPERTY_XPATH)); commentManager.deleteComment(userDoc, comments.get(0)); comments = commentManager.getComments(userDoc); assertEquals(0, comments.size()); } }
Source:
<code>public void buildShellScript() throws Exception { <START> story.addStep( <END> new Statement() { @Override public void evaluate() throws Throwable { Node node = TestUtils.createSwarmClient( story.j, processDestroyer, tmpDir.allocate()); WorkflowJob project = story.j.createProject(WorkflowJob.class); project.setConcurrentBuild(false); project.setDefinition(new CpsFlowDefinition(getFlow(node, 0), true)); WorkflowRun build = project.scheduleBuild2(0).waitForStart(); story.j.waitForCompletion(build); story.j.assertLogContains("ON_SWARM_CLIENT=true", build); story.j.assertBuildStatusSuccess(build); tearDown(); } }); }</code><technical_language>If in Java 8, is nicer .then</technical_language>

Target:
public void buildShellScript() throws Exception { story.then( s -> { Node node = TestUtils.createSwarmClient(story.j, processDestroyer, temporaryFolder); WorkflowJob project = story.j.createProject(WorkflowJob.class); project.setConcurrentBuild(false); project.setDefinition(new CpsFlowDefinition(getFlow(node, 0), true)); WorkflowRun build = story.j.buildAndAssertSuccess(project); story.j.assertLogContains("ON_SWARM_CLIENT=true", build); tearDown(); }); }
Source:
<code>private <T> T provideUnchecked(final Class<T> serviceClass) { final Registration<T> registration = (Registration<T>) this.services.get(serviceClass); if (registration != null) { return registration.service(); } <START> throw new IllegalStateException(""); <END> }</code><technical_language>"No provider is registered for service '" + service.getName() + "'", service" (this is current errore message). this thrown a ProvisioningException</technical_language>

Target:
private <T> T provideUnchecked(final Class<T> serviceClass) { final Registration<T> registration = (Registration<T>) this.services.get(serviceClass); if (registration != null) { return registration.service(); } throw new IllegalStateException("Service registration does not exist."); }
Source:
<code>public void update(float delta) { if (contents != null) { contents.update(delta); animationSystem.update(delta); <START> if (depth == -999999) { <END> setDepthAuto(); } } }</code><technical_language>another reason for magic numbers considered evil: This time is 9s. in AbstractWidget is _five_ 9s. purpose? Bug? a public static constant worry a change in more place :-)</technical_language>

Target:
public void update(float delta) { if (contents != null) { contents.update(delta); animationSystem.update(delta); if (depth == SortOrderSystem.DEFAULT_DEPTH) { setDepthAuto(); } } }
Source:
<code>@Override public Map<UUID, Integer> topologySnapshot() { <START> return top; <END> }</code><technical_language>Do want share a reference this map? share a reference read view of it</technical_language>

Target:
@Override public Map<UUID, Integer> topologySnapshot() { return Collections.unmodifiableMap(top); }
Source:
<code>private void checkAttributes(Map<String, Object> attributes) { if (attributes == null) { <START> throw new IllegalArgumentException("Attributes must be non null"); <END> } }</code><technical_language>></technical_language>

Target:
private void checkAttributes(Map<String, Object> attributes) { if (attributes == null) { throw new IllegalArgumentException("Attributes must be not null"); } }
Source:
<code>public BlockFamily createFamily(BlockBuilderHelper blockBuilderHelper) { Preconditions.checkState(!isFreeform()); <START> return BlockfamilyLibrary.createFamily(getData().getBlockFamily(), this, blockBuilderHelper); <END> }</code><technical_language>lowercase family change</technical_language>

Target:
public BlockFamily createFamily(BlockBuilderHelper blockBuilderHelper) { Preconditions.checkState(!isFreeform()); return BlockFamilyLibrary.createFamily(getData().getBlockFamily(), this, blockBuilderHelper); }
Source:
<code>@Test public void staticCodeBlock() { TypeSpec taco = TypeSpec.classBuilder("Taco") .addField(String.class, "mFoo", Modifier.PRIVATE) .addField(String.class, "FOO", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .addStaticBlock(CodeBlock.builder() .addStatement("FOO = $S", "FOO") .build()) .addMethod(MethodSpec.methodBuilder("toString") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(String.class) .addCode("return FOO;\n") .build()) .build(); assertThat(toString(taco)).isEqualTo("" + "package com.squareup.tacos;\n" + "\n" + "import java.lang.Override;\n" + "import java.lang.String;\n" + "\n" + "class Taco {\n" <START> + " private static final String FOO;\n\n" <END> + " static {\n" + " FOO = \"FOO\";\n" + " }\n\n" + " private String mFoo;\n\n" + " @Override\n" + " public String toString() {\n" + " return FOO;\n" + " }\n" + "}\n"); }</code><technical_language>Do a favor? a separate line for \n \n\n</technical_language>

Target:
@Test public void staticCodeBlock() { TypeSpec taco = TypeSpec.classBuilder("Taco") .addField(String.class, "foo", Modifier.PRIVATE) .addField(String.class, "FOO", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .addStaticBlock(CodeBlock.builder() .addStatement("FOO = $S", "FOO") .build()) .addMethod(MethodSpec.methodBuilder("toString") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(String.class) .addCode("return FOO;\n") .build()) .build(); assertThat(toString(taco)).isEqualTo("" + "package com.squareup.tacos;\n" + "\n" + "import java.lang.Override;\n" + "import java.lang.String;\n" + "\n" + "class Taco {\n" + " private static final String FOO;\n" + "\n" + " static {\n" + " FOO = \"FOO\";\n" + " }\n" + "\n" + " private String foo;\n" + "\n" + " @Override\n" + " public String toString() {\n" + " return FOO;\n" + " }\n" + "}\n"); }
Source:
<code>private Command getPropertyPublicPart(RepositoryNode selectedNode, IElementParameter param, Node node, ConnectionItem connectionItem) { param.getChildParameters().get(EParameterName.PROPERTY_TYPE.getName()).setValue(EmfComponent.REPOSITORY); ChangeValuesFromRepository command2 = new ChangeValuesFromRepository( node, connectionItem.getConnection(), param.getName() + ":" + EParameterName.REPOSITORY_PROPERTY_TYPE.getName(), selectedNode.getObject().getProperty().getId()); if (selectedNode.getObject() instanceof IMetadataTable) { IMetadataTable metadataTable = (IMetadataTable) selectedNode.getObject(); command2.setTable(metadataTable); } <START> if (selectedNode.getProperties(EProperties.CONTENT_TYPE) == ERepositoryObjectType.METADATA_CONNECTIONS) { <END> command2.setGuessQuery(true); } return command2; }</code><technical_language>line 1440</technical_language>

Target:
private Command getPropertyPublicPart(RepositoryNode selectedNode, IElementParameter param, Node node, ConnectionItem connectionItem) { param.getChildParameters().get(EParameterName.PROPERTY_TYPE.getName()).setValue(EmfComponent.REPOSITORY); ChangeValuesFromRepository command2 = new ChangeValuesFromRepository( node, connectionItem.getConnection(), param.getName() + ":" + EParameterName.REPOSITORY_PROPERTY_TYPE.getName(), selectedNode.getObject().getProperty().getId()); if (selectedNode.getObject() instanceof IMetadataTable) { IMetadataTable metadataTable = (IMetadataTable) selectedNode.getObject(); command2.setTable(metadataTable); } if (selectedNode.getProperties(EProperties.CONTENT_TYPE) != ERepositoryObjectType.METADATA_CON_QUERY) { command2.setGuessQuery(true); } return command2; }
Source:
<code>public void testCoordinatorFailed() throws Exception { startGrids(NODES_CNT); CountDownLatch startLatch = new CountDownLatch(NODES_CNT); CountDownLatch finishLatch = new CountDownLatch(NODES_CNT - 1); HashMap<String, DistributedProcess<Integer, Integer>> processes = new HashMap<>(); int processRes = 1; for (Ignite grid : G.allGrids()) { DistributedProcess<Integer, Integer> dp = new DistributedProcess<>(((IgniteEx)grid).context(), TEST_PROCESS, req -> GridTestUtils.runAsync(() -> { <START> startLatch.countDown(); <END> try { nodeLeftLatch.await(); } catch (InterruptedException ignored) { fail("Unexpected interrupt."); } return req; }), (uuid, res, err) -> { if (res.values().size() == NODES_CNT - 1 && res.values().stream().allMatch(i -> i == processRes)) finishLatch.countDown(); else fail("Unexpected process result [res=" + res + ", err=" + err + ']'); } ); processes.put(grid.name(), dp); } listeningLog.registerListener(s -> { if (s.startsWith("Failed to send a single message to coordinator")) msgSendLatch.countDown(); }); processes.get(grid(0).name()).start(UUID.randomUUID(), processRes); assertTrue(startLatch.await(TIMEOUT, MILLISECONDS)); stopGrid(0); assertTrue(finishLatch.await(TIMEOUT, MILLISECONDS)); assertFalse(failure.get()); }</code><technical_language>release latch single-message future completed? a new coordinator assigned prior single message sent</technical_language>

Target:
public void testCoordinatorFailed() throws Exception { startGrids(NODES_CNT); CountDownLatch startLatch = new CountDownLatch(NODES_CNT); CountDownLatch finishLatch = new CountDownLatch(NODES_CNT - 1); HashMap<String, DistributedProcess<Integer, Integer>> processes = new HashMap<>(); int processRes = 1; for (Ignite grid : G.allGrids()) { DistributedProcess<Integer, Integer> dp = new DistributedProcess<>(((IgniteEx)grid).context(), TEST_PROCESS, req -> { IgniteInternalFuture<Integer> fut = runAsync(() -> { try { nodeLeftLatch.await(); } catch (InterruptedException ignored) { fail("Unexpected interrupt."); } return req; }); if (!grid.name().equals(getTestIgniteInstanceName(STOP_NODE_IDX))) fut.listen(f -> msgSendLatch.countDown()); startLatch.countDown(); return fut; }, (uuid, res, err) -> { if (res.values().size() == NODES_CNT - 1 && res.values().stream().allMatch(i -> i == processRes)) finishLatch.countDown(); else fail("Unexpected process result [res=" + res + ", err=" + err + ']'); } ); processes.put(grid.name(), dp); } processes.get(grid(STOP_NODE_IDX).name()).start(UUID.randomUUID(), processRes); assertTrue(startLatch.await(TIMEOUT, MILLISECONDS)); stopGrid(STOP_NODE_IDX); assertTrue(finishLatch.await(TIMEOUT, MILLISECONDS)); assertFalse(failure.get()); }
Source:
<code>public AdvancedJUnitLaunchConfigurationDelegate() { <START> allowAdvancedSourcelookup(); <END> }</code><technical_language>call super constructor also</technical_language>

Target:
public AdvancedJUnitLaunchConfigurationDelegate() { super(); allowAdvancedSourcelookup(); }
Source:
<code>protected void post2(BuildListener listener) throws Exception { if(getResult()== Result.SUCCESS) getStatus().onSuccessfulPromotion(Promotion.this); if (getTarget() != null) { getTarget().save(); <START> } <END> if (getResult() == Result.SUCCESS) { PromotedBuildAction pba = getTarget().getAction(PromotedBuildAction.class); for (PromotionProcess pp : pba.getPendingPromotions()) { pp.considerPromotion2(getTarget()); } for (AbstractProject<?,?> p : JenkinsHelper.getInstance().getAllItems(AbstractProject.class)) { PromotionTrigger pt = p.getTrigger(PromotionTrigger.class); if (pt!=null) pt.consider(Promotion.this); } } }</code><technical_language>need logging otherwise</technical_language>

Target:
protected void post2(BuildListener listener) throws Exception { if (getTarget() == null) { listener.error("No Promotion target, cannot save target or update status"); return; } if(getResult()== Result.SUCCESS) getStatus().onSuccessfulPromotion(Promotion.this); getTarget().save(); if (getResult() == Result.SUCCESS) { PromotedBuildAction pba = getTarget().getAction(PromotedBuildAction.class); for (PromotionProcess pp : pba.getPendingPromotions()) { pp.considerPromotion2(getTarget()); } for (AbstractProject<?,?> p : JenkinsHelper.getInstance().getAllItems(AbstractProject.class)) { PromotionTrigger pt = p.getTrigger(PromotionTrigger.class); if (pt!=null) pt.consider(Promotion.this); } } }
Source:
<code>public static EntityTypeSearchResults create(EntityType entityType, List<AttributeSearchResults> attributeSearchResults) { <START> return new AutoValue_EntityTypeSearchResults(entityType, attributeSearchResults); <END> }</code><technical_language>create immutable copy of search results</technical_language>

Target:
public static EntityTypeSearchResults create(EntityType entityType, List<AttributeSearchResults> attributeSearchResults) { return new AutoValue_EntityTypeSearchResults(entityType, ImmutableList.copyOf(attributeSearchResults)); }
Source:
<code>public final void postprocess() throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, ClassNotFoundException, IOException, CoreException { for (Field resultField : resultFields) { resultField.setAccessible(true); AbstractResult<?> result = (AbstractResult<?>) resultField.get(null); String name = NamingHelper.createFullNameForMember(resultField); result.setName(name); simulatorInitializationInfo.results.add(result); } for (Class<?> decisionPointClass : decisionPointClasses) { AbstractDecisionPoint dpt = (AbstractDecisionPoint) decisionPointClass.newInstance(); simulatorInitializationInfo.decisionPoints.add(dpt); } for (IResource processFile : BuildUtil.getAllFilesInProject(project, "proc")) { ProcessModelNode model; try { model = ProcessEditor.readModelFromFile((IFile) processFile); } catch (EOFException e) { continue; } List<Block> blocks; <START> blocks = BlockConverter.convertModelToBlocks(model, modelContentsInfo); <END> simulatorInitializationInfo.processBlocks.addAll(blocks); } for (Class<?> animationClass : animationClasses) { AnimationFrame frame = (AnimationFrame) animationClass.newInstance(); animationFrames.add(frame); } }</code><technical_language>java List<Block> blocks = BlockConverter.convertModelToBlocks(model, modelContentsInfo);</technical_language>

Target:
public final void postprocess() throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, ClassNotFoundException, IOException, CoreException { for (Field resultField : resultFields) { resultField.setAccessible(true); AbstractResult<?> result = (AbstractResult<?>) resultField.get(null); String name = NamingHelper.createFullNameForMember(resultField); result.setName(name); simulatorInitializationInfo.results.add(result); } for (Class<?> decisionPointClass : decisionPointClasses) { AbstractDecisionPoint dpt = (AbstractDecisionPoint) decisionPointClass.newInstance(); simulatorInitializationInfo.decisionPoints.add(dpt); } for (IResource processFile : BuildUtil.getAllFilesInProject(project, "proc")) { ProcessModelNode model = ProcessEditor.readModelFromFile((IFile) processFile); if (model == null) model = new ProcessModelNode(); List<Block> blocks = BlockConverter.convertModelToBlocks(model, modelContentsInfo); simulatorInitializationInfo.processBlocks.addAll(blocks); } for (Class<?> animationClass : animationClasses) { AnimationFrame frame = (AnimationFrame) animationClass.newInstance(); animationFrames.add(frame); } }
Source:
<code>public void customApplicationIdUserAgentTest() throws Exception { final HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(new NoOpHttpClient() { @Override public Mono<HttpResponse> send(HttpRequest request) { String header = request.getHeaders().getValue("User-Agent"); String expectedHeaderPrefix = "user_specified_appId"; <START> Assertions.assertTrue(header.startsWith(expectedHeaderPrefix)); <END> return Mono.just(new MockHttpResponse(request, 200)); } }) .policies(new UserAgentPolicy( "user_specified_appId", "package.name", "package_version", Configuration.NONE, () -> "1.0")) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http://localhost"))).block(); Assertions.assertEquals(200, response.getStatusCode()); }</code><technical_language>validate User-Agent string</technical_language>

Target:
public void customApplicationIdUserAgentTest() throws Exception { final String testSdkName = "sdk.name"; final String testAppId = "user_specified_appId"; final String testPackageVersion = "package_version"; String javaVersion = Configuration.getGlobalConfiguration().get("java.version"); String osName = Configuration.getGlobalConfiguration().get("os.name"); String osVersion = Configuration.getGlobalConfiguration().get("os.version"); String testPlatformInfo = javaVersion + "; " + osName + " " + osVersion; String expectedHeader = testAppId + " " + "azsdk-java-" + testSdkName + "/" + testPackageVersion + " " + testPlatformInfo; final HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(new NoOpHttpClient() { @Override public Mono<HttpResponse> send(HttpRequest request) { String header = request.getHeaders().getValue("User-Agent"); assertEquals(header, expectedHeader); return Mono.just(new MockHttpResponse(request, 200)); } }) .policies(new UserAgentPolicy( testAppId, testSdkName, testPackageVersion, Configuration.NONE, () -> "1.0")) .build(); Mono<HttpResponse> response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http://localhost"))); StepVerifier.create(response) .expectNextMatches(httpResponse -> { assertEquals(200, httpResponse.getStatusCode()); assertEquals(expectedHeader, httpResponse.getRequest().getHeaders().getValue("User-Agent")); return true; }) .verifyComplete(); }
Source:
<code>private synchronized void putConnectorConfig(String connName, final Map<String, String> config, boolean allowReplace, final Callback<Created<ConnectorInfo>> callback, ConfigInfos configInfos) { try { if (maybeAddConfigErrors(configInfos, callback)) { return; } final boolean created; if (configState.contains(connName)) { if (!allowReplace) { callback.onCompletion(new AlreadyExistsException("Connector " + connName + " already exists"), null); return; } worker.stopAndAwaitConnector(connName); created = false; } else { created = true; } configBackingStore.putConnectorConfig(connName, config); Callback<TargetState> onStart = new Callback<TargetState>() { @Override public void onCompletion(Throwable error, TargetState result) { if (error != null) { callback.onCompletion(error, null); return; } <START> requestExecutorService.submit(new Runnable() { <END> @Override public void run() { synchronized (this) { updateConnectorTasks(connName); } callback.onCompletion(null, new Created<>(created, createConnectorInfo(connName))); } }); } }; startConnector(connName, onStart); } catch (Throwable t) { callback.onCompletion(t, null); } }</code><technical_language>I this is worth backporting AK 2.0, back. that, suggest lambda notation a new Runnable is needed avoid Runnable declaration boilerplate</technical_language>

Target:
private synchronized void putConnectorConfig(String connName, final Map<String, String> config, boolean allowReplace, final Callback<Created<ConnectorInfo>> callback, ConfigInfos configInfos) { try { if (maybeAddConfigErrors(configInfos, callback)) { return; } final boolean created; if (configState.contains(connName)) { if (!allowReplace) { callback.onCompletion(new AlreadyExistsException("Connector " + connName + " already exists"), null); return; } worker.stopAndAwaitConnector(connName); created = false; } else { created = true; } configBackingStore.putConnectorConfig(connName, config); startConnector(connName, (error, result) -> { if (error != null) { callback.onCompletion(error, null); return; } requestExecutorService.submit(() -> { updateConnectorTasks(connName); callback.onCompletion(null, new Created<>(created, createConnectorInfo(connName))); }); }); } catch (Throwable t) { callback.onCompletion(t, null); } }
Source:
<code>private HTMLPageUrl getHtmlPageAsset(final PageContext context, final Host host, final HttpServletRequest request) throws DotDataException, DotSecurityException { HTMLPageUrl htmlPageUrl = null; for (final SearchPageFunction pageSearcher : pageSearchers) { final Optional<HTMLPageUrl> optional = pageSearcher.search(context, host, request); if (optional.isPresent()) { htmlPageUrl = optional.get(); break; } } if(htmlPageUrl == null ){ <START> throw new HTMLPageAssetNotFoundException(context.getPageUri()); <END> } checkPagePermission(context, htmlPageUrl.htmlPage); return htmlPageUrl; }</code><technical_language>Log.debug warning</technical_language>

Target:
private HTMLPageUrl getHtmlPageAsset(final PageContext context, final Host host, final HttpServletRequest request) throws DotDataException, DotSecurityException { Optional<HTMLPageUrl> htmlPageUrlOptional = findPageByContext(host, context); if (!htmlPageUrlOptional.isPresent()) { htmlPageUrlOptional = findByURLMap(context, host, request); } if(!htmlPageUrlOptional.isPresent()){ throw new HTMLPageAssetNotFoundException(context.getPageUri()); } final HTMLPageUrl htmlPageUrl = htmlPageUrlOptional.get(); checkPagePermission(context, htmlPageUrl.htmlPage); return htmlPageUrl; }
Source:
<code>protected FreeIpaDownscaleContext createFlowContext(FlowParameters flowParameters, StateContext<DownscaleState, DownscaleFlowEvent> stateContext, P payload) { Stack stack = stackService.getByIdWithListsInTransaction(payload.getResourceId()); MDCBuilder.buildMdcContext(stack); Location location = location(region(stack.getRegion())); CloudContext cloudContext = new CloudContext(stack.getId(), stack.getName(), stack.getCloudPlatform(), stack.getCloudPlatform(), location, stack.getOwner(), stack.getOwner(), stack.getAccountId()); CloudCredential cloudCredential = credentialConverter.convert(credentialService.getCredentialByEnvCrn(stack.getEnvironmentCrn())); CloudStack cloudStack = cloudStackConverter.convert(stack); Map<Object, Object> variables = stateContext.getExtendedState().getVariables(); <START> List<String> instanceIds = extractInstanceIds(payload, variables); String operationId = extractOperationId(payload, variables); <END> FreeIpa freeIpa = freeIpaService.findByStackId(stack.getId()); List<String> hosts = getHosts(stack, instanceIds, variables); return new FreeIpaDownscaleContext(flowParameters, stack, cloudContext, cloudCredential, cloudStack, instanceIds, freeIpa, operationId, hosts); }</code><technical_language>I misused a bit this variables. like, if need multiple times in state, put here, get later. set it, in state/action. set in action, do adding this logic context building, loosing purpose. if do this in "step", to, avoid instanceof</technical_language>

Target:
protected StackContext createFlowContext(FlowParameters flowParameters, StateContext<DownscaleState, DownscaleFlowEvent> stateContext, P payload) { Stack stack = stackService.getByIdWithListsInTransaction(payload.getResourceId()); MDCBuilder.buildMdcContext(stack); Location location = location(region(stack.getRegion())); CloudContext cloudContext = new CloudContext(stack.getId(), stack.getName(), stack.getCloudPlatform(), stack.getCloudPlatform(), location, stack.getOwner(), stack.getOwner(), stack.getAccountId()); CloudCredential cloudCredential = credentialConverter.convert(credentialService.getCredentialByEnvCrn(stack.getEnvironmentCrn())); CloudStack cloudStack = cloudStackConverter.convert(stack); return new StackContext(flowParameters, stack, cloudContext, cloudCredential, cloudStack); }
Source:
<code>public void testCopyScriptsInTargetDirectory() throws IOException { File f = new File(this.folder.newFolder(), "toto.properties"); Utils.writeStringInto( "id: tid\nprop: value\nhandler: h", f ); TestApplicationTemplate appT = new TestApplicationTemplate(); Utils.writeStringInto( "#!/bin/bash\necho Bonjour le monde cruel > toto.txt", new File( f.getParentFile(), "toto.sh" )); Utils.writeStringInto( "#!/bin/bash\necho touch toto.txt", new File( f.getParentFile(), "titi-script.py" )); File targetDir = new File( this.configurationMngr.getWorkingDirectory(), ConfigurationUtils.TARGETS + "/tid" ); Assert.assertFalse( targetDir.exists()); String targetId = this.mngr.createTarget( f, appT ); Assert.assertEquals( "tid", targetId ); Assert.assertTrue( targetDir.exists()); Assert.assertEquals( 4, targetDir.list().length); File toto = new File( targetDir, "toto.sh"); <START> File titi = new File( targetDir, "titi-script.py"); <END> Assert.assertTrue(toto.exists()); Assert.assertTrue(titi.exists()); }</code><technical_language>OK, wrote a test. test is false. :laughing: **titi-script.py** copied. write a test target properties, set of scripts script</technical_language>

Target:
public void testCopyScriptsInTargetDirectory() throws IOException { File f = new File(this.folder.newFolder(), "toto.properties"); Utils.writeStringInto( "id: tid\nprop: value\nhandler: h", f ); TestApplicationTemplate appT = new TestApplicationTemplate(); Utils.writeStringInto( "#!/bin/bash\necho Bonjour le monde cruel > toto.txt", new File( f.getParentFile(), "toto.sh" )); Utils.writeStringInto( "#!/bin/bash\ntouch titi.txt", new File( f.getParentFile(), "titi.sh" )); Utils.writeStringInto( "#!/bin/bash\necho tototo", new File( f.getParentFile(), "toto-script.sh" )); File targetDir = new File( this.configurationMngr.getWorkingDirectory(), ConfigurationUtils.TARGETS + "/tid" ); Assert.assertFalse( targetDir.exists()); String targetId = this.mngr.createTarget( f, appT ); Assert.assertEquals( "tid", targetId ); Assert.assertTrue( targetDir.exists()); Assert.assertEquals( 4, targetDir.list().length); File toto = new File( targetDir, "toto.sh"); File titi = new File( targetDir, "titi.sh"); File totoMain = new File( targetDir, "toto-script.sh"); Assert.assertTrue(toto.exists()); Assert.assertFalse(titi.exists()); Assert.assertTrue(totoMain.exists()); }
Source:
<code>static BearerTokenCredential parseBearerTokenType(ConfigurationXMLStreamReader reader) throws ConfigXMLParseException { final int attributeCount = reader.getAttributeCount(); String value = null; <START> for (int i = 0; i < attributeCount; i ++) { <END> checkAttributeNamespace(reader, i); switch (reader.getAttributeLocalName(i)) { case "value": { if (value != null) throw reader.unexpectedAttribute(i); value = reader.getAttributeValue(i); break; } default: } } if (value == null) { throw missingAttribute(reader, "value"); } while (reader.hasNext()) { final int tag = reader.nextTag(); if (tag == START_ELEMENT) { throw reader.unexpectedElement(); } else if (tag == END_ELEMENT) { return new BearerTokenCredential(value); } else { throw reader.unexpectedContent(); } } throw reader.unexpectedDocumentEnd(); }</code><technical_language>change this, for future reference, a "requireSingleAttribute" method this work for you</technical_language>

Target:
static BearerTokenCredential parseBearerTokenType(ConfigurationXMLStreamReader reader) throws ConfigXMLParseException { String value = requireSingleAttribute(reader, "value"); while (reader.hasNext()) { final int tag = reader.nextTag(); if (tag == START_ELEMENT) { throw reader.unexpectedElement(); } else if (tag == END_ELEMENT) { return new BearerTokenCredential(value); } else { throw reader.unexpectedContent(); } } throw reader.unexpectedDocumentEnd(); }
Source:
<code>public SubscriptionInfo(final int version, final int latestSupportedVersion, final UUID processId, final Set<TaskId> prevTasks, final Set<TaskId> standbyTasks, final String userEndPoint) { validateVersions(version, latestSupportedVersion); final SubscriptionInfoData data = new SubscriptionInfoData(); data.setVersion(version); if (version >= 3) { data.setLatestSupportedVersion(latestSupportedVersion); } data.setProcessId(processId); data.setPrevTasks(prevTasks.stream().map(t -> { final SubscriptionInfoData.TaskId taskId = new SubscriptionInfoData.TaskId(); taskId.setTopicGroupId(t.topicGroupId); taskId.setPartition(t.partition); return taskId; }).collect(Collectors.toList())); data.setStandbyTasks(standbyTasks.stream().map(t -> { final SubscriptionInfoData.TaskId taskId = new SubscriptionInfoData.TaskId(); taskId.setTopicGroupId(t.topicGroupId); taskId.setPartition(t.partition); return taskId; }).collect(Collectors.toList())); <START> if (version >= 2) { <END> data.setUserEndPoint(userEndPoint == null ? new byte[0] : userEndPoint.getBytes(StandardCharsets.UTF_8)); } this.data = data; }</code><technical_language>nit: move this if statement below/above version check line 62</technical_language>

Target:
public SubscriptionInfo(final int version, final int latestSupportedVersion, final UUID processId, final Set<TaskId> prevTasks, final Set<TaskId> standbyTasks, final String userEndPoint) { validateVersions(version, latestSupportedVersion); final SubscriptionInfoData data = new SubscriptionInfoData(); data.setVersion(version); if (version >= 2) { data.setUserEndPoint(userEndPoint == null ? new byte[0] : userEndPoint.getBytes(StandardCharsets.UTF_8)); } if (version >= 3) { data.setLatestSupportedVersion(latestSupportedVersion); } data.setProcessId(processId); data.setPrevTasks(prevTasks.stream().map(t -> { final SubscriptionInfoData.TaskId taskId = new SubscriptionInfoData.TaskId(); taskId.setTopicGroupId(t.topicGroupId); taskId.setPartition(t.partition); return taskId; }).collect(Collectors.toList())); data.setStandbyTasks(standbyTasks.stream().map(t -> { final SubscriptionInfoData.TaskId taskId = new SubscriptionInfoData.TaskId(); taskId.setTopicGroupId(t.topicGroupId); taskId.setPartition(t.partition); return taskId; }).collect(Collectors.toList())); this.data = data; }
Source:
<code>void populate(final int row, final PluginInfo plugin) { <START> CheckBox checkBox = new CheckBox(); <END> table.setWidget(row, 1, checkBox); table.setText(row, 2, plugin.name()); table.setText(row, 3, plugin.version()); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(row, 1, Gerrit.RESOURCES.css().iconCell()); fmt.addStyleName(row, 2, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 3, Gerrit.RESOURCES.css().dataCell()); setRowItem(row, plugin); }</code><technical_language>checkbox do</technical_language>

Target:
void populate(final int row, final PluginInfo plugin) { table.setText(row, 1, plugin.name()); table.setText(row, 2, plugin.version()); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(row, 1, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 2, Gerrit.RESOURCES.css().dataCell()); setRowItem(row, plugin); }
Source:
<code>public Object[] getNodes() { List<EObject> nodes = new ArrayList<>(); <START> metaModelAdapter = ExtensionPointHelper.getTraceMetamodelAdapter().get(); <END> if (currentSelection.get(0) instanceof EObject) { EObject object = (EObject) currentSelection.get(0); connections = metaModelAdapter.getTransitivelyConnectedElements(object, traceModel); for (Connection c : connections) { nodes.add(c.getOrigin()); nodes.addAll(c.getTargets()); } } return nodes.stream().distinct().collect(Collectors.toList()).toArray(); }</code><technical_language>metaModelAdapter extenion point if set constructor? in getAdjacentNodes(Object)</technical_language>

Target:
public Object[] getNodes() { List<EObject> nodes = new ArrayList<>(); if (currentSelection.get(0) instanceof EObject) { EObject object = (EObject) currentSelection.get(0); connections = metaModelAdapter.getTransitivelyConnectedElements(object, traceModel); for (Connection c : connections) { nodes.add(c.getOrigin()); nodes.addAll(c.getTargets()); } } return nodes.stream().distinct().collect(Collectors.toList()).toArray(); }
Source:
<code>public static String combine(String head, List<ParametersSet> params) { <START> StringBuilder combined_params = new StringBuilder(""); <END> if (params != null) { for (ParametersSet ps : params) { for (Parameter param : ps.getParameters()) { combined_params.append(String.format(MATRIX_PARAMETER_TEMPLATE, param.getName(), param.getValue())); } } } combined_params.insert(0, head); return combined_params.toString(); }</code><technical_language>empty string in constructor is redundant</technical_language>

Target:
public static String combine(String head, List<ParametersSet> params) { StringBuilder combined_params = new StringBuilder(); if (params != null) { for (ParametersSet ps : params) { for (Parameter param : ps.getParameters()) { combined_params.append(String.format(MATRIX_PARAMETER_TEMPLATE, param.getName(), param.getValue())); } } } combined_params.insert(0, head); return combined_params.toString(); }
Source:
<code>public void testAssignment() throws ParseException { <START> final String net_id = "assistant1"; <END> final String password = "assistant1"; final AssignmentView view = openLoginScreen() .login(net_id, password) .listAssistingCourses() .get(0).click() .listGroups() .get(0).click() .toAssignmentView() .listAssignments() .get(0).click(); final AssignmentView.Assignment assignment = view.getAssignment(); assertEquals("Student Two", assignment.getAuthor()); }</code><technical_language>Please store values in a static variable, ASSISTANT_USERNAME :smile:</technical_language>

Target:
public void testAssignment() throws ParseException { final AssignmentView view = openLoginScreen() .login(ASSISTANT_USERNAME, ASSISTANT_PASSWORD) .listAssistingCourses() .get(0).click() .listGroups() .get(0).click() .toAssignmentView() .listAssignments() .get(1).click(); final CourseEdition course = courseEditions.find(1); final Group group = groups.find(course).get(0); final Delivery modelDelivery = deliveries.find(group,2L); final Assignment modelAssignment = modelDelivery.getAssignment(); final AssignmentView.Assignment viewAssignment = view.getAssignment(); assertEquals(modelDelivery.getCreatedUser().getName(), viewAssignment.getAuthor()); assertEquals(modelAssignment.getName(), viewAssignment.getName()); assertEquals(modelDelivery.getState(), viewAssignment.getStatus()); }
Source:
<code>public void flush() throws IOException { <START> if (getDepth() == 0 && (localsLocked || lstAppendEnabled)) <END> { unsafeFlush(); } }</code><technical_language>I !user.hasAnnotations() check in here</technical_language>

Target:
public void flush() throws IOException { if (getDepth() == 0 && !user.hasAnnotations() && (localsLocked || lstAppendEnabled)) { unsafeFlush(); } }
Source:
<code>public InvokeFuture<EhcacheEntityResponse> invokeAsync(EhcacheEntityMessage message, boolean replicate) throws MessageCodecException { InvokeFuture<EhcacheEntityResponse> invoke; <START> if (clientId == null) { <END> throw new IllegalStateException("Client ID cannot be null"); } if (replicate) { message.setId(sequenceGenerator.getAndIncrement()); invoke = endpoint.beginInvoke().message(message).replicate(true).invoke(); } else { invoke = endpoint.beginInvoke().message(message).replicate(false).invoke(); } return invoke; }</code><technical_language>Simply getId() duplicate validation logic</technical_language>

Target:
public InvokeFuture<EhcacheEntityResponse> invokeAsync(EhcacheEntityMessage message, boolean replicate) throws MessageCodecException { InvokeFuture<EhcacheEntityResponse> invoke; getClientId(); if (replicate) { message.setId(sequenceGenerator.getAndIncrement()); } return endpoint.beginInvoke().message(message).replicate(replicate).invoke(); }
Source:
<code>public void shouldFailVerificationOnMethodArgument() throws Exception { mock.clear(); mock.add("foo"); verify(mock).clear(); try { verify(mock).add("bar"); <START> } catch (AssertionError expected) { <END> return; } fail(); }</code><technical_language>Empty catch again? :) AssertJ suppress work for I think</technical_language>

Target:
public void shouldFailVerificationOnMethodArgument() throws Exception { mock.clear(); mock.add("foo"); verify(mock).clear(); assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() { verify(mock).add("bar"); } }).isInstanceOf(ArgumentsAreDifferent.class); }
Source:
<code>protected void encode(ChannelHandlerContext ctx, OnDemandResponse response, ByteBuf buf) { int fs = response.getFs(); int folder = response.getFolder(); ByteBuf container = response.getChunkData(); buf.writeByte(fs); buf.writeShort(folder); int compression = container.readUnsignedByte(); if (response.getPriority() == OnDemandRequest.Priority.LOW) { <START> compression |= 0x80; <END> } buf.writeByte(compression); int bytes = container.readableBytes(); if (bytes > 508) bytes = 508; buf.writeBytes(container.readBytes(bytes)); for (; ; ) { bytes = container.readableBytes(); if (bytes == 0) { break; } else if (bytes > 511) bytes = 511; buf.writeByte(0xFF); final var payload = container.readBytes(bytes); buf.writeBytes(payload); payload.release(); } }</code><technical_language>magic numbers need (including 508, 511 below)</technical_language>

Target:
protected void encode(ChannelHandlerContext ctx, OnDemandResponse response, ByteBuf buf) { int fs = response.getFs(); int folder = response.getFolder(); ByteBuf container = response.getChunkData(); buf.writeByte(fs); buf.writeShort(folder); int compression = container.readUnsignedByte(); if (response.getPriority() == OnDemandRequest.Priority.LOW) { compression |= PREFTECH; } buf.writeByte(compression); buf.writeBytes(container.readBytes(Math.min(ENTRY_PAYLOAD_START, container.readableBytes()))); int bytes; while ((bytes = Math.min(ENTRY_PAYLOAD, container.readableBytes())) != 0) { buf.writeByte(ENTRY_DELIMITER); final var payload = container.readBytes(bytes); buf.writeBytes(payload); payload.release(); } }
Source:
<code>protected void assertL1GetWithConcurrentUpdate(final Cache<Object, String> nonOwnerCache, Cache<Object, String> ownerCache, final Object key, String originalValue, String updateValue) throws InterruptedException, ExecutionException, TimeoutException, BrokenBarrierException { CyclicBarrier barrier = new CyclicBarrier(2); addBlockingInterceptorBeforeTx(nonOwnerCache, barrier, GetKeyValueCommand.class); try { Future<String> future = nonOwnerCache.getAsync(key); barrier.await(1, TimeUnit.SECONDS); assertEquals(originalValue, ownerCache.put(key, updateValue)); <START> asyncWait(key, PutKeyValueCommand.class, ownerCache); <END> barrier.await(); assertEquals(originalValue, future.get(1, TimeUnit.SECONDS)); removeAllBlockingInterceptorsFromCache(nonOwnerCache); assertIsNotInL1(nonOwnerCache, key); assertEquals(updateValue, nonOwnerCache.get(key)); assertIsInL1(nonOwnerCache, key); } finally { removeAllBlockingInterceptorsFromCache(nonOwnerCache); } }</code><technical_language>removed this method, do anything..</technical_language>

Target:
protected void assertL1GetWithConcurrentUpdate(final Cache<Object, String> nonOwnerCache, Cache<Object, String> ownerCache, final Object key, String originalValue, String updateValue) throws InterruptedException, ExecutionException, TimeoutException, BrokenBarrierException { CyclicBarrier barrier = new CyclicBarrier(2); addBlockingInterceptorBeforeTx(nonOwnerCache, barrier, GetKeyValueCommand.class); try { Future<String> future = nonOwnerCache.getAsync(key); barrier.await(5, TimeUnit.SECONDS); assertEquals(originalValue, ownerCache.put(key, updateValue)); barrier.await(5, TimeUnit.SECONDS); assertEquals(originalValue, future.get(5, TimeUnit.SECONDS)); removeAllBlockingInterceptorsFromCache(nonOwnerCache); assertIsNotInL1(nonOwnerCache, key); assertEquals(updateValue, nonOwnerCache.get(key)); assertIsInL1(nonOwnerCache, key); } finally { removeAllBlockingInterceptorsFromCache(nonOwnerCache); } }