auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void assertEmptyCommit(String projectName, String... refs) throws RepositoryNotFoundException, IOException { Repository repo = git.openRepository(new Project.NameKey(projectName)); RevWalk rw = new RevWalk(repo); try { for (String ref : refs) { RevCommit commit = rw.lookupCommit(repo.getRef(ref).getObjectId()); rw.parseBody(commit); <START> assertEquals("Initial empty repository\n", commit.getFullMessage()); <END> } } finally { rw.release(); repo.close(); } }</code><technical_language>this asserts this commit this commit message tree is empty. check commit tree verify is empty of change method name like: assertCommitMessage</technical_language>

Target:
private void assertEmptyCommit(String projectName, String... refs) throws RepositoryNotFoundException, IOException { Repository repo = git.openRepository(new Project.NameKey(projectName)); RevWalk rw = new RevWalk(repo); TreeWalk tw = new TreeWalk(repo); try { for (String ref : refs) { RevCommit commit = rw.lookupCommit(repo.getRef(ref).getObjectId()); rw.parseBody(commit); tw.addTree(commit.getTree()); assertFalse("ref " + ref + " has non empty commit", tw.next()); tw.reset(); } } finally { tw.release(); rw.release(); repo.close(); } }
Source:
<code><START> public DelimitedStreamReader(InputStream stream, Charset charset, int bufferSize) { <END> this.inputStream = stream; this.charset = charset; this.strBuffer = new byte[bufferSize * 2]; buffer = new byte[bufferSize]; offset = 0; end = 0; }</code><technical_language>add some Preconditions null</technical_language>

Target:
public DelimitedStreamReader(InputStream stream, Charset charset, int bufferSize) { Preconditions.checkArgument(bufferSize > 0); this.inputStream = Preconditions.checkNotNull(stream); this.charset = Preconditions.checkNotNull(charset); this.strBuffer = new byte[bufferSize * 2]; buffer = new byte[bufferSize]; offset = 0; end = 0; }
Source:
<code>public boolean shouldAlertUpgrade(ArrayList<RpmVersion> isos, Version hostOs) { boolean alert = false; for (RpmVersion iso: isos) { <START> if (iso.compareTo(hostOs) > 0) { <END> alert = true; break; } } return alert; }</code><technical_language>do compare major version</technical_language>

Target:
public boolean shouldAlertUpgrade(ArrayList<RpmVersion> isos, Version hostOs) { boolean alert = false; for (RpmVersion iso: isos) { if (iso.getMajor() == hostOs.getMajor() && iso.compareTo(hostOs) != 0) { alert = true; break; } } return alert; }
Source:
<code>private static void setupHdfs(String hadoopPrefix, String testDir, int numMappers, int numPerMapper) throws IllegalArgumentException, IOException { Configuration config = new Configuration(); config.addResource(new Path(hadoopPrefix+"/conf/core-site.xml")); config.addResource(new Path(hadoopPrefix+"/conf/hdfs-site.xml")); <START> try (FileSystem hdfs = FileSystem.get(config)) { <END> String inputDir = testDir + "/input"; hdfs.mkdirs(new Path(inputDir)); FSDataOutputStream fos = hdfs.create(new Path(inputDir + "/data")); for (int i = 0; i < numMappers; i++) { fos.writeUTF(Integer.toString(numPerMapper) + "\n"); } fos.close(); } }</code><technical_language>closing FileSystem object... if shared threads, impact other threads... matter for this case</technical_language>

Target:
private static void setupHdfs(String hadoopPrefix, String testDir, int numMappers, int numPerMapper) throws IllegalArgumentException, IOException { Configuration config = new Configuration(); config.addResource(new Path(hadoopPrefix+"/conf/core-site.xml")); config.addResource(new Path(hadoopPrefix+"/conf/hdfs-site.xml")); @SuppressWarnings("resource") FileSystem hdfs = FileSystem.get(config); String inputDir = testDir+"/input"; hdfs.mkdirs(new Path(inputDir)); try (FSDataOutputStream fos = hdfs.create(new Path(inputDir + "/data"))) { for (int i = 0; i < numMappers; i++) { fos.writeUTF(Integer.toString(numPerMapper) + "\n"); } } }
Source:
<code>private List<Entry> verifyFlowResponse(CompletableFuture<Event> response) throws OdataMetadataEntityNotFoundException, OdataMetadataFieldsException, OdataMetadataResourceNotFound, OdataMetadataFormatException, ODataInvalidFlowResponseException, ClientErrorException { try { CoreEvent event; event = (CoreEvent) response.get(); OdataMetadataManager metadataManager = getMetadataManager(); EntityDefinition entityDefinition = metadataManager.getEntityByName(entity); List<Entry> entries; String payload = CoreEventUtils.getPayloadAsString(event); <START> if(payload != null || payload != "") { <END> entries = Helper.transformJsonToEntryList(payload); } else { throw new ODataInvalidFlowResponseException("The payload of the response should be a valid json."); } int entryNumber = 1; for (Entry entry : entries) { if (entry.getProperties().entrySet().size() > entityDefinition.getProperties().size()) throw new ODataInvalidFlowResponseException("There are absent properties in flow response (entry #" + (entryNumber++) + ")"); for (String propertyName : entry.getProperties().keySet()) { EntityDefinitionProperty entityDefinitionProperty = entityDefinition.findPropertyDefinition(propertyName); if (entityDefinitionProperty == null) throw new ODataInvalidFlowResponseException("Property '" + propertyName + "' was not expected for entity '" + entityDefinition.getName() + "'"); } } return entries; } catch (InterruptedException | ExecutionException e) { throw new ODataInvalidFlowResponseException(e.getMessage()); } }</code><technical_language>In previous version, returning empty list payload is null, throwing exception</technical_language>

Target:
private List<Entry> verifyFlowResponse(CompletableFuture<Event> response) throws OdataMetadataEntityNotFoundException, OdataMetadataFieldsException, OdataMetadataResourceNotFound, OdataMetadataFormatException, ODataInvalidFlowResponseException, ClientErrorException { try { CoreEvent event; event = (CoreEvent) response.get(); OdataMetadataManager metadataManager = getMetadataManager(); EntityDefinition entityDefinition = metadataManager.getEntityByName(entity); List<Entry> entries; String payload = CoreEventUtils.getPayloadAsString(event); if(payload == null || payload == "") throw new ODataInvalidFlowResponseException("The payload of the response should be a valid json."); entries = Helper.transformJsonToEntryList(payload); int entryNumber = 1; for (Entry entry : entries) { if (entry.getProperties().entrySet().size() > entityDefinition.getProperties().size()) throw new ODataInvalidFlowResponseException("There are absent properties in flow response (entry #" + (entryNumber++) + ")"); for (String propertyName : entry.getProperties().keySet()) { EntityDefinitionProperty entityDefinitionProperty = entityDefinition.findPropertyDefinition(propertyName); if (entityDefinitionProperty == null) throw new ODataInvalidFlowResponseException("Property '" + propertyName + "' was not expected for entity '" + entityDefinition.getName() + "'"); } } return entries; } catch (InterruptedException | ExecutionException e) { throw new ODataInvalidFlowResponseException(e.getMessage()); } }
Source:
<code>protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) throws IOException { DeleteExpiredDataAction.Request request; if (restRequest.hasContent()) { request = DeleteExpiredDataAction.Request.PARSER.apply(restRequest.contentParser(), null); } else { request = new DeleteExpiredDataAction.Request(); String perSecondParam = restRequest.param(DeleteExpiredDataAction.Request.REQUESTS_PER_SECOND.getPreferredName()); if (perSecondParam != null) { try { request.setRequestsPerSecond(Float.parseFloat(perSecondParam)); } catch (NumberFormatException e) { throw new IllegalArgumentException("Failed to parse float parameter [" + DeleteExpiredDataAction.Request.REQUESTS_PER_SECOND.getPreferredName() + "] with value [" + perSecondParam + "]", e); } } String timeoutParam = restRequest.param(DeleteExpiredDataAction.Request.TIMEOUT.getPreferredName()); if (timeoutParam != null) { request.setTimeout(restRequest.paramAsTime(timeoutParam, null)); } } <START> String jobId = restRequest.param(Fields.JOB_ID.getPreferredName()); <END> if (Strings.isNullOrEmpty(jobId) == false) { request.setJobId(jobId); } return channel -> client.execute(DeleteExpiredDataAction.INSTANCE, request, new RestToXContentListener<>(channel)); }</code><technical_language>This pull in field name Job config object. data frame analytics fields</technical_language>

Target:
protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) throws IOException { DeleteExpiredDataAction.Request request; if (restRequest.hasContent()) { request = DeleteExpiredDataAction.Request.PARSER.apply(restRequest.contentParser(), null); } else { request = new DeleteExpiredDataAction.Request(); String perSecondParam = restRequest.param(DeleteExpiredDataAction.Request.REQUESTS_PER_SECOND.getPreferredName()); if (perSecondParam != null) { try { request.setRequestsPerSecond(Float.parseFloat(perSecondParam)); } catch (NumberFormatException e) { throw new IllegalArgumentException("Failed to parse float parameter [" + DeleteExpiredDataAction.Request.REQUESTS_PER_SECOND.getPreferredName() + "] with value [" + perSecondParam + "]", e); } } String timeoutParam = restRequest.param(DeleteExpiredDataAction.Request.TIMEOUT.getPreferredName()); if (timeoutParam != null) { request.setTimeout(restRequest.paramAsTime(timeoutParam, null)); } } String jobId = restRequest.param(Job.ID.getPreferredName()); if (Strings.isNullOrEmpty(jobId) == false) { request.setJobId(jobId); } return channel -> client.execute(DeleteExpiredDataAction.INSTANCE, request, new RestToXContentListener<>(channel)); }
Source:
<code>private static TableDefinition partitionedTableWithVariablePartitionsDefinition() { <START> String tableName = "partitioned_table_with_too_many_partitions"; <END> String createTableDdl = "CREATE TABLE %NAME%(col INT) " + "PARTITIONED BY (part_col INT) " + "STORED AS ORC"; return HiveTableDefinition.builder(tableName) .setCreateTableDDLTemplate(createTableDdl) .setNoData() .build(); }</code><technical_language>nice partition this table columns</technical_language>

Target:
private static TableDefinition partitionedTableWithVariablePartitionsDefinition() { String createTableDdl = "CREATE TABLE %NAME%(col INT) " + "PARTITIONED BY (part_col INT) " + "STORED AS ORC"; return HiveTableDefinition.builder(PARTITIONED_TABLE_WITH_VARIABLE_PARTITIONS) .setCreateTableDDLTemplate(createTableDdl) .setNoData() .build(); }
Source:
<code>public synchronized boolean isCovered(IResource resource, int depth) { IPath fullPath = resource.getFullPath(); for (Object element : deepFolders) { <START> IResource deepFolder = (IResource) element; <END> if (deepFolder.getFullPath().isPrefixOf(fullPath)) { return true; } } if (resource.getType() == IResource.FILE) { return (shallowFolders.contains(resource.getParent()) || files.contains(resource)); } switch (depth) { case IResource.DEPTH_ONE: return (shallowFolders.contains(resource)); case IResource.DEPTH_ZERO: return (shallowFolders.contains(resource.getParent()) || zeroFolders.contains(resource)); } return false; }</code><technical_language>loop var; collections typed for other changes in this file</technical_language>

Target:
public synchronized boolean isCovered(IResource resource, int depth) { IPath fullPath = resource.getFullPath(); for (IResource deepFolder : deepFolders) { if (deepFolder.getFullPath().isPrefixOf(fullPath)) { return true; } } if (resource.getType() == IResource.FILE) { return (shallowFolders.contains(resource.getParent()) || files.contains(resource)); } switch (depth) { case IResource.DEPTH_ONE: return (shallowFolders.contains(resource)); case IResource.DEPTH_ZERO: return (shallowFolders.contains(resource.getParent()) || zeroFolders.contains(resource)); } return false; }
Source:
<code>void setBackgroundColor (long context, long handle, GdkRGBA rgba) { if (OS.GTK_VERSION >= OS.VERSION(3, 16, 0)) { String cssRGBA = rgba != null ? display.gtk_rgba_to_css_string (rgba) : "rgba(0,0,0,0)"; background = rgba; String name = OS.GTK_VERSION >= OS.VERSION(3, 20, 0) ? "notebook header" : "GtkNotebook"; String css = name + " {background-color: " + cssRGBA + ";}"; <START> System.out.println(css); <END> cssBackground = css; String finalCss = display.gtk_css_create_css_color_string (cssBackground, cssForeground, SWT.BACKGROUND); gtk_css_provider_load_from_css (context, finalCss); } else { OS.gtk_widget_override_background_color (handle, OS.GTK_STATE_FLAG_NORMAL, rgba); } }</code><technical_language>remove</technical_language>

Target:
void setBackgroundColor (long context, long handle, GdkRGBA rgba) { if (OS.GTK_VERSION >= OS.VERSION(3, 16, 0)) { String cssRGBA = rgba != null ? display.gtk_rgba_to_css_string (rgba) : "rgba(0,0,0,0)"; background = rgba; String name = OS.GTK_VERSION >= OS.VERSION(3, 20, 0) ? "notebook header" : "GtkNotebook"; String css = name + " {background-color: " + cssRGBA + ";}"; cssBackground = css; String finalCss = display.gtk_css_create_css_color_string (cssBackground, cssForeground, SWT.BACKGROUND); gtk_css_provider_load_from_css (context, finalCss); } else { OS.gtk_widget_override_background_color (handle, OS.GTK_STATE_FLAG_NORMAL, rgba); } }
Source:
<code>public void scenario1() throws IOException { final String testObj = ingestObj("/rest/webacl_box1"); final String acl1 = ingestAcl("fedoraAdmin", "/acls/01/acl.ttl", "/acls/01/authorization.ttl"); linkToAcl(testObj, acl1); final String aclLink = Link.fromUri(acl1).rel("acl").build().toString(); logger.debug("Anonymous can't read"); final HttpGet request = getObjMethod(testObj.replace(serverAddress, "")); assertEquals(HttpStatus.SC_FORBIDDEN, getStatus(request)); logger.debug("Can username 'smith123' read " + testObj); setAuth(request, "smith123"); try (final CloseableHttpResponse response = execute(request)) { assertEquals(HttpStatus.SC_OK, getStatus(response)); final Optional<String> header = Arrays.asList(response.getHeaders("Link")).stream().map(Header::getValue) .filter(aclLink::equals).findFirst(); assertTrue("Missing Link header", header.isPresent()); } logger.debug("Can username 'smith123' read a child of {}", testObj); final String childObj = ingestObj("/rest/webacl_box1/child"); final HttpGet getReq = getObjMethod(childObj.replace(serverAddress, "")); setAuth(getReq, "smith123"); try (final CloseableHttpResponse response = execute(getReq)) { assertEquals(HttpStatus.SC_OK, getStatus(response)); <START> final Optional<String> header = Arrays.asList(response.getHeaders("Link")).stream().map(Header::getValue) <END> .filter(aclLink::equals).findFirst(); assertTrue("Missing Link header to ACL on parent", header.isPresent()); } }</code><technical_language>Arrays::stream, consider static importing it</technical_language>

Target:
public void scenario1() throws IOException { final String testObj = ingestObj("/rest/webacl_box1"); final String acl1 = ingestAcl("fedoraAdmin", "/acls/01/acl.ttl", "/acls/01/authorization.ttl"); linkToAcl(testObj, acl1); final String aclLink = Link.fromUri(acl1).rel("acl").build().toString(); final HttpGet request = getObjMethod(testObj.replace(serverAddress, "")); assertEquals("Anonymous can read " + testObj, HttpStatus.SC_FORBIDDEN, getStatus(request)); setAuth(request, "smith123"); try (final CloseableHttpResponse response = execute(request)) { assertEquals("User 'smith123' can't read" + testObj, HttpStatus.SC_OK, getStatus(response)); final Optional<String> header = stream(response.getHeaders("Link")).map(Header::getValue) .filter(aclLink::equals).findFirst(); assertTrue("Missing Link header", header.isPresent()); } final String childObj = ingestObj("/rest/webacl_box1/child"); final HttpGet getReq = getObjMethod(childObj.replace(serverAddress, "")); setAuth(getReq, "smith123"); try (final CloseableHttpResponse response = execute(getReq)) { assertEquals("User 'smith123' can't read child of " + testObj, HttpStatus.SC_OK, getStatus(response)); final Optional<String> header = stream(response.getHeaders("Link")).map(Header::getValue) .filter(aclLink::equals).findFirst(); assertTrue("Missing Link header to ACL on parent", header.isPresent()); } }
Source:
<code>public void handle_missing_node() throws Exception { doThrow(new NodeCommandException("Exception Message", new IOException())).when(eslintBridgeServerMock).startServerLazily(any()); AnalysisWarnings analysisWarnings = mock(AnalysisWarnings.class); EslintBasedRulesSensor eslintBasedRulesSensor = new EslintBasedRulesSensor(checkFactory(ESLINT_BASED_RULE), eslintBridgeServerMock, analysisWarnings); eslintBasedRulesSensor.execute(context); assertThat(logTester.logs(LoggerLevel.ERROR)).contains("Exception Message"); <START> verify(analysisWarnings).addUnique("Some eslint-based rules were not executed. Exception Message"); <END> }</code><technical_language>correct this way, if node, (not some) eslint-based rules executed</technical_language>

Target:
public void handle_missing_node() throws Exception { doThrow(new NodeCommandException("Exception Message", new IOException())).when(eslintBridgeServerMock).startServerLazily(any()); AnalysisWarnings analysisWarnings = mock(AnalysisWarnings.class); EslintBasedRulesSensor eslintBasedRulesSensor = new EslintBasedRulesSensor(checkFactory(ESLINT_BASED_RULE), eslintBridgeServerMock, analysisWarnings); eslintBasedRulesSensor.execute(context); assertThat(logTester.logs(LoggerLevel.ERROR)).contains("Exception Message"); verify(analysisWarnings).addUnique("Eslint-based rules were not executed. Exception Message"); }
Source:
<code>protected URL retrieve(Channel channel, long sum1, long sum2) throws IOException, InterruptedException { File target = map(sum1, sum2); File parent = target.getParentFile(); parent.mkdirs(); try { File tmp = File.createTempFile(target.getName(),"tmp", parent); try { RemoteOutputStream o = new RemoteOutputStream(new FileOutputStream(tmp)); try { LOGGER.log(Level.FINE, String.format("Retrieving jar file %16X%16X",sum1,sum2)); getJarLoader(channel).writeJarTo(sum1, sum2, o); } finally { o.close(); } tmp.renameTo(target); if (target.exists()) { Checksum expected = new Checksum(sum1, sum2); Checksum actual = Checksum.forFile(target); if (!expected.equals(actual)) { <START> throw new IOException("Checksum of retrieved jar doesn't match: " + target); <END> } return target.toURI().toURL(); } throw new IOException("Unable to create "+target+" from "+tmp); } finally { tmp.delete(); } } catch (IOException e) { throw (IOException)new IOException("Failed to write to "+target).initCause(e); } }</code><technical_language>I suggest including checksums in detail message, for future diagnosis</technical_language>

Target:
protected URL retrieve(Channel channel, long sum1, long sum2) throws IOException, InterruptedException { File target = map(sum1, sum2); File parent = target.getParentFile(); if (target.exists()) { LOGGER.fine(String.format("Jar file already exists: %16X%16X", sum1, sum2)); return target.toURI().toURL(); } parent.mkdirs(); try { File tmp = File.createTempFile(target.getName(),"tmp", parent); try { RemoteOutputStream o = new RemoteOutputStream(new FileOutputStream(tmp)); try { LOGGER.log(Level.FINE, String.format("Retrieving jar file %16X%16X",sum1,sum2)); getJarLoader(channel).writeJarTo(sum1, sum2, o); } finally { o.close(); } Checksum expected = new Checksum(sum1, sum2); Checksum actual = Checksum.forFile(tmp); if (!expected.equals(actual)) { throw new IOException(String.format( "Incorrect checksum of retrieved jar: %s\nExpected: %s\nActual: %s", tmp.getAbsolutePath(), expected, actual)); } if (!tmp.renameTo(target)) { if (!target.exists()) { throw new IOException("Unable to create " + target + " from " + tmp); } actual = Checksum.forFile(target); if (!expected.equals(actual)) { throw new IOException(String.format( "Incorrect checksum of jar: %s\nExpected: %s\nActual: %s", target.getAbsolutePath(), expected, actual)); } } return target.toURI().toURL(); } finally { tmp.delete(); } } catch (IOException e) { throw (IOException)new IOException("Failed to write to "+target).initCause(e); } }
Source:
<code>private SearchOptions parseFilters(String filterJson) { <START> if (filterJson != null && StringUtils.isNotEmpty(filterJson) && !filterJson.equals("{}")) { <END> try { JsonObject jsonObject = (JsonObject) new JsonParser().parse(filterJson); String name = (jsonObject.get(NAME) != null) ? jsonObject.get(NAME).getAsString() : EMPTY_STRING; String email = (jsonObject.get(EMAIL) != null) ? jsonObject.get(EMAIL).getAsString() : EMPTY_STRING; String phone = (jsonObject.get(PHONE) != null) ? jsonObject.get(PHONE).getAsString() : EMPTY_STRING; return SearchOptions.builder().name(name).email(email).phone(phone).build(); } catch (JsonSyntaxException e) { LOGGER.error("Cannot read filters from json", e); } } return SearchOptions.builder().name(EMPTY_STRING).email(EMPTY_STRING).phone(EMPTY_STRING).build(); }</code><technical_language>StringUtils.isNotEmpty contains a nullcheck, need add one</technical_language>

Target:
private SearchOptions parseFilters(String filterJson) { if (StringUtils.isNotEmpty(filterJson) && !filterJson.equals(EMPTY_JSON)) { try { JsonObject jsonObject = (JsonObject) new JsonParser().parse(filterJson); String name = getValueFromJsonObjectByMemberName(jsonObject, NAME); String email = getValueFromJsonObjectByMemberName(jsonObject, EMAIL); String phone = getValueFromJsonObjectByMemberName(jsonObject, PHONE); return SearchOptions.builder().name(name).email(email).phone(phone).build(); } catch (JsonSyntaxException e) { LOGGER.error("Cannot read filters from json", e); } } return SearchOptions.builder().name(StringUtils.EMPTY).email(StringUtils.EMPTY).phone(StringUtils.EMPTY).build(); }
Source:
<code>public static NodeProperty<Node> mkNodeProperty(int number) { switch (number) { case 1: return new NodePropertyOne(); case 2: <START> return new NodePropertyOne(); <END> case 3: return new NodePropertyOne(); default: throw new IllegalArgumentException("Need 1, 2 or 3: Got " + number); } }</code><technical_language>This return implementations</technical_language>

Target:
public static NodeProperty<Node> mkNodeProperty(int number) { switch (number) { case 1: return new NodePropertyOne(); case 2: return new NodePropertyTwo(); case 3: return new NodePropertyThree(); default: throw new IllegalArgumentException("Need 1, 2 or 3: Got " + number); } }
Source:
<code>public void testCommentContentToken() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(IllegalTokenCheck.class); checkConfig.addAttribute("tokens", "COMMENT_CONTENT"); final String path = getPath("InputIllegalTokens.java"); final String lineSeparator; if (new FileText(new File(path), StandardCharsets.UTF_8.name()) .getFullText().chars().anyMatch(character -> character == '\r')) { lineSeparator = "\r\n"; <START> } <END> else { lineSeparator = "\n"; } final String[] expected = { "3:3: " + getCheckMessage(MSG_KEY, JavadocUtil.escapeAllControlChars( "*" + lineSeparator + " * Test for illegal tokens" + lineSeparator + " ")), "31:29: " + getCheckMessage(MSG_KEY, JavadocUtil.escapeAllControlChars( " some comment href" + lineSeparator)), "35:28: " + getCheckMessage(MSG_KEY, JavadocUtil.escapeAllControlChars( " some a href" + lineSeparator)), }; verify(checkConfig, path, expected); }</code><technical_language>new concept, is "\n"(LF), is enforced file ".gitattributes" in repo, in future some validation CI level. need calculation of lineSeparator, "\n" do conversion of string \r\n \n if required</technical_language>

Target:
public void testCommentContentToken() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(IllegalTokenCheck.class); checkConfig.addAttribute("tokens", "COMMENT_CONTENT"); final String path = getPath("InputIllegalTokens.java"); final String lineSeparator = CheckUtil.getLineSeparatorForFile(path, StandardCharsets.UTF_8); final String[] expected = { "3:3: " + getCheckMessage(MSG_KEY, JavadocUtil.escapeAllControlChars( "*" + lineSeparator + " * Test for illegal tokens" + lineSeparator + " ")), "31:29: " + getCheckMessage(MSG_KEY, JavadocUtil.escapeAllControlChars( " some comment href" + lineSeparator)), "35:28: " + getCheckMessage(MSG_KEY, JavadocUtil.escapeAllControlChars( " some a href" + lineSeparator)), }; verify(checkConfig, path, expected); }
Source:
<code>public static DynamicClassLoader getClassLoader(final PName tenantId, final String jarPath) { DynamicClassLoader cl = tenantIdSpecificCls.get(tenantId); String parent = null; if (cl != null) return cl; if(jarPath != null && !jarPath.isEmpty()) { cl = pathSpecificCls.get(jarPath); if (cl != null) return cl; Path path = new Path(jarPath); if(jarPath.endsWith(".jar")) { parent = path.getParent().toString(); } else { parent = path.toString(); } } if (jarPath == null || jarPath.isEmpty() || config.get(DYNAMIC_JARS_DIR_KEY) != null && (parent != null && parent.equals(config.get(DYNAMIC_JARS_DIR_KEY)))) { <START> Lock lock = locker.acquireLock(tenantId.getString()); <END> try { cl = tenantIdSpecificCls.get(tenantId); if (cl == null) { cl = new DynamicClassLoader(config, UDFExpression.class.getClassLoader()); } DynamicClassLoader prev = tenantIdSpecificCls.putIfAbsent(tenantId, cl); if (prev != null) { cl = prev; } return cl; } finally { lock.unlock(); } } else { Lock lock = pathLocker.acquireLock(jarPath); try { cl = pathSpecificCls.get(jarPath); if (cl == null) { Configuration conf = HBaseConfiguration.create(config); conf.set(DYNAMIC_JARS_DIR_KEY, parent); cl = new DynamicClassLoader(conf, UDFExpression.class.getClassLoader()); } DynamicClassLoader prev = pathSpecificCls.putIfAbsent(jarPath, cl); if (prev != null) { cl = prev; } return cl; } finally { lock.unlock(); } } }</code><technical_language>Rajesh says: want clarify map is concurrent map get putifAbsent atomic is a chance get put if other client puts a class loader for tenant classloader configuration object created garbage. locker. If ok I do suggested. do u say? Samarth says: expensive is creating a new classloader config? expensive. I worry creating discarding two. Besides race condition of another thread winning race get() putIfAbsent is likely. sum up, yes, I get rid of KeyLocker altogether</technical_language>

Target:
public static DynamicClassLoader getClassLoader(final PName tenantId, final String jarPath) { DynamicClassLoader cl = tenantIdSpecificCls.get(tenantId); String parent = null; if (cl != null) return cl; if(jarPath != null && !jarPath.isEmpty()) { cl = pathSpecificCls.get(jarPath); if (cl != null) return cl; Path path = new Path(jarPath); if(jarPath.endsWith(".jar")) { parent = path.getParent().toString(); } else { parent = path.toString(); } } if (jarPath == null || jarPath.isEmpty() || config.get(DYNAMIC_JARS_DIR_KEY) != null && (parent != null && parent.equals(config.get(DYNAMIC_JARS_DIR_KEY)))) { cl = tenantIdSpecificCls.get(tenantId); if (cl == null) { cl = new DynamicClassLoader(config, UDFExpression.class.getClassLoader()); } DynamicClassLoader prev = tenantIdSpecificCls.putIfAbsent(tenantId, cl); if (prev != null) { cl = prev; } return cl; } else { cl = pathSpecificCls.get(jarPath); if (cl == null) { Configuration conf = HBaseConfiguration.create(config); conf.set(DYNAMIC_JARS_DIR_KEY, parent); cl = new DynamicClassLoader(conf, UDFExpression.class.getClassLoader()); } DynamicClassLoader prev = pathSpecificCls.putIfAbsent(jarPath, cl); if (prev != null) { cl = prev; } return cl; } }
Source:
<code>public void testDynamicImport() throws Exception { File testData = getTestData("dymamicImport", "testData/dynamicImport"); IInstallableUnit iu = BundlesAction.createBundleIU(BundlesAction.createBundleDescription(testData), null, new PublisherInfo()); Collection<IRequirement> requirements = iu.getRequirements(); for (IRequirement req : requirements) <START> System.out.println("------> " + req); <END> verifyRequirement(requirements, TESTDYN_REQ_EE_FILTER, 0, 1, true); assertEquals(1, requirements.size()); }</code><technical_language>Please remove this debugging sysout</technical_language>

Target:
public void testDynamicImport() throws Exception { File testData = getTestData("dymamicImport", "testData/dynamicImport"); IInstallableUnit iu = BundlesAction.createBundleIU(BundlesAction.createBundleDescription(testData), null, new PublisherInfo()); Collection<IRequirement> requirements = iu.getRequirements(); verifyRequirement(requirements, TESTDYN_REQ_EE_FILTER, 0, 1, true); assertEquals(1, requirements.size()); }
Source:
<code>public String getRecommendationPosition() { <START> return "" <END> + JavaRenameRecommend.result.recommendStartPosition + "," + JavaRenameRecommend.result.recommendOriginalName.length(); }</code><technical_language>return json</technical_language>

Target:
public String getRecommendationPosition() { return "" + JavaRenameRecommend.result.getRecommendStartPosition() + "," + JavaRenameRecommend.result.getRecommendOriginalName().length(); }
Source:
<code>private String readStringUntil(char end) throws IOException { StringBuilder sb = new StringBuilder(); int ch; while ((ch = inputStream.read()) != -1) { if (ch == end) { return sb.toString(); } else { sb.append((char) ch); } } throw new IOException("readStringUntil(): end of stream reached. Read: " <START> + sb.toString() + " while waiting for '"+end+"'"); <END> }</code><technical_language>Code style: operator end of line; missing spaces + operators. of end is \r. want output ASCII code character end is 32. java throw new IOException("readStringUntil(): end of stream reached. " + "Read: \"" + sb.toString() + "\" while waiting for " + formatChar(end)); } private String formatChar(char value) { return < 32 ? "[" + Integer.toString(value) + "]" : "'" + + "'"; }</technical_language>

Target:
private String readStringUntil(char end) throws IOException { StringBuilder sb = new StringBuilder(); int ch; while ((ch = inputStream.read()) != -1) { if (ch == end) { return sb.toString(); } else { sb.append((char) ch); } } throw new IOException("readStringUntil(): end of stream reached. " + "Read: \"" + sb.toString() + "\" while waiting for " + formatChar(end)); }
Source:
<code>protected static void writeProperties(JsonGenerator jg, DocumentModel doc, String schema, ServletRequest request) throws IOException { Collection<Property> properties = doc.getPropertyObjects(schema); if (properties.isEmpty()) { return; } SchemaManager schemaManager = Framework.getService(SchemaManager.class); String prefix = schemaManager.getSchema(schema).getNamespace().prefix; if (prefix == null || prefix.length() == 0) { prefix = schema; } JSONPropertyWriter writer = JSONPropertyWriter.create().writeNull(false).writeEmpty(false).prefix(prefix); if (request != null) { DownloadService downloadService = Framework.getService(DownloadService.class); String blobUrlPrefix = VirtualHostHelper.getBaseURL(request) + downloadService.getDownloadUrl(doc, null, null) + "/"; writer.filesBaseUrl(blobUrlPrefix); } for (Property p : properties) { try { writer.writeProperty(jg, p); } catch (ClassCastException e) { var nuxeoException = new NuxeoException(e); <START> nuxeoException.addInfo( <END> String.format("writing JSON property failed on document: %s for property: %s", doc, p)); throw nuxeoException; } } }</code><technical_language>do throw new NuxeoException(message, e), need for addInfo is useful if rethrow NuxeoException caught</technical_language>

Target:
protected static void writeProperties(JsonGenerator jg, DocumentModel doc, String schema, ServletRequest request) throws IOException { Collection<Property> properties = doc.getPropertyObjects(schema); if (properties.isEmpty()) { return; } SchemaManager schemaManager = Framework.getService(SchemaManager.class); String prefix = schemaManager.getSchema(schema).getNamespace().prefix; if (prefix == null || prefix.length() == 0) { prefix = schema; } JSONPropertyWriter writer = JSONPropertyWriter.create().writeNull(false).writeEmpty(false).prefix(prefix); if (request != null) { DownloadService downloadService = Framework.getService(DownloadService.class); String blobUrlPrefix = VirtualHostHelper.getBaseURL(request) + downloadService.getDownloadUrl(doc, null, null) + "/"; writer.filesBaseUrl(blobUrlPrefix); } for (Property p : properties) { try { writer.writeProperty(jg, p); } catch (ClassCastException e) { throw new NuxeoException( String.format("writing JSON property failed on document: %s for property: %s", doc, p), e); } } }
Source:
<code>public void updateDNS() { synchronized (sync) { if (shutdown) { return; } long ttl = TimeUnit.SECONDS.convert(period, periodUnit); try { List<ResolveResult> resolveResults = resolver.resolve(); List<HostAndPort> hosts = Lists.newArrayListWithCapacity(resolveResults.size()); for (ResolveResult resolveResult : resolveResults) { hosts.add(HostAndPort.fromParts(resolveResult.getHost(), resolveResult.getPort())); <START> ttl = Math.min(ttl, resolveResult.getTtl()); <END> } List<HostAndPort> newAddresses = Ordering.from(HostAndPortComparator.INSTANCE).sortedCopy(hosts); if (!newAddresses.equals(addresses)) { addresses = newAddresses; log.info("Connecting to " + newAddresses); List<AddressAndClient> addressAndClients = getAddressesAndClients(newAddresses); setPendingClient(addressAndClients); } } finally { long delay = clamp(MIN_DNS_WAIT_TIME, MAX_DNS_WAIT_TIME, ttl); refreshJob = this.executor.schedule(this::updateDNS, delay, TimeUnit.SECONDS); } } }</code><technical_language>final</technical_language>

Target:
public void updateDNS() { synchronized (sync) { if (shutdown) { return; } long ttl = this.ttl; try { List<ResolveResult> resolveResults = resolver.resolve(); if (resolveResults.isEmpty()) { return; } List<HostAndPort> hosts = Lists.newArrayListWithCapacity(resolveResults.size()); for (ResolveResult resolveResult : resolveResults) { hosts.add(HostAndPort.fromParts(resolveResult.getHost(), resolveResult.getPort())); ttl = Math.min(ttl, resolveResult.getTtl()); } final ImmutableSet<HostAndPort> newAddresses = resolveResults .stream() .map(result -> HostAndPort.fromParts(result.getHost(), result.getPort())) .collect(ImmutableSet.toImmutableSet()); final long resolvedTtl = resolveResults.stream().mapToLong(ResolveResult::getTtl).min().orElse(Long.MAX_VALUE); ttl = Math.min(ttl, resolvedTtl); final Set<HostAndPort> currentAddresses = clients.keySet(); if (!newAddresses.equals(currentAddresses)) { final ImmutableSet<HostAndPort> toRemove = Sets.difference(currentAddresses, newAddresses).immutableCopy(); final Sets.SetView<HostAndPort> toAdd = Sets.difference(newAddresses, currentAddresses); if (!toAdd.isEmpty()) { log.info("Connecting to " + toAdd); } if (!toRemove.isEmpty()) { log.info("Scheduling disconnect from " + toRemove); } for (final HostAndPort host : toAdd) { final RawMemcacheClient newClient = connector.connect(host); newClient.registerForConnectionChanges(listener); clients.put(host, newClient); } final ImmutableList.Builder<RawMemcacheClient> removedClients = ImmutableList.builder(); for (final HostAndPort host : toRemove) { final RawMemcacheClient removed = clients.remove(host); removed.unregisterForConnectionChanges(listener); removedClients.add(removed); } setPendingClient(removedClients); } } finally { long delay = clamp(MIN_DNS_WAIT_TIME, MAX_DNS_WAIT_TIME, ttl); refreshJob = this.executor.schedule(this::updateDNS, delay, TimeUnit.SECONDS); } } }
Source:
<code>public Map<String, String> getLabelsMap() { <START> if(label == null) { return ImmutableMap.of("jenkins/" + DEFAULT_LABEL, "true"); } ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); getLabelSet().stream().map(Objects::toString).sorted().forEach((atom) -> { builder.put("jenkins/" + sanitizeLabel(atom), "true"); }); return builder.build(); <END> }</code><technical_language>effectively revert [JENKINS-60088](<LINK_0> Exposed labels in Kubernetes effect Jenkins labels. I recommend reverting this hunk</technical_language>

Target:
public Map<String, String> getLabelsMap() { if (label == null) { return ImmutableMap.of( "jenkins/label", DEFAULT_LABEL, "jenkins/label-digest", "0" ); } else { return ImmutableMap.of( "jenkins/label", sanitizeLabel(label), "jenkins/label-digest", LABEL_DIGEST_FUNCTION.hashString(label).toString() ); } }
Source:
<code>private void notifyLeaderChanges( Outcome outcome ) { LeaderInfo leaderInfo = new LeaderInfo( outcome.getLeader(), outcome.getTerm() ); boolean isStepDown = outcome.isSteppingDown(); if ( isStepDown ) { leaderInfo.stepDown(); } <START> <END> for ( LeaderListener listener : leaderListeners ) { if ( isStepDown ) { listener.onLeaderStepDown( leaderInfo ); } listener.onLeaderSwitch( leaderInfo ); } }</code><technical_language>wondering if a default final method LeadershipListener called foo checks isStepDown, if true calls onLeaderStepDown calls onLeaderSwitch</technical_language>

Target:
private void notifyLeaderChanges( Outcome outcome ) { LeaderInfo leaderInfo = new LeaderInfo( outcome.getLeader(), outcome.getTerm(), outcome.isSteppingDown() ); for ( LeaderListener listener : leaderListeners ) { if ( outcome.isSteppingDown() ) { listener.onLeaderStepDown( leaderInfo ); } listener.onLeaderSwitch( leaderInfo ); } }
Source:
<code>public void provision(OpenShiftEnvironment osEnv, RuntimeIdentity identity) throws InfrastructureException { if (!supportArbitraryUser(osEnv.getAttributes())) { return; } Set<String> recipeMachineNames = osEnv .getMachines() .entrySet() .stream() <START> .filter(e -> e.getValue().getAttributes() != null) <END> .filter( e -> RECIPE_CONTAINER_SOURCE.equals( e.getValue().getAttributes().get(CONTAINER_SOURCE_ATTRIBUTE))) .map(Entry::getKey) .collect(Collectors.toSet()); for (PodData podData : osEnv.getPodsData().values()) { for (Container container : podData.getSpec().getContainers()) { String machineName = Names.machineName(podData, container); if (recipeMachineNames.contains(machineName)) { rewriteContainerCommand(container); } } } }</code><technical_language>nan</technical_language>

Target:
public void provision(OpenShiftEnvironment osEnv, RuntimeIdentity identity) throws InfrastructureException { if (!supportArbitraryUser(osEnv.getAttributes())) { return; } Set<String> recipeMachineNames = osEnv .getMachines() .entrySet() .stream() .filter( e -> RECIPE_CONTAINER_SOURCE.equals( e.getValue().getAttributes().get(CONTAINER_SOURCE_ATTRIBUTE))) .map(Entry::getKey) .collect(Collectors.toSet()); for (PodData podData : osEnv.getPodsData().values()) { for (Container container : podData.getSpec().getContainers()) { String machineName = Names.machineName(podData, container); if (recipeMachineNames.contains(machineName)) { rewriteContainerCommand(container); } } } }
Source:
<code>public List<SecurityTeam> getSecurityTeams(PerunSession sess) throws PrivilegeException, InternalErrorException { Utils.checkPerunSession(sess); if (!AuthzResolver.authorizedInternal(sess, "getSecurityTeams_policy")) { throw new PrivilegeException("getSecurityTeams"); } else { List<SecurityTeam> securityTeams = getSecurityTeamsManagerBl().getAllSecurityTeams(sess); securityTeams.removeIf(st -> { try { return !AuthzResolver.authorizedInternal(sess, "filter-getSecurityTeams_policy", Collections.singletonList(st)); <START> } catch (InternalErrorException e) { <END> return true; } }); return securityTeams; } }</code><technical_language>remove this exception now</technical_language>

Target:
public List<SecurityTeam> getSecurityTeams(PerunSession sess) throws PrivilegeException, InternalErrorException { Utils.checkPerunSession(sess); if (!AuthzResolver.authorizedInternal(sess, "getSecurityTeams_policy")) { throw new PrivilegeException("getSecurityTeams"); } else { List<SecurityTeam> securityTeams = getSecurityTeamsManagerBl().getAllSecurityTeams(sess); securityTeams.removeIf(st -> !AuthzResolver.authorizedInternal(sess, "filter-getSecurityTeams_policy", Collections.singletonList(st))); return securityTeams; } }
Source:
<code>private void processSingleResult(String resultPath, Matcher m) { DispoItemData item = datIdToItem.get(generateDatId(m.group(1), m.group(2))); String location = m.group(3); String text = ""; Discrepancy matchingDiscrepancy = matchDiscrepancy(location, item.getDiscrepanciesList()); if (matchingDiscrepancy != null) { text = matchingDiscrepancy.getText(); Map<String, Discrepancy> discrepancies = item.getDiscrepanciesList(); discrepancies.remove(matchingDiscrepancy.getId()); item.setDiscrepanciesList(discrepancies); addAnnotationForForCoveredLine(item, location, Test_Unit_Resolution, resultPath, text); } else { <START> System.out.println(); <END> } }</code><technical_language>log this instead of print ln</technical_language>

Target:
private void processSingleResult(String resultPath, Matcher m) { DispoItemData item = datIdToItem.get(generateDatId(m.group(1), m.group(2))); if(item != null) { String location = m.group(3); String text = ""; Discrepancy matchingDiscrepancy = matchDiscrepancy(location, item.getDiscrepanciesList()); if (matchingDiscrepancy != null) { text = matchingDiscrepancy.getText(); Map<String, Discrepancy> discrepancies = item.getDiscrepanciesList(); discrepancies.remove(matchingDiscrepancy.getId()); item.setDiscrepanciesList(discrepancies); addAnnotationForForCoveredLine(item, location, Test_Unit_Resolution, text, resultPath); } } }
Source:
<code>public void afterPropertiesSet() throws Exception { <START> this.channelFactory = beanFactory.getBean(ChannelFactory.class); <END> Assert.notNull(this.channelFactory, "ChannelFactory must not be null."); }</code><technical_language>a bean lookup here</technical_language>

Target:
public void afterPropertiesSet() throws Exception { ReflectionUtils.doWithMethods(type, new ReflectionUtils.MethodCallback() { @Override public void doWith(Method method) throws IllegalArgumentException { try { Input input = AnnotationUtils.findAnnotation(method, Input.class); if (input != null) { String name = BindingBeanDefinitionRegistryUtils.getChannelName(input, method); MessageChannel sharedChannel = locateSharedChannel(name); if (sharedChannel == null) { inputs.put(name, new ChannelHolder( channelFactory.createChannel(name, method.getReturnType()), true)); } else { configureSharedMessageChannel(name, method.getReturnType(), sharedChannel); } } } catch (Exception e) { throw new RuntimeException(e); } } }); ReflectionUtils.doWithMethods(type, new ReflectionUtils.MethodCallback() { @Override public void doWith(Method method) throws IllegalArgumentException { try { Output output = AnnotationUtils.findAnnotation(method, Output.class); if (output != null) { String name = BindingBeanDefinitionRegistryUtils.getChannelName(output, method); Class<?> messageChannelType = method.getReturnType(); MessageChannel sharedChannel = locateSharedChannel(name); if (sharedChannel == null) { outputs.put(name, new ChannelHolder( channelFactory.createChannel(name, method.getReturnType()), true)); } else { configureSharedMessageChannel(name, method.getReturnType(), sharedChannel); } } } catch (Exception e) { throw new RuntimeException(e); } } }); }
Source:
<code>static Map<Long, ConfigGroup> collectConfigGroupsWithoutServiceName() { Map<Long, ConfigGroup> configGroupMap = new HashMap<>(); Clusters clusters = injector.getInstance(Clusters.class); Map<String, Cluster> clusterMap = clusters.getClusters(); if (MapUtils.isEmpty(clusterMap)) return configGroupMap; for (Cluster cluster : clusterMap.values()) { Map<Long, ConfigGroup> configGroups = cluster.getConfigGroups(); if (MapUtils.isEmpty(configGroups)) continue; <START> <END> for (ConfigGroup configGroup : configGroups.values()) { if (StringUtils.isEmpty(configGroup.getServiceName())) { configGroupMap.put(configGroup.getId(), configGroup); } } } return configGroupMap; }</code><technical_language>please add curly braces</technical_language>

Target:
static Map<Long, ConfigGroup> collectConfigGroupsWithoutServiceName() { Map<Long, ConfigGroup> configGroupMap = new HashMap<>(); Clusters clusters = injector.getInstance(Clusters.class); Map<String, Cluster> clusterMap = clusters.getClusters(); if (MapUtils.isEmpty(clusterMap)) return configGroupMap; for (Cluster cluster : clusterMap.values()) { Map<Long, ConfigGroup> configGroups = cluster.getConfigGroups(); if (MapUtils.isEmpty(configGroups)) { continue; } for (ConfigGroup configGroup : configGroups.values()) { if (StringUtils.isEmpty(configGroup.getServiceName())) { configGroupMap.put(configGroup.getId(), configGroup); } } } return configGroupMap; }
Source:
<code>public void test(@ArquillianResource URL url) throws Exception { HttpResponse response; HttpGet httpget = new HttpGet(url.toString() + "ejb-security"); String headerValue = java.util.Base64.getEncoder().encodeToString("user:password".getBytes()); Assert.assertNotNull(headerValue); httpget.addHeader("Authorization", "Basic " + headerValue); String text; try (CloseableHttpClient httpclient = HttpClients.createDefault()){ response = httpclient.execute(httpget); text = Utils.getContent(response); Assert.assertFalse(text.contains("java.lang.NullPointerException")); } catch (IOException e) { <START> throw new RuntimeException("Servlet response IO exception", e); <END> } }</code><technical_language>is need for this</technical_language>

Target:
public void test(@ArquillianResource URL url) throws Exception { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(USER, PASSWORD)); try (CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credentialsProvider) .build()) { HttpGet httpget = new HttpGet(url.toExternalForm() + "SecuredEJBServlet/"); HttpResponse response = httpclient.execute(httpget); assertNotNull("Response is 'null', we expected non-null response!", response); String text = Utils.getContent(response); assertEquals(200, response.getStatusLine().getStatusCode()); assertTrue("User principal different from what we expected!", text.contains("Principal: " + USER)); assertTrue("Remote user different from what we expected!", text.contains("Remote User: " + USER)); assertTrue("Authentication type different from what we expected!", text.contains("Authentication Type: BASIC")); } }
Source:
<code>private static <T> T createProxyForZeroNodes(Class<T> type) { return Reflection.newProxy(type, (unused1, unused2, unused3) -> { <START> throw new ServiceNotAvailableException("The " + type.getSimpleName() + " is currently unavailable," <END> + " because we don't know how to talk to it (we think there are zero nodes)."); }); }</code><technical_language>word this error message more directly: "The " + type.getSimpleName() + " is currently unavailable," + " configuration contains zero servers."</technical_language>

Target:
private static <T> T createProxyForZeroNodes(Class<T> type) { return Reflection.newProxy(type, (unused1, unused2, unused3) -> { throw new ServiceNotAvailableException("The " + type.getSimpleName() + " is currently unavailable," + " because configuration contains zero servers."); }); }