auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ITmfTrace openTrace(String projectName, String traceName, boolean isExperiment) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject rootProject = root.getProject(projectName); <START> TmfProjectElement rootElement = TmfProjectRegistry.getProject(rootProject); <END> String childrenName = isExperiment ? "Experiments" : "Traces"; ITmfProjectModelElement traceFolder = rootElement.getChild(childrenName); ITmfProjectModelElement traceChild = traceFolder.getChild(traceName); if (!(traceChild instanceof TmfCommonProjectElement)) { return null; } Display.getDefault().syncExec(new Runnable() { @Override public void run() { if ((traceChild instanceof TmfTraceElement) && !isExperiment) { TmfTraceElement traceElement = (TmfTraceElement) traceChild; TmfOpenTraceHelper.openTraceFromElement(traceElement.getElementUnderTraceFolder()); } else if ((traceChild instanceof TmfExperimentElement) && isExperiment) { TmfExperimentElement experimentElement = (TmfExperimentElement) traceChild; TmfOpenTraceHelper.openTraceFromElement(experimentElement); } } }); TmfCommonProjectElement projectElement = (TmfCommonProjectElement) traceChild; ITmfTrace trace = projectElement.getTrace(); Integer tryCounter = 0; final Integer numberOfTry = 10; while (trace == null && tryCounter < numberOfTry) { try { Thread.sleep(100); } catch (InterruptedException e) { break; } trace = projectElement.getTrace(); tryCounter++; } return trace; }</code><technical_language>need null check this element</technical_language>

Target:
public ITmfTrace openTrace(String projectName, String traceName, boolean isExperiment) throws FileNotFoundException { ITmfProjectModelElement traceChild = getFile(projectName, traceName, isExperiment); if (!(traceChild instanceof TmfCommonProjectElement)) { throw new FileNotFoundException(); } Display.getDefault().syncExec(new Runnable() { @Override public void run() { if ((traceChild instanceof TmfTraceElement) && !isExperiment) { TmfTraceElement traceElement = (TmfTraceElement) traceChild; TmfOpenTraceHelper.openTraceFromElement(traceElement.getElementUnderTraceFolder()); } else if ((traceChild instanceof TmfExperimentElement) && isExperiment) { TmfExperimentElement experimentElement = (TmfExperimentElement) traceChild; TmfOpenTraceHelper.openTraceFromElement(experimentElement); } } }); TmfCommonProjectElement projectElement = (TmfCommonProjectElement) traceChild; ITmfTrace trace = projectElement.getTrace(); Integer tryCounter = 0; final Integer numberOfTry = 10; while (trace == null && tryCounter < numberOfTry) { try { Thread.sleep(100); } catch (InterruptedException e) { break; } trace = projectElement.getTrace(); tryCounter++; } if (trace != null) { return trace; } throw new FileNotFoundException(); }
Source:
<code>public void testBuildXMLGenerateLanguageBundle() throws CarbonToolsIntegrationTestException, IOException { boolean isJarCreated = false; Process process = null; try { File sourceFile = new File(TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts" + File.separator + "CARBON" + File.separator + "carbontools" + File.separator + "resources"); File targetFile = new File(carbonHome + File.separator + "resources"); super.copyFolder(sourceFile, targetFile); String cmdArray[]; if (CarbonCommandToolsUtil.isCurrentOSWindows()) { cmdArray = new String[]{"cmd.exe", "/c", "start", "ant", "localize"}; } else { cmdArray = new String[]{"ant", "localize"}; } process = CarbonCommandToolsUtil.runScript(carbonHome + File.separator + "bin", cmdArray); File folder = new File(carbonHome + File.separator + "repository" + File.separator + "components" + File.separator + "dropins"); long startTime = System.currentTimeMillis(); long timeout = 20000; while ((System.currentTimeMillis() - startTime) < timeout) { if (folder.exists() && folder.isDirectory()) { File[] listOfFiles = folder.listFiles(); for (File file : listOfFiles) { if (file.getName(). <START> contains("org.wso2.carbon.identity.oauth.ui.languageBundle_4.0.7.jar")) { <END> log.info("LanguageBundle jar created successfully"); isJarCreated = true; break; } } if (isJarCreated) { break; } } } } finally { if (process != null) { process.destroy(); } } assertTrue(isJarCreated, "Jar not created successfully"); }</code><technical_language>hard code jar version</technical_language>

Target:
public void testBuildXMLGenerateLanguageBundle() throws CarbonToolsIntegrationTestException { boolean isJarCreated = false; Process process = null; try { File sourceFile = new File(TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts" + File.separator + "CARBON" + File.separator + "carbontools" + File.separator + "resources"); File targetFile = new File(carbonHome + File.separator + "resources"); super.copyFolder(sourceFile, targetFile); String cmdArray[]; if ((CarbonCommandToolsUtil.getCurrentOperatingSystem(). contains(OperatingSystems.WINDOWS.name().toLowerCase())) ) { cmdArray = new String[]{"cmd.exe", "/c", "start", "ant", "localize"}; } else { cmdArray = new String[]{"ant", "localize"}; } process = CarbonCommandToolsUtil.runScript(carbonHome + File.separator + "bin", cmdArray); File folder = new File(carbonHome + File.separator + "repository" + File.separator + "components" + File.separator + "dropins"); long startTime = System.currentTimeMillis(); long timeout = 20000; while ((System.currentTimeMillis() - startTime) < timeout) { if (folder.exists() && folder.isDirectory()) { File[] listOfFiles = folder.listFiles(); for (File file : listOfFiles) { if (file.getName(). contains("org.wso2.carbon.identity.oauth.ui.languageBundle_4.0.7.jar")) { log.info("LanguageBundle jar created successfully"); isJarCreated = true; break; } } if (isJarCreated) { break; } } } } finally { if (process != null) { process.destroy(); } } assertTrue(isJarCreated, "Jar not created successfully"); }
Source:
<code><START> public void setBuilderCache(LRUBuilderCache builderCache) { <END> this.builderCache = builderCache; }</code><technical_language>Please change constructor injection instead of a public setter, remove instance variable injection</technical_language>

Target:
protected void setBuilderCache( LRUBuilderCache builderCache ) { this.builderCache = builderCache; }
Source:
<code>public String toFullString() { return typeDetails.stream() .map(s -> s.replace(DELIMITER, ESCAPED_DELIMITER)) <START> .collect(Collectors.joining(",'")); <END> }</code><technical_language>a extra ' slipped in here. Please DELIMITER constant</technical_language>

Target:
public String toFullString() { return typeDetails.stream() .map(s -> s.replace(DELIMITER, ESCAPED_DELIMITER)) .collect(Collectors.joining(DELIMITER)); }
Source:
<code>public String getShortText() { if (cleaner.isResizing) return NodeL10n.getBase().getString("SaltedHashFreenetStore.shortResizeProgress", new String[] { "name", "processed", "total" }, <START> new String[] { name, String.valueOf((cleaner.entriesTotal - cleaner.entriesLeft)) , <END> String.valueOf(cleaner.entriesTotal) }); else return NodeL10n.getBase().getString("SaltedHashFreenetStore.shortRebuildProgress" + (slotFilter.isNew() ? "New" : ""), new String[] { "name", "processed", "total" }, new String[] { name, String.valueOf((cleaner.entriesTotal - cleaner.entriesLeft)) , String.valueOf(cleaner.entriesTotal) }); }</code><technical_language>additional pair of parens clarify here. Please get rid of them</technical_language>

Target:
public String getShortText() { if (cleaner.isResizing) return NodeL10n.getBase().getString("SaltedHashFreenetStore.shortResizeProgress", new String[] { "name", "processed", "total" }, new String[] { name, String.valueOf(cleaner.entriesTotal - cleaner.entriesLeft) , String.valueOf(cleaner.entriesTotal) }); else return NodeL10n.getBase().getString("SaltedHashFreenetStore.shortRebuildProgress" + (slotFilter.isNew() ? "New" : ""), new String[] { "name", "processed", "total" }, new String[] { name, String.valueOf(cleaner.entriesTotal - cleaner.entriesLeft) , String.valueOf(cleaner.entriesTotal) }); }
Source:
<code>public void testRFileEncrypted() throws Exception { AccumuloConfiguration cryptoOnConf = getAccumuloConfig(CRYPTO_ON_CONF); FileSystem fs = FileSystem.getLocal(CachedConfiguration.getInstance()); ArrayList<Key> keys = testData(); SummarizerConfiguration sumConf = SummarizerConfiguration.builder(KeyCounter.class.getName()) .build(); String file = "target/testFile1.rf"; fs.delete(new Path(file), true); try (RFileWriter writer = RFile.newWriter().to(file).withFileSystem(fs) .withTableProperties(cryptoOnConf).withSummarizers(sumConf).build()) { Value empty = new Value(new byte[] {}); writer.startDefaultLocalityGroup(); for (Key key : keys) { writer.append(key, empty); } } Scanner iter = RFile.newScanner().from(file).withFileSystem(fs) .withTableProperties(cryptoOnConf).build(); ArrayList<Key> keysRead = new ArrayList<>(); iter.forEach(e -> keysRead.add(e.getKey())); assertEquals(keys, keysRead); <START> <END> for (Summary summary : RFile.summaries().from(file).withFileSystem(fs) .withTableProperties(cryptoOnConf).read()) { long total = summary.getFileStatistics().getTotal(); assertTrue(total > 0); } }</code><technical_language>nice check key count also. I experimented this locally. checks key count narrows file stats checks. java Collection<Summary> summaries = RFile.summaries().from(file).withFileSystem(fs) .withTableProperties(cryptoOnConf).read(); assertEquals(1, summaries.size()); Summary summary = Iterables.getOnlyElement(summaries); assertEquals(keys.size(), (long)summary.getStatistics().get("keys")); assertEquals(1, summary.getStatistics().size()); assertEquals(0, summary.getFileStatistics().getInaccurate()); assertEquals(1, summary.getFileStatistics().getTotal());</technical_language>

Target:
public void testRFileEncrypted() throws Exception { AccumuloConfiguration cryptoOnConf = getAccumuloConfig(CRYPTO_ON_CONF); FileSystem fs = FileSystem.getLocal(CachedConfiguration.getInstance()); ArrayList<Key> keys = testData(); SummarizerConfiguration sumConf = SummarizerConfiguration.builder(KeyCounter.class.getName()) .build(); String file = "target/testFile1.rf"; fs.delete(new Path(file), true); try (RFileWriter writer = RFile.newWriter().to(file).withFileSystem(fs) .withTableProperties(cryptoOnConf).withSummarizers(sumConf).build()) { Value empty = new Value(new byte[] {}); writer.startDefaultLocalityGroup(); for (Key key : keys) { writer.append(key, empty); } } Scanner iter = RFile.newScanner().from(file).withFileSystem(fs) .withTableProperties(cryptoOnConf).build(); ArrayList<Key> keysRead = new ArrayList<>(); iter.forEach(e -> keysRead.add(e.getKey())); assertEquals(keys, keysRead); Collection<Summary> summaries = RFile.summaries().from(file).withFileSystem(fs) .withTableProperties(cryptoOnConf).read(); Summary summary = Iterables.getOnlyElement(summaries); assertEquals(keys.size(), (long) summary.getStatistics().get("keys")); assertEquals(1, summary.getStatistics().size()); assertEquals(0, summary.getFileStatistics().getInaccurate()); assertEquals(1, summary.getFileStatistics().getTotal()); }
Source:
<code>public InvocationContext createInvocationContext(boolean isWrite, int keyCount) { if (keyCount == 1) { <START> SingleKeyNonTxInvocationContext result = <END> new SingleKeyNonTxInvocationContext(true, keyEq); return result; } else if (keyCount > 0) { NonTxInvocationContext ctx = new NonTxInvocationContext(keyCount, true, keyEq); return ctx; } return createInvocationContext(null); }</code><technical_language>I remove variables do return new SingleKeyNonTxInvocationContext(true, keyEq); applied other methods</technical_language>

Target:
public InvocationContext createInvocationContext(boolean isWrite, int keyCount) { if (keyCount == 1) { return new SingleKeyNonTxInvocationContext(true, keyEq); } else if (keyCount > 0) { return new NonTxInvocationContext(keyCount, true, keyEq); } return createInvocationContext(null); }
Source:
<code>public void createTopicShouldNotPassAndMustShowTopicErrorIfItIsInvalid() throws NotFoundException { BindingResult result = mock(BindingResult.class); when(result.hasErrors()).thenReturn(true); when(branchService.get(BRANCH_ID)).thenReturn(branch); List<Breadcrumb> breadcrumbs = new BreadcrumbBuilder().getNewTopicBreadcrumb(branch); when(breadcrumbBuilder.getNewTopicBreadcrumb(branch)).thenReturn(breadcrumbs); ModelAndView mav = controller.createTopic(getDto(), result, BRANCH_ID); verify(branchService).get(BRANCH_ID); verify(breadcrumbBuilder).getNewTopicBreadcrumb(branch); List<Breadcrumb> breadcrumbsFromModel = (List) mav.getModel().get("breadcrumbList"); for (int i = 0; i < breadcrumbs.size(); i++) { assertEquals(breadcrumbs.get(i).getValue(), breadcrumbsFromModel.get(i).getValue()); <START> if(i == 1) <END> assertEquals(breadcrumbsFromModel.get(1).getValue(), branch.getSection().getName()); if(i == 2) assertEquals(breadcrumbsFromModel.get(2).getValue(), branch.getName()); } assertViewName(mav, "topic/topicForm"); long branchId = assertAndReturnModelAttributeOfType(mav, "branchId", Long.class); assertEquals(branchId, BRANCH_ID); }</code><technical_language>I copy-paste here. I want need theses if blocks asserts loop</technical_language>

Target:
public void createTopicShouldNotPassAndMustShowTopicErrorIfItIsInvalid() throws NotFoundException { BindingResult result = mock(BindingResult.class); when(result.hasErrors()).thenReturn(true); when(branchService.get(BRANCH_ID)).thenReturn(branch); List<Breadcrumb> breadcrumbs = new BreadcrumbBuilder().getNewTopicBreadcrumb(branch); when(breadcrumbBuilder.getNewTopicBreadcrumb(branch)).thenReturn(breadcrumbs); ModelAndView mav = controller.createTopic(getDto(), result, BRANCH_ID); verify(branchService).get(BRANCH_ID); verify(breadcrumbBuilder).getNewTopicBreadcrumb(branch); List<Breadcrumb> breadcrumbsFromModel = (List) mav.getModel().get("breadcrumbList"); for (int i = 0; i < breadcrumbs.size(); i++) { assertEquals(breadcrumbs.get(i).getValue(), breadcrumbsFromModel.get(i).getValue()); } assertEquals(breadcrumbsFromModel.get(1).getValue(), branch.getSection().getName()); assertEquals(breadcrumbsFromModel.get(2).getValue(), branch.getName()); assertViewName(mav, "topic/topicForm"); long branchId = assertAndReturnModelAttributeOfType(mav, "branchId", Long.class); assertEquals(branchId, BRANCH_ID); }
Source:
<code>private ReplicationSpec getNewEventOnlyReplicationSpec(Long eventId) throws SemanticException { ReplicationSpec rspec = getNewReplicationSpec(eventId.toString(), eventId.toString()); <START> rspec.setIsEventDump(true); <END> return rspec; }</code><technical_language>rename this setIsIncrementalDump more define purpose</technical_language>

Target:
private ReplicationSpec getNewEventOnlyReplicationSpec(Long eventId) throws SemanticException { ReplicationSpec rspec = getNewReplicationSpec(eventId.toString(), eventId.toString()); rspec.setIsIncrementalDump(true); return rspec; }
Source:
<code>public void testConfiguration(String username, String password, LdapConfiguration configuration) throws IOException { authenticationItemConfigurationManager.testCustomAuthenticationItem(configuration, this, (c) -> { LdapUserDetailsService luds = (LdapUserDetailsService) c.getBean("ldapUserDetailsService"); UserDetails user = luds.loadUserByUsername(username); <START> if (!PasswordEncoderFactories.createDelegatingPasswordEncoder().matches(password, user.getPassword())) <END> { throw new BadCredentialsException("Credentials don't match."); } return false; }); }</code><technical_language>@anki2189 I PasswordEncoderFactories.createDelegatingPasswordEncoder() instead of BCryptPasswordEncoder in StrongboxSecurityConfig.passwordEncoder(). This aslo affect strongbox users, store passwords prefix in DB well</technical_language>

Target:
public void testConfiguration(String username, String password, LdapConfiguration configuration) throws IOException { authenticationItemConfigurationManager.testCustomAuthenticationItem(configuration, this, (c) -> { LdapUserDetailsService luds = (LdapUserDetailsService) c.getBean("ldapUserDetailsService"); UserDetails user = luds.loadUserByUsername(username); if (!passwordEncoder.matches(password, user.getPassword())) { throw new BadCredentialsException("Credentials don't match."); } return false; }); }
Source:
<code>protected HttpResponse post(String url) { <START> if (!url.startsWith("http")) { <END> url = getFullUrl(url); } HttpResponse response = null; try { Request request = Request.Post(url); if (session != null && session.isSignedIn()) { request.setHeader(BRIDGE_SESSION_HEADER, session.getSessionToken()); } logger.debug("POST " + url + "\n <EMPTY>"); response = exec.execute(request).returnResponse(); throwExceptionOnErrorStatus(response, url); } catch (ClientProtocolException e) { throw new BridgeServerException(CONNECTION_FAILED, e, url); } catch (IOException e) { throw new BridgeServerException(CONNECTION_FAILED, e, url); } return response; }</code><technical_language>this rolled getFullUrl do in place</technical_language>

Target:
protected HttpResponse post(String url) { url = getFullUrl(url); HttpResponse response = null; try { Request request = Request.Post(url); if (session != null && session.isSignedIn()) { request.setHeader(BRIDGE_SESSION_HEADER, session.getSessionToken()); } logger.debug("POST " + url + "\n <EMPTY>"); response = exec.execute(request).returnResponse(); throwExceptionOnErrorStatus(response, url); } catch (ClientProtocolException e) { throw new BridgeServerException(CONNECTION_FAILED, e, url); } catch (IOException e) { throw new BridgeServerException(CONNECTION_FAILED, e, url); } return response; }
Source:
<code>private void notifyPluginSettingsChange(PluginSettings pluginSettings) { String pluginId = pluginSettings.getPluginId(); for (GoPluginExtension extension : extensions) { if (extension.canHandlePlugin(pluginId)) { try { extension.notifyPluginSettingsChange(pluginId, pluginSettings.getSettingsMap()); <START> break; <END> } catch (Exception e) { LOGGER.warn("Error notifying plugin - with settings change", pluginId, e); } } } }</code><technical_language>I break of try block break loop - extension (extension.canHandlePlugin(pluginId))for a pluginId, notify plugin extension. If call failed, for other extension notify plugin settings change</technical_language>

Target:
private void notifyPluginSettingsChange(PluginSettings pluginSettings) { String pluginId = pluginSettings.getPluginId(); for (GoPluginExtension extension : extensions) { if (extension.canHandlePlugin(pluginId)) { try { extension.notifyPluginSettingsChange(pluginId, pluginSettings.getSettingsAsKeyValuePair()); break; } catch (Exception e) { LOGGER.warn("Error notifying plugin - with settings change", pluginId, e); } } } }
Source:
<code>public TestingSourceOperator( SourceReader<T, MockSourceSplit> reader, WatermarkStrategy<T> watermarkStrategy, ProcessingTimeService timeService, OperatorEventGateway eventGateway, int subtaskIndex, int parallelism, boolean emitProgressiveWatermarks) { super( (context) -> reader, eventGateway, new MockSourceSplitSerializer(), watermarkStrategy, timeService, new Configuration(), "localhost", emitProgressiveWatermarks); this.subtaskIndex = subtaskIndex; this.parallelism = parallelism; this.metrics = UnregisteredMetricGroups.createUnregisteredOperatorMetricGroup(); this.readerCreated = false; <START> this.sourceMetricGroup = new TestingSourceMetricGroup(); <END> }</code><technical_language>do a testing constructor in SourceOperator accepts a metric group, making a parent field public mutating here</technical_language>

Target:
public TestingSourceOperator( SourceReader<T, MockSourceSplit> reader, WatermarkStrategy<T> watermarkStrategy, ProcessingTimeService timeService, OperatorEventGateway eventGateway, int subtaskIndex, int parallelism, boolean emitProgressiveWatermarks) { super( (context) -> reader, eventGateway, new MockSourceSplitSerializer(), watermarkStrategy, timeService, new Configuration(), "localhost", emitProgressiveWatermarks, new TestingSourceMetricGroup()); this.subtaskIndex = subtaskIndex; this.parallelism = parallelism; this.metrics = UnregisteredMetricGroups.createUnregisteredOperatorMetricGroup(); this.readerCreated = false; }
Source:
<code>public void connect(String connectionString, Properties info) throws SQLException { registerDriver(); <START> if (currentConnection != null) { <END> closeConnection(); } currentConnection = DriverManager.getConnection(connectionString, info); afterConnectionEstablished(); }</code><technical_language>need of null check - closeConnection() takes care that</technical_language>

Target:
public void connect(String connectionString, Properties info) throws SQLException { registerDriver(); closeConnection(); currentConnection = DriverManager.getConnection(connectionString, info); afterConnectionEstablished(); }
Source:
<code>public String getImage(String imageKey, IMAGE_SIZE_TYPE sizeType) throws MambuApiException { ParamsMap params = new ParamsMap(); if (sizeType != null) params.put(SIZE, sizeType.name()); String urlString = new String(mambuAPIService.createUrl(IMAGES + "/" + imageKey)); String apiResponse = mambuAPIService.executeRequest(urlString, params, Method.GET); final String encodingStartsAfter = "base64,"; <START> final int dataStart = apiResponse.indexOf(encodingStartsAfter) + encodingStartsAfter.length(); <END> String base64EncodedString = apiResponse.substring(dataStart); base64EncodedString = base64EncodedString.replaceAll("(\\\\r)?\\\\n", ""); return base64EncodedString; }</code><technical_language>Please check if prefix is contained in API response, in case of a non-existing image invalid encodedKey return exception IndexOutOfRange exception here</technical_language>

Target:
public String getImage(String imageKey, IMAGE_SIZE_TYPE sizeType) throws MambuApiException { if (imageKey == null) { throw new IllegalArgumentException("Image key cannot be null"); } ParamsMap params = new ParamsMap(); if (sizeType != null) { params.put(SIZE, sizeType.name()); } String urlString = new String(mambuAPIService.createUrl(IMAGES + "/" + imageKey)); String apiResponse = mambuAPIService.executeRequest(urlString, params, Method.GET); final String encodingStartsAfter = "base64,"; String base64EncodedString = null; if (apiResponse != null && apiResponse.contains(encodingStartsAfter)) { final int dataStart = apiResponse.indexOf(encodingStartsAfter) + encodingStartsAfter.length(); base64EncodedString = apiResponse.substring(dataStart); base64EncodedString = base64EncodedString.replaceAll("(\\\\r)?\\\\n", ""); } return base64EncodedString; }
Source:
<code>private Set<String> getReadGroups(SingularityRequest request) { Set<String> allowedReadGroups = new HashSet<>( authConfiguration.getGlobalReadOnlyGroups() ); allowedReadGroups.addAll(authConfiguration.getGlobalReadWriteGroups()); if (request.getActionPermissions().isPresent()) { request <START> .getActionPermissions() <END> .get() .entrySet() .stream() .filter( e -> e.getValue().contains(SingularityAuthorizationScope.READ) || e.getValue().contains(SingularityAuthorizationScope.WRITE) ) .map(Entry::getKey) .forEach(allowedReadGroups::add); } else { if (!request.getReadOnlyGroups().isPresent()) { allowedReadGroups.addAll(authConfiguration.getDefaultReadOnlyGroups()); } request.getReadOnlyGroups().ifPresent(allowedReadGroups::addAll); request.getReadWriteGroups().ifPresent(allowedReadGroups::addAll); } request.getGroup().ifPresent(allowedReadGroups::add); if (allowedReadGroups.isEmpty()) { LOG.warn("No read-enabled groups set for {}", request.getId()); } return allowedReadGroups; }</code><technical_language>is this needed still? I action permissions write-based (and SingularityAuthorizationScope objects)</technical_language>

Target:
private Set<String> getReadGroups(SingularityRequest request) { Set<String> allowedReadGroups = new HashSet<>( authConfiguration.getGlobalReadOnlyGroups() ); allowedReadGroups.addAll(authConfiguration.getGlobalReadWriteGroups()); if (!request.getReadOnlyGroups().isPresent()) { allowedReadGroups.addAll(authConfiguration.getDefaultReadOnlyGroups()); } request.getReadOnlyGroups().ifPresent(allowedReadGroups::addAll); request.getReadWriteGroups().ifPresent(allowedReadGroups::addAll); request.getGroup().ifPresent(allowedReadGroups::add); if (allowedReadGroups.isEmpty()) { LOG.warn("No read-enabled groups set for {}", request.getId()); } return allowedReadGroups; }
Source:
<code>private byte[] handleBeginDownloadMessage(byte[] message, byte[] msgNumber) { boolean msgValid = true; <START> if (message.length < 25 || message.length > 65534) { <END> msgValid = false; } else { fileLength = message[4] & 0xFF | (message[5] & 0xFF) << 8 | (message[6] & 0xFF) << 16 | (message[7] & 0xFF) << 24; } replyRequired = true; return getDownloadReply(msgValid, msgNumber, message[3]); }</code><technical_language>numbers defined in a static variable</technical_language>

Target:
private byte[] handleBeginDownloadMessage(byte[] message, byte[] msgNumber) { boolean msgValid = true; if (message.length < MIN_BEGIN_DOWNLOAD_LENGTH || message.length > MAX_MESSAGE_LENGTH) { msgValid = false; } else { fileLength = message[4] & 0xFF | (message[5] & 0xFF) << 8 | (message[6] & 0xFF) << 16 | (message[7] & 0xFF) << 24; } replyRequired = true; return getDownloadReply(msgValid, msgNumber, message[3]); }
Source:
<code><START> protected boolean subdirectoryExists(String subdirectoryName) { <END> String fullSubdirectory = String.format("%s%s", rootPath, subdirectoryName); try (JarFile jar = new JarFile(jarFile)) { Enumeration<JarEntry> jarEntries = jar.entries(); while (jarEntries.hasMoreElements()) { JarEntry entry = jarEntries.nextElement(); String entryName = entry.getName(); if (entryName.startsWith(fullSubdirectory)) { return true; } } return false; } catch (Exception e) { throw new IllegalArgumentException( Messages.format("Error loading resource from JAR file: {}", jarFile), e); } }</code><technical_language>this executes complicated/full dir structure is, however, dirs in a single pass, shoved a container contains() performed same. If usage is heavy consider this change</technical_language>

Target:
protected boolean subdirectoryExists(String subdirectoryName) { String resolvedName = subdirectoryName.startsWith(File.separator) ? subdirectoryName.substring(1) : subdirectoryName; if (resolvedName.endsWith(File.separator)) { resolvedName = resolvedName.substring(0, resolvedName.length() - 1); } return entries.contains(resolvedName); }
Source:
<code>public CompletableFuture<String> callGreeting(String name) { <START> if (ms != null) { <END> return this.greetingService.greeting(name); } else { return CompletableFuture.completedFuture("microservices is not set"); } }</code><technical_language>I understand case. microservices other checking is null - is meaning of it? is simpler inject greetingService if microservices set check greetingService null</technical_language>

Target:
public CompletableFuture<String> callGreeting(String name) { return this.greetingService.greeting(name); }
Source:
<code>private int access(Parameters requireCapabilities) { return requireCapabilities.entrySet() .stream() .filter(entry -> Header.removeDuplicateMarker(entry.getKey()) .equals(EXTENDER_NAMESPACE)) .findAny() <START> .map(entry -> ModuleAttribute.ACC_OPEN) <END> .orElse(0); }</code><technical_language>mapToInt need int Integer</technical_language>

Target:
private int access(Parameters requireCapabilities) { return requireCapabilities.entrySet() .stream() .filter(entry -> Header.removeDuplicateMarker(entry.getKey()) .equals(EXTENDER_NAMESPACE)) .mapToInt(entry -> ModuleAttribute.ACC_OPEN) .findAny() .orElse(0); }
Source:
<code>private Response delete(BaseDataAccessor zkBaseDataAccessor, String path) { Stat stat = zkBaseDataAccessor.getStat(path, AccessOption.PERSISTENT); if (stat != null && stat.getEphemeralOwner() <= 0) { throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN) <START> .entity(String.format("Deleting a non ephemeral node is not allowed", path)).build()); <END> } Boolean ret = zkBaseDataAccessor.remove(path, AccessOption.PERSISTENT); Map<String, String> result = ImmutableMap.of(ZooKeeperCommand.delete.name(), ret.toString(), PATH_STR, path); return JSONRepresentation(result); }</code><technical_language>Missing %s</technical_language>

Target:
private Response delete(BaseDataAccessor zkBaseDataAccessor, String path) { Stat stat = zkBaseDataAccessor.getStat(path, AccessOption.PERSISTENT); if (stat == null) { return notFound(); } else if (stat.getEphemeralOwner() <= 0) { throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN) .entity(String.format("Deleting a non-ephemeral node is not allowed.")).build()); } if (zkBaseDataAccessor.remove(path, AccessOption.PERSISTENT)) { return OK(); } else { throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(String.format("Failed to delete %s.", path)).build()); } }
Source:
<code>public void requestHandleWithGoodInputTest() throws Exception { doRequestHandleTest(HttpMethod.POST, "POST", false, false); doRequestHandleTest(HttpMethod.GET, "GET", false, false); doRequestHandleTest(HttpMethod.DELETE, "DELETE", false, false); <START> doRequestHandleTest(HttpMethod.GET, "GET", false, true); <END> }</code><technical_language>for GET for request types</technical_language>

Target:
public void requestHandleWithGoodInputTest() throws Exception { doRequestHandleTest(HttpMethod.POST, "POST", false, false); doRequestHandleTest(HttpMethod.GET, "GET", false, false); doRequestHandleTest(HttpMethod.DELETE, "DELETE", false, false); doRequestHandleTest(HttpMethod.POST, "POST", false, true); doRequestHandleTest(HttpMethod.GET, "GET", false, true); doRequestHandleTest(HttpMethod.DELETE, "DELETE", false, true); }
Source:
<code>public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); try { <START> if (evt instanceof IdleStateEvent) { <END> logger.info("IdleStateEvent triggered, close channel " + channel); channel.close(); } super.userEventTriggered(ctx, evt); } finally { NettyChannel.removeChannelIfDisconnected(ctx.channel()); } }</code><technical_language>logic NettyClientHandler. call NettyChannel.getOrAddChannel if (evt instanceof IdleStateEvent)</technical_language>

Target:
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); try { logger.info("IdleStateEvent triggered, close channel " + channel); channel.close(); } finally { NettyChannel.removeChannelIfDisconnected(ctx.channel()); } } super.userEventTriggered(ctx, evt); }
Source:
<code>public void setProfilerMode(boolean profilerMode) { if (profilerMode == profilerMode_) { return; } profilerMode_ = profilerMode; <START> setSecondaryToolbarVisible(debugMode_ || profilerMode_); <END> secondaryToolbar_.removeAllWidgets(); if (profilerMode_) { if (debugMode_) { loadDebugToolsIntoSecondaryToolbar(); } loadProfilerToolsIntoSecondaryToolbar(); } else if (debugMode_) { loadDebugToolsIntoSecondaryToolbar(); } }</code><technical_language>Nit: call code set toolbar state based debugMode_ profilerMode_ mode switch functions</technical_language>

Target:
public void setProfilerMode(boolean profilerMode) { if (profilerMode == profilerMode_) { return; } profilerMode_ = profilerMode; loadDebugToolsIntoSecondaryToolbar(); }
Source:
<code>private void assertCopy(FullBinaryMemcacheRequest expected, ByteBuf expectedContent, FullBinaryMemcacheRequest actual) { assertNotSame(expected, actual); <START> assertTrue(ByteBufUtil.equals(expected.key(), actual.key())); <END> assertTrue(ByteBufUtil.equals(expected.extras(), actual.extras())); assertTrue(ByteBufUtil.equals(expectedContent, actual.content())); assertEquals(expected.reserved(), actual.reserved()); assertEquals(expected.magic(), actual.magic()); assertEquals(expected.opcode(), actual.opcode()); assertEquals(expected.keyLength(), actual.keyLength()); assertEquals(expected.extrasLength(), actual.extrasLength()); assertEquals(expected.dataType(), actual.dataType()); assertEquals(expected.totalBodyLength(), actual.totalBodyLength()); assertEquals(expected.opaque(), actual.opaque()); assertEquals(expected.cas(), actual.cas()); }</code><technical_language>assertEquals(expected.key(), actual.key() .... for other lines</technical_language>

Target:
private void assertCopy(FullBinaryMemcacheRequest expected, ByteBuf expectedContent, FullBinaryMemcacheRequest actual) { assertNotSame(expected, actual); assertEquals(expected.key(), actual.key()); assertEquals(expected.extras(), actual.extras()); assertEquals(expectedContent, actual.content()); assertEquals(expected.reserved(), actual.reserved()); assertEquals(expected.magic(), actual.magic()); assertEquals(expected.opcode(), actual.opcode()); assertEquals(expected.keyLength(), actual.keyLength()); assertEquals(expected.extrasLength(), actual.extrasLength()); assertEquals(expected.dataType(), actual.dataType()); assertEquals(expected.totalBodyLength(), actual.totalBodyLength()); assertEquals(expected.opaque(), actual.opaque()); assertEquals(expected.cas(), actual.cas()); }
Source:
<code>public ChargeQueryResponse queryPaymentStatus(ChargeEntity charge) throws GatewayException { <START> logger.info("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); <END> GatewayClient.Response response = inquiryClient.postRequestFor( gatewayUrlMap.get(charge.getGatewayAccount().getType()), charge.getGatewayAccount(), buildQuery(charge), getGatewayAccountCredentialsAsAuthHeader(charge.getGatewayAccount()) ); GatewayResponse<WorldpayQueryResponse> worldpayGatewayResponse = getWorldpayGatewayResponse(response, WorldpayQueryResponse.class); return worldpayGatewayResponse.getBaseResponse() .map(ChargeQueryResponse::from) .orElseThrow(() -> new WebApplicationException(format( "Unable to query charge %s - an error occurred: %s", charge.getExternalId(), worldpayGatewayResponse ))); }</code><technical_language>![bc9](<LINK_0></technical_language>

Target:
public ChargeQueryResponse queryPaymentStatus(ChargeEntity charge) throws GatewayException { GatewayClient.Response response = inquiryClient.postRequestFor( gatewayUrlMap.get(charge.getGatewayAccount().getType()), charge.getGatewayAccount(), buildQuery(charge), getGatewayAccountCredentialsAsAuthHeader(charge.getGatewayAccount()) ); GatewayResponse<WorldpayQueryResponse> worldpayGatewayResponse = getWorldpayGatewayResponse(response, WorldpayQueryResponse.class); return worldpayGatewayResponse.getBaseResponse() .map(ChargeQueryResponse::from) .orElseThrow(() -> new WebApplicationException(format( "Unable to query charge %s - an error occurred: %s", charge.getExternalId(), worldpayGatewayResponse ))); }
Source:
<code>public void setUserSharingScope(Context context, String scope) { userSessionInfo.setSharingScope(scope); <START> saveUserSession(context, userSessionInfo); <END> service.dataSharing(new SharingOptionBody(scope)) .compose(ObservableUtils.applyDefault()).subscribe(response -> LogExt.d(getClass(), "Response: " + response.code() + ", message: " + response.message()), error -> { LogExt.e(getClass(), error.getMessage()); }); }</code><technical_language>wait for success server setting this</technical_language>

Target:
public void setUserSharingScope(Context context, String scope) { service.dataSharing(new SharingOptionBody(scope)) .compose(ObservableUtils.applyDefault()) .doOnNext(response -> { if(response.isSuccess()) { userSessionInfo.setSharingScope(scope); saveUserSession(context, userSessionInfo); } }) .subscribe(response -> LogExt.d(getClass(), "Response: " + response.code() + ", message: " + response.message()), error -> { LogExt.e(getClass(), error.getMessage()); }); }
Source:
<code>public void sendMessage(Message... messages) { List<String> s = new ArrayList<String>(); for (Message message : messages) { <START> if (message instanceof Message.Text) <END> s.add((String) message.getContent()); } this.sendMessage(s.toArray(new String[s.size()])); }</code><technical_language>Missing braces if statement</technical_language>

Target:
public void sendMessage(Message... messages) { for (Message message : messages) { if (message instanceof Message.Text) { this.addChatMessage(new ChatComponentText((String) message.getContent())); } else { this.addChatMessage(new ChatComponentText(message.toLegacy())); } } }
Source:
<code>private boolean isDomainAttachedToDifferentStoragePool() { if (getStoragePool().getStatus() == StoragePoolStatus.Uninitialized) { for (Guid storageDomainId : getParameters().getStorages()) { <START> StorageDomain domain = DbFacade.getInstance().getStorageDomainDao().get(storageDomainId); <END> if (domain.getStorageDomainType().isDataDomain() && isStorageDomainAttachedToStoragePool(domain)) { return failCanDoAction(VdcBllMessages.ERROR_CANNOT_ADD_STORAGE_DOMAIN_WITH_ATTACHED_DATA_DOMAIN); } } } return true; }</code><technical_language>getStorageDomainDao</technical_language>

Target:
private boolean isDomainAttachedToDifferentStoragePool() { if (getStoragePool().getStatus() == StoragePoolStatus.Uninitialized) { for (Guid storageDomainId : getParameters().getStorages()) { StorageDomain domain = getStorageDomainDAO().get(storageDomainId); if (domain.getStorageDomainType().isDataDomain() && isStorageDomainAttachedToStoragePool(domain)) { return failCanDoAction(VdcBllMessages.ERROR_CANNOT_ADD_STORAGE_DOMAIN_WITH_ATTACHED_DATA_DOMAIN); } } } return true; }
Source:
<code>public void getCheckRuns() throws Exception { <START> GHCheckRuns checkRuns = getRepository().getCheckRuns("8051615eff597f4e49f4f47625e6fc2b49f26bfc"); <END> assertThat(checkRuns.getTotalCount(), equalTo(2)); assertThat(checkRuns.getCheckRuns(), hasSize(2)); assertThat(checkRuns.getCheckRuns().get(0).getName(), equalTo("Travis CI - Pull Request")); assertThat(checkRuns.getCheckRuns().get(1).getName(), equalTo("Travis CI - Branch")); }</code><technical_language>GHCheckRuns paging set page count 1 rerecord this. Also, record this based github-api/github-api currently a larger number of checks</technical_language>

Target:
public void getCheckRuns() throws Exception { final int expectedCount = 8; PagedIterable<GHCheckRun> checkRuns = gitHub.getOrganization("github-api") .getRepository("github-api") .getCheckRuns("78b9ff49d47daaa158eb373c4e2e040f739df8b9"); assertThat(checkRuns.withPageSize(2).iterator().nextPage(), hasSize(2)); int checkRunsCount = 0; for (GHCheckRun checkRun : checkRuns) { assertThat(checkRun.getConclusion(), equalTo("success")); checkRunsCount++; } assertThat(checkRunsCount, equalTo(expectedCount)); }
Source:
<code>public static boolean isProvider(URL url) { return PROVIDERS_CATEGORY.equals(url.getParameter(Constants.CATEGORY_KEY, PROVIDERS_CATEGORY)) && !OVERRIDE_PROTOCOL.equals(url.getProtocol()) <START> && !ROUTE_PROTOCOL.equals(url.getProtocol()); <END> }</code><technical_language>apply approach here</technical_language>

Target:
public static boolean isProvider(URL url) { return !OVERRIDE_PROTOCOL.equals(url.getProtocol()) && !ROUTE_PROTOCOL.equals(url.getProtocol()) && PROVIDERS_CATEGORY.equals(url.getParameter(CATEGORY_KEY, PROVIDERS_CATEGORY)); }
Source:
<code>synchronized public FirebaseAnalytics getAnalyticsInstance() { <START> analyticsInstance.setUserId(getUserIdOrNull()); <END> return this.analyticsInstance; }</code><technical_language>this throw NPE if FirebaseAnalyticsUtil.versionIncompatible is true line 218</technical_language>

Target:
synchronized public FirebaseAnalytics getAnalyticsInstance() { if (analyticsInstance == null) { analyticsInstance = FirebaseAnalytics.getInstance(this); } analyticsInstance.setUserId(getUserIdOrNull()); return analyticsInstance; }
Source:
<code>@Nullable protected ITmfTreeViewerEntry updateElements(long start, long end, boolean isSelection) { if (isSelection || (start == end)) { return null; } TmfAbstractAnalysisModule analysisModule = getStatisticsAnalysisModule(); if (getTrace() == null || !(analysisModule instanceof LatencyStatisticsAnalysisModule)) { return null; } LatencyStatisticsAnalysisModule module = (LatencyStatisticsAnalysisModule) analysisModule; module.waitForCompletion(); LatencyStatistics entry = module.getTotalStats(); TmfTreeViewerEntry root = new TmfTreeViewerEntry(""); List<ITmfTreeViewerEntry> entryList = root.getChildren(); TmfTreeViewerEntry child = new LatencyTreeViewerEntry(checkNotNull(Messages.LatencyStatistics_TotalLabel), checkNotNull(entry)); entryList.add(child); HiddenTreeViewerEntry syscalls = new HiddenTreeViewerEntry(checkNotNull(SYSCALL_LEVEL)); child.addChild(syscalls); Map<String, LatencyStatistics> perSyscallStats = module.getPerSyscallStats(); if (perSyscallStats != null) { <START> Iterator<Entry<@NonNull String, @NonNull LatencyStatistics>> stats = perSyscallStats.entrySet().iterator(); <END> while (stats.hasNext()) { Entry<String, LatencyStatistics> statsEntry = stats.next(); syscalls.addChild(new LatencyTreeViewerEntry(statsEntry.getKey(), statsEntry.getValue())); } } return root; }</code><technical_language>redundant if in @NNBD. warning is in part: perSyscallStats.entrySet().iterator(); tricky. annotated Map.entrySet() return a @NonNull Set<Entry>. I a @NonNull Set<@NonNull Entry>. if a map permits empty key and/or values, I Entry object in entrySet null, right</technical_language>

Target:
@Nullable protected ITmfTreeViewerEntry updateElements(long start, long end, boolean isSelection) { if (isSelection || (start == end)) { return null; } TmfAbstractAnalysisModule analysisModule = getStatisticsAnalysisModule(); if (getTrace() == null || !(analysisModule instanceof LatencyStatisticsAnalysisModule)) { return null; } LatencyStatisticsAnalysisModule module = (LatencyStatisticsAnalysisModule) analysisModule; module.waitForCompletion(); LatencyStatistics entry = module.getTotalStats(); TmfTreeViewerEntry root = new TmfTreeViewerEntry(""); List<ITmfTreeViewerEntry> entryList = root.getChildren(); TmfTreeViewerEntry child = new LatencyTreeViewerEntry(checkNotNull(Messages.LatencyStatistics_TotalLabel), checkNotNull(entry)); entryList.add(child); HiddenTreeViewerEntry syscalls = new HiddenTreeViewerEntry(checkNotNull(SYSCALL_LEVEL)); child.addChild(syscalls); Map<String, LatencyStatistics> perSyscallStats = module.getPerSyscallStats(); if (perSyscallStats != null) { Iterator<Entry<String, LatencyStatistics>> stats = perSyscallStats.entrySet().iterator(); while (stats.hasNext()) { Entry<String, LatencyStatistics> statsEntry = stats.next(); syscalls.addChild(new LatencyTreeViewerEntry(statsEntry.getKey(), statsEntry.getValue())); } } return root; }
Source:
<code>private Data getNextBlock() { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; boolean abortTransaction = false; try { con = DbConnectionManager.getTransactionConnection(); pstmt = con.prepareStatement(LOAD_ID); pstmt.setInt(1, type); rs = pstmt.executeQuery(); long currentID = 1; if (rs.next()) { currentID = rs.getLong(1); } else { createNewID(con, type); } DbConnectionManager.fastcloseStmt(rs, pstmt); long newID = currentID + blockSize; pstmt = con.prepareStatement(UPDATE_ID); pstmt.setLong(1, newID); pstmt.setInt(2, type); pstmt.setLong(3, currentID); if (pstmt.executeUpdate() == 1) { final Data result = new Data(currentID, newID); sequenceBlocks.put(type, result); return result; } else { <START> throw new IllegalStateException("Failed at attempt to obtain an ID, aborting..."); <END> } } catch (SQLException e) { Log.error("An exception occurred while trying to obtain new sequence values from the database for type {}", type, e); abortTransaction = true; throw new IllegalStateException("Failed at attempt to obtain an ID, aborting...", e); } finally { DbConnectionManager.closeStatement(rs, pstmt); DbConnectionManager.closeTransactionConnection(con, abortTransaction); } }</code><technical_language>this set abortTransaction true, aborted? Is desired? FWIW, default rollback flag true, set false immediately return result;, needs changed in place</technical_language>

Target:
private Data getNextBlock() { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(LOAD_ID); pstmt.setInt(1, type); rs = pstmt.executeQuery(); long currentID = 1; if (rs.next()) { currentID = rs.getLong(1); } else { createNewID(con, type); } DbConnectionManager.fastcloseStmt(rs, pstmt); long newID = currentID + blockSize; pstmt = con.prepareStatement(UPDATE_ID); pstmt.setLong(1, newID); pstmt.setInt(2, type); pstmt.setLong(3, currentID); if (pstmt.executeUpdate() == 1) { final Data result = new Data(currentID, newID); sequenceBlocks.put(type, result); return result; } else { throw new IllegalStateException("Failed at attempt to obtain an ID, aborting..."); } } catch (SQLException e) { Log.error("An exception occurred while trying to obtain new sequence values from the database for type {}", type, e); throw new IllegalStateException("Failed at attempt to obtain an ID, aborting...", e); } finally { DbConnectionManager.closeConnection(rs, pstmt, con); } }
Source:
<code>public void adDisplayed(final AppLovinAd ad) { ApplovinAdapter.log( DEBUG, adType + " displayed" ); runOnUiThread(new Runnable() { @Override public void run() { if ( isRewarded ) { rewardedListener.onAdOpened( adapter ); <START> reward = null; <END> } else { interstitialListener.onAdOpened( adapter ); } } }); fullyWatched = false; }</code><technical_language>Setting reward null is causing adapter provide a reward in adHidden(). I moving this immediately reward callback fix issue</technical_language>

Target:
public void adDisplayed(final AppLovinAd ad) { ApplovinAdapter.log( DEBUG, adType + " displayed" ); runOnUiThread(new Runnable() { @Override public void run() { if ( isRewarded ) { rewardedListener.onAdOpened( adapter ); } else { interstitialListener.onAdOpened( adapter ); } } }); fullyWatched = false; }
Source:
<code>protected void handleHMSMessage(String data) { if (data.startsWith("H")) { String device = data.substring(1, 5); String woHeader = data.substring(5, data.length() - 1); String s1 = woHeader.substring(0, 1); String batteryStatus = "ok"; boolean isEmpty = (s1.charAt(0) & 2) == 2; boolean isReplaced = (s1.charAt(0) & 4) == 4; if (isEmpty) { batteryStatus = "empty"; } else if (isReplaced) { batteryStatus = "replaced"; } double temperature = Integer.parseInt(woHeader.substring(5, 6) + woHeader.substring(2, 4)) / 10.0; boolean isNegative = (s1.charAt(0) & 8) == 8; if (isNegative) { temperature = -temperature; } double humidity = Integer.parseInt(woHeader.substring(6, 8) + woHeader.substring(4, 5)) / 10.0; logger.info("device: " + device + ", T: " +(!isNegative?" ":"")+ temperature + ",\tH: " + humidity + ", Bat.: " <START> + batteryStatus); <END> HMSBindingConfig temperatureConfig = findConfig(device, HMSBindingConfig.Datapoint.TEMPERATURE); if (temperatureConfig != null) { updateItem(temperatureConfig.item, temperature); } HMSBindingConfig humidityConfig = findConfig(device, HMSBindingConfig.Datapoint.HUMIDITY); if (humidityConfig != null) { updateItem(humidityConfig.item, humidity); } } else { logger.warn("Received unparseable message: " + data); } }</code><technical_language>parameterised logging</technical_language>

Target:
protected void handleHMSMessage(String data) { if (data.startsWith("H")) { String device = data.substring(1, 5); String woHeader = data.substring(5, data.length() - 1); String s1 = woHeader.substring(0, 1); String batteryStatus = "ok"; boolean isEmpty = (s1.charAt(0) & 2) == 2; boolean isReplaced = (s1.charAt(0) & 4) == 4; if (isEmpty) { batteryStatus = "empty"; } else if (isReplaced) { batteryStatus = "replaced"; } double temperature = Integer.parseInt(woHeader.substring(5, 6) + woHeader.substring(2, 4)) / 10.0; boolean isNegative = (s1.charAt(0) & 8) == 8; if (isNegative) { temperature = -temperature; } double humidity = Integer.parseInt(woHeader.substring(6, 8) + woHeader.substring(4, 5)) / 10.0; logger.info("device: {}, T: {},\tH: {}, Bat.: {}", device, (!isNegative ? " " : "") + temperature, humidity, batteryStatus); HMSBindingConfig temperatureConfig = findConfig(device, HMSBindingConfig.Datapoint.TEMPERATURE); if (temperatureConfig != null) { updateItem(temperatureConfig.item, temperature); } HMSBindingConfig humidityConfig = findConfig(device, HMSBindingConfig.Datapoint.HUMIDITY); if (humidityConfig != null) { updateItem(humidityConfig.item, humidity); } } else { logger.warn("Received unparseable message: " + data); } }