auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Block renderNotification(CompositeEvent eventNotification) throws NotificationException { Object oldContextAttribute = scriptContextManager.getCurrentScriptContext().getAttribute(EVENT_BINDING_NAME, ScriptContext.ENGINE_SCOPE); try { scriptContextManager.getCurrentScriptContext().setAttribute(EVENT_BINDING_NAME, eventNotification, ScriptContext.ENGINE_SCOPE); <START> if (StringUtils.isBlank(this.notificationTemplate.getContent().getContent())) { <END> return ((NotificationDisplayer) this.componentManager.getInstance(NotificationDisplayer.class)) .renderNotification(eventNotification); } return templateManager.execute(notificationTemplate); } catch (Exception e) { throw new NotificationException( String.format("Unable to render notification template for the [%s].", this.eventType), e); } finally { scriptContextManager.getCurrentScriptContext().setAttribute(EVENT_BINDING_NAME, oldContextAttribute, ScriptContext.ENGINE_SCOPE); } }</code><technical_language>Instead, I create notificationTemplate if content is empty test for null notificationTemplate here</technical_language>

Target:
public Block renderNotification(CompositeEvent eventNotification) throws NotificationException { Object oldContextAttribute = scriptContextManager.getCurrentScriptContext().getAttribute(EVENT_BINDING_NAME, ScriptContext.ENGINE_SCOPE); try { scriptContextManager.getCurrentScriptContext().setAttribute(EVENT_BINDING_NAME, eventNotification, ScriptContext.ENGINE_SCOPE); if (this.notificationTemplate == null) { return ((NotificationDisplayer) this.componentManager.getInstance(NotificationDisplayer.class)) .renderNotification(eventNotification); } return templateManager.execute(notificationTemplate); } catch (Exception e) { throw new NotificationException( String.format("Unable to render notification template for the [%s].", this.eventType), e); } finally { scriptContextManager.getCurrentScriptContext().setAttribute(EVENT_BINDING_NAME, oldContextAttribute, ScriptContext.ENGINE_SCOPE); } }
Source:
<code>private void verifyFetchedLog(List<String> logs, String[] expectedLogs) { StringBuilder stringBuilder = new StringBuilder(); for (String log : logs) { stringBuilder.append(log); } String accumulatedLogs = stringBuilder.toString(); for (String expectedLog : expectedLogs) { <START> LOG.error("Checking match for " + expectedLog); <END> assertTrue(accumulatedLogs.contains(expectedLog)); } }</code><technical_language>info log</technical_language>

Target:
private void verifyFetchedLog(List<String> logs, String[] expectedLogs) { StringBuilder stringBuilder = new StringBuilder(); for (String log : logs) { stringBuilder.append(log); } String accumulatedLogs = stringBuilder.toString(); for (String expectedLog : expectedLogs) { LOG.info("Checking match for " + expectedLog); assertTrue(accumulatedLogs.contains(expectedLog)); } }
Source:
<code>public void positiveEnforcementUAGTest() { VDSGroup vdsGroup = arem.perClusterMap.keySet().iterator().next(); AffinityRulesEnforcementPerCluster perCluster = arem.perClusterMap.get(vdsGroup); VDS vds1 = _vdsDao.get(addHost(vdsGroup.getId())); VDS vds2 = _vdsDao.get(addHost(vdsGroup.getId())); final Guid vmId1 = addNewVm(vds1.getId(), true); final Guid vmId2 = addNewVm(vds1.getId(), true); final Guid vmCandidateForMigrationGuid = addNewVm(vds2.getId(), true); List<Guid> agList = new ArrayList<>(); ArrayList<Guid> vmList = <START> new ArrayList<Guid>() {{add(vmId1); add(vmId2); add(vmCandidateForMigrationGuid);}}; <END> Guid affinityGroup = addAffinityGroup(vmList, vdsGroup.getId(), true); agList.add(affinityGroup); VM candidateVm = _vmDao.get(vmCandidateForMigrationGuid); assertEquals(perCluster.chooseNextVmToMigrate(), candidateVm); }</code><technical_language>Arrays.asList(vmId1, vmId2, vmCandidateForMigrationGuid) is more readable more common. Note this returns a fix sized list</technical_language>

Target:
public void positiveEnforcementUAGTest() { VDSGroup vdsGroup = arem.perClusterMap.keySet().iterator().next(); AffinityRulesEnforcementPerCluster perCluster = arem.perClusterMap.get(vdsGroup); VDS vds1 = _vdsDao.get(addHost(vdsGroup.getId())); VDS vds2 = _vdsDao.get(addHost(vdsGroup.getId())); final Guid vmId1 = addNewVm(vds1.getId(), true); final Guid vmId2 = addNewVm(vds1.getId(), true); final Guid vmCandidateForMigrationGuid = addNewVm(vds2.getId(), true); List<Guid> agList = new ArrayList<>(); List<Guid> vmList = Arrays.asList(vmId1, vmId2, vmCandidateForMigrationGuid); Guid affinityGroup = addAffinityGroup(vmList, vdsGroup.getId(), true); agList.add(affinityGroup); VM candidateVm = _vmDao.get(vmCandidateForMigrationGuid); assertEquals(candidateVm, perCluster.chooseNextVmToMigrate()); }
Source:
<code>public boolean getEnableManagementPlugin() { <START> return getConfig(ENABLE_MANAGEMENT_PLUGIN); <END> }</code><technical_language>Worth returning Boolean.TRUE.equals(getConfig(ENABLE_MANAGEMENT_PLUGIN)) in case stupid sets ENABLE_MANAGEMENT_PLUGIN null</technical_language>

Target:
public boolean getEnableManagementPlugin() { return Boolean.TRUE.equals(getConfig(ENABLE_MANAGEMENT_PLUGIN)); }
Source:
<code>private static InputStream readFile(String path) { InputStream inputStream; ClassLoader classLoader = ServerConfigurationTest.class.getClassLoader(); inputStream = classLoader.getResourceAsStream(path); <START> return inputStream; <END> }</code><technical_language>write this code as, java ClassLoader classLoader = ServerConfigurationTest.class.getClassLoader(); return classLoader.getResourceAsStream(path); IMO this more readable</technical_language>

Target:
private InputStream readFile(String path) { ClassLoader classLoader = ServerConfigurationTest.class.getClassLoader(); return classLoader.getResourceAsStream(path); }
Source:
<code>public static void updateDatabase(Connection dbConnection, String sqlStmt, Object... params) throws UserStoreException { try ( PreparedStatement prepStmt = getPreparedStatement(dbConnection, sqlStmt,params)) { prepStmt.executeUpdate(); } catch (SQLException e) { String errorMessage = "Using sql : " + sqlStmt + " " + e.getMessage(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { <START> close(dbConnection); <END> } }</code><technical_language>connection passed a parameter this method, close connection this method. Need close connection in original place originally (create )close dbConnection</technical_language>

Target:
public static void updateDatabase(Connection dbConnection, String sqlStmt, Object... params) throws UserStoreException { try ( PreparedStatement prepStmt = getPreparedStatement(dbConnection, sqlStmt,params)) { prepStmt.executeUpdate(); } catch (SQLException e) { String errorMessage = "Using sql : " + sqlStmt + " " + e.getMessage(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } }
Source:
<code>public void connectionStateListener_OnConnectionEvent(boolean isTcpConnectionEndpointRediscoveryEnabled, RequestResponseType responseType, int times) { TcpServer server = TcpServerFactory.startNewRntbdServer(port); server.injectServerResponse(responseType); ConnectionPolicy connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); connectionPolicy.setTcpConnectionEndpointRediscoveryEnabled(isTcpConnectionEndpointRediscoveryEnabled); GlobalAddressResolver addressResolver = Mockito.mock(GlobalAddressResolver.class); SslContext sslContext = SslContextUtils.CreateSslContext("client.jks", false); Configs config = Mockito.mock(Configs.class); Mockito.doReturn(sslContext).when(config).getSslContext(); RntbdTransportClient client = new RntbdTransportClient( config, connectionPolicy, new UserAgentContainer(), addressResolver); RxDocumentServiceRequest req = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Create, ResourceType.Document, "dbs/fakedb/colls/fakeColls", getDocumentDefinition(), new HashMap<>()); req.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity("fakeCollectionId","fakePartitionKeyRangeId")); Uri targetUri = new Uri(serverUriString); try { client.invokeStoreAsync(targetUri, req).block(); } catch (Exception e) { <START> e.printStackTrace(); <END> } finally { Mockito.verify(addressResolver, Mockito.times(times)).updateAddresses(Mockito.any(), Mockito.any()); } TcpServerFactory.shutdownRntbdServer(server); }</code><technical_language>please try logger else instead of e.printStackTrace()</technical_language>

Target:
public void connectionStateListener_OnConnectionEvent( boolean isTcpConnectionEndpointRediscoveryEnabled, RequestResponseType responseType, int times) throws ExecutionException, InterruptedException { TcpServer server = TcpServerFactory.startNewRntbdServer(port); server.injectServerResponse(responseType); ConnectionPolicy connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); connectionPolicy.setTcpConnectionEndpointRediscoveryEnabled(isTcpConnectionEndpointRediscoveryEnabled); GlobalAddressResolver addressResolver = Mockito.mock(GlobalAddressResolver.class); SslContext sslContext = SslContextUtils.CreateSslContext("client.jks", false); Configs config = Mockito.mock(Configs.class); Mockito.doReturn(sslContext).when(config).getSslContext(); RntbdTransportClient client = new RntbdTransportClient( config, connectionPolicy, new UserAgentContainer(), addressResolver); RxDocumentServiceRequest req = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Create, ResourceType.Document, "dbs/fakedb/colls/fakeColls", getDocumentDefinition(), new HashMap<>()); req.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity("fakeCollectionId","fakePartitionKeyRangeId")); Uri targetUri = new Uri(serverUriString); try { client.invokeStoreAsync(targetUri, req).block(); } catch (Exception e) { logger.info("expected failed request with reason {}", e); } finally { Mockito.verify(addressResolver, Mockito.times(times)).updateAddresses(Mockito.any(), Mockito.any()); } TcpServerFactory.shutdownRntbdServer(server); }
Source:
<code>String getAgentStatusReportRequestBody(JobIdentifier identifier, String elasticAgentId, Map<String, String> clusterProfile) { JsonObject jsonObject = new JsonObject(); if (identifier != null) { jsonObject.add("job_identifier", jobIdentifierJson(identifier)); } <START> if (clusterProfile != null) { <END> jsonObject.add("cluster_profile_properties", mapToJsonObject(clusterProfile)); } jsonObject.addProperty("elastic_agent_id", elasticAgentId); return GSON.toJson(jsonObject); }</code><technical_language>if this is right place do null check. jsonObject.add("cluster_profile_properties", mapToJsonObject(clusterProfileProperties)); instead send empty map top, instead of sending null</technical_language>

Target:
String getAgentStatusReportRequestBody(JobIdentifier identifier, String elasticAgentId, Map<String, String> clusterProfile) { JsonObject jsonObject = new JsonObject(); if (identifier != null) { jsonObject.add("job_identifier", jobIdentifierJson(identifier)); } jsonObject.add("cluster_profile_properties", mapToJsonObject(clusterProfile)); jsonObject.addProperty("elastic_agent_id", elasticAgentId); return GSON.toJson(jsonObject); }
Source:
<code>public PowerMaxState handleMessage() { if (isAckRequired()) { PowerMaxCommDriver.getTheCommDriver().sendAck(this, (byte) 0x02); } <START> logger.debug("{}message handled by class {}: {}", (receiveType == null) ? "Unsupported " : "", <END> this.getClass().getSimpleName(), this.toString()); return null; }</code><technical_language>missing space message</technical_language>

Target:
public PowerMaxState handleMessage() { if (isAckRequired()) { PowerMaxCommDriver.getTheCommDriver().sendAck(this, (byte) 0x02); } if (logger.isDebugEnabled()) { logger.debug("{}message handled by class {}: {}", (receiveType == null) ? "Unsupported " : "", this.getClass().getSimpleName(), this.toString()); } return null; }
Source:
<code>public void testNegativeAggregateAgainstInverse() throws Exception { <START> UseRestriction consent = new Not(new Named("<LINK_1>")); <END> Boolean b = ONT_MODEL_CACHE.matchPurpose(new MatchWorkerMessage(resources, new MatchPair(aggregatePurpose, consent))); Assert.assertFalse(b); }</code><technical_language>aggregate_research</technical_language>

Target:
public void testNegativeAggregateAgainstInverse() throws Exception { UseRestriction consent = new Not(new Named("<LINK_0>")); Boolean b = ONT_MODEL_CACHE.matchPurpose(new MatchWorkerMessage(resources, new MatchPair(aggregatePurpose, consent))); Assert.assertFalse(b); }
Source:
<code>public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } CredentialsIdentityConfig other = (CredentialsIdentityConfig) obj; <START> if (credentials == null) { if (other.credentials != null) { return false; } } else if (!credentials.equals(other.credentials)) { return false; } <END> return true; }</code><technical_language>Objects.equals()</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } CredentialsIdentityConfig other = (CredentialsIdentityConfig) obj; return Objects.equals(credentials, other.credentials); }
Source:
<code>public void removeImportedTransaction (Xid xid) throws XAException { if (xid == null) throw new IllegalArgumentException(); AtomicReference<SubordinateTransaction> remove = _transactions.remove(new SubordinateXidImple(xid)); if (remove != null) { TransactionImple.removeTransaction((com.arjuna.ats.internal.jta.transaction.jts.TransactionImple) remove.get()); <START> } <END> }</code><technical_language>I I reviewed other PRs I wondering if is a race here. import a new xid initially put AtomicReference in map a null value: <LINK_0> happen this remove.get() call null if this is case TransactionImple.removeTransaction() call blow up</technical_language>

Target:
public void removeImportedTransaction (Xid xid) throws XAException { if (xid == null) throw new IllegalArgumentException(); AtomicReference<SubordinateTransaction> remove = _transactions.remove(new SubordinateXidImple(xid)); if (remove != null) { synchronized (remove) { com.arjuna.ats.internal.jta.transaction.jts.TransactionImple transactionImple = (com.arjuna.ats.internal.jta.transaction.jts.TransactionImple) remove.get(); while (transactionImple == null) { try { remove.wait(); transactionImple = (com.arjuna.ats.internal.jta.transaction.jts.TransactionImple) remove.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new XAException(XAException.XAER_RMFAIL); } } TransactionImple.removeTransaction(transactionImple); } } }
Source:
<code>private static void levelStatus() { if (currentGame.getCurrentLevel().getNPCs().isEmpty() && currentGame.getCurrentLevel().getEnemyBubbles().isEmpty()) { if (endTimer <= 0) { if (currentGame.remainingLevels() == 0) { Logger.getInstance().log("Player completed the game successfully."); animationTimer.stop(); winDialog(); } else { Logger.getInstance().log("Player advanced to the next level."); staticContext.setFill(Color.WHITE); staticContext.fillText(Constants.ADVANCINGLABEL, (Constants.LEVELX / 2) - 100, (Constants.LEVELY / 2) - 130); currentGame.goToNextLevel(); GameDisplay.renderStatic(); } endTimer = Constants.REFRESH_RATE * 4; } <START> endTimer--; <END> } }</code><technical_language>This is correct yet: endtimer decremented delta instead of 1 cycle, this timer is in sync StepTimer, please timestamps. I a snapshot of game.getSteps() player finishes level, compare snapshot current game.getSteps() cycle. Advance next level if difference is larger 4 times refresh_rate</technical_language>

Target:
private static void levelStatus() { Level currentLevel = currentGame.getCurrentLevel(); if (currentLevel.getNPCs().isEmpty() && currentLevel.getEnemyBubbles().isEmpty()) { if (endStepsSnapShot == 0) { staticContext.setFill(Color.WHITE); staticContext.fillText(Constants.ADVANCINGLABEL, (Constants.LEVELX / 2) - 100, (Constants.LEVELY / 2) - 130); endStepsSnapShot = currentGame.getSteps(); } if (endStepsSnapShot + Constants.REFRESH_RATE * 4 < currentGame.getSteps()) { if (currentGame.remainingLevels() == 0) { Logger.getInstance().log("Player completed the game successfully."); animationTimer.stop(); winDialog(); } else { Logger.getInstance().log("Player advanced to the next level."); currentGame.goToNextLevel(); GameDisplay.renderStatic(); } endStepsSnapShot = 0; } } }
Source:
<code>public void downloadAndReplaceSegment(String segmentName, LLCRealtimeSegmentZKMetadata llcSegmentMetadata, IndexLoadingConfig indexLoadingConfig, TableConfig tableConfig) { final String uri = llcSegmentMetadata.getDownloadUrl(); <START> if (!"PEER".equalsIgnoreCase(uri)) { <END> try { downloadSegmentFromDeepStore(segmentName, indexLoadingConfig, uri); } catch (Exception e) { if (isPeerSegmentDownloadEnabled(tableConfig)) { downloadSegmentFromPeer(segmentName, tableConfig.getValidationConfig().getPeerSegmentDownloadScheme(), indexLoadingConfig); } else { throw e; } } } else { if (isPeerSegmentDownloadEnabled(tableConfig)) { downloadSegmentFromPeer(segmentName, tableConfig.getValidationConfig().getPeerSegmentDownloadScheme(), indexLoadingConfig); } else { throw new RuntimeException("Peer segment download not enabled for segment " + segmentName); } } }</code><technical_language>"PEER" is unparseable uri, is a good idea put downloadUrl in metadata. is leave unset (or explicit set null). I suggest float metadata changes in email table config changes. I suggest change follows: (1) Change segment completion protocol mention "PEER" in uri string (or, a specific URI "peer://uri/of/server/segmentName". (2). controller, if receives a peer scheme server, segment needs committed a URI in segment metadata</technical_language>

Target:
public void downloadAndReplaceSegment(String segmentName, LLCRealtimeSegmentZKMetadata llcSegmentMetadata, IndexLoadingConfig indexLoadingConfig, TableConfig tableConfig) { final String uri = llcSegmentMetadata.getDownloadUrl(); if (!METADATA_URI_FOR_PEER_DOWNLOAD.equals(uri)) { try { downloadSegmentFromDeepStore(segmentName, indexLoadingConfig, uri); } catch (Exception e) { _logger.warn("Download segment from deepstore uri failed.", segmentName, uri, e); if (isPeerSegmentDownloadEnabled(tableConfig)) { downloadSegmentFromPeer(segmentName, tableConfig.getValidationConfig().getPeerSegmentDownloadScheme(), indexLoadingConfig); } else { throw e; } } } else { if (isPeerSegmentDownloadEnabled(tableConfig)) { downloadSegmentFromPeer(segmentName, tableConfig.getValidationConfig().getPeerSegmentDownloadScheme(), indexLoadingConfig); } else { throw new RuntimeException("Peer segment download not enabled for segment " + segmentName); } } }
Source:
<code>private void loadData( ) { for ( int i = 0; i < data.getTags().size(); i++ ) { final int idx = i; final String tag = data.getTags().get( idx ); <START> Button fullTag = new Button( tag, IconType.TRASH ); <END> fullTag.setType( ButtonType.INVERSE ); fullTag.setSize( ButtonSize.SMALL ); tags.add( fullTag ); if ( !readOnly ) { fullTag.addClickHandler( new ClickHandler() { public void onClick( final ClickEvent event ) { removeTag( idx ); } } ); } } }</code><technical_language>a small FullTag class extends Button. codes tend grow fast this is prevent this class big</technical_language>

Target:
public void loadData( ) { view.clear(); for (String tag : data.getTags()) { view.addTag( tag, readOnly ); } }
Source:
<code>long getTotalNumberOfPages(final long totalElements) { <START> return (long) Math.ceil((double) totalElements / pageSize); <END> }</code><technical_language>In Java / operator a higher predence cast operator. actually, no, [cast higher precedence division](<LINK_0> <LINK_1></technical_language>

Target:
long getTotalNumberOfPages(final long totalElements) { return (totalElements - 1 + pageSize) / pageSize; }
Source:
<code>public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) { ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); <START> Assert.isInstanceOf(BeanDefinitionRegistry.class, beanFactory); <END> BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; registry.registerBeanDefinition(JOB_LAUNCHER_TEST_UTILS_BEAN_NAME, new RootBeanDefinition(JobLauncherTestUtils.class)); registry.registerBeanDefinition(JOB_REPOSITORY_TEST_UTILS_BEAN_NAME, new RootBeanDefinition(JobRepositoryTestUtils.class)); }</code><technical_language>Need error message here</technical_language>

Target:
public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) { ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); Assert.isInstanceOf(BeanDefinitionRegistry.class, beanFactory, "The bean factory must be an instance of BeanDefinitionRegistry"); BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; registry.registerBeanDefinition(JOB_LAUNCHER_TEST_UTILS_BEAN_NAME, new RootBeanDefinition(JobLauncherTestUtils.class)); registry.registerBeanDefinition(JOB_REPOSITORY_TEST_UTILS_BEAN_NAME, new RootBeanDefinition(JobRepositoryTestUtils.class)); }
Source:
<code>public void testRange() throws Exception { Jhob[] jobs = new Jhob[100]; for (int i=0; i<jobs.length; i++) jobs[i] = new Jhob("job"+i,"aaa","bbb"); Vhew v = new Vhew("view","aaa",jobs); <START> assertResult("{_class:Vhew,jobs:[{_class:Jhob,name:job0},{_class:Jhob,name:job1},{_class:Jhob,name:job2}]}", v, "jobs[name]{,3}"); <END> assertResult("{_class:Vhew,jobs:[{_class:Jhob,name:job3},{_class:Jhob,name:job4},{_class:Jhob,name:job5}]}", v, "jobs[name]{3,6}"); assertResult("{_class:Vhew,jobs:[{_class:Jhob,name:job38}]}", v, "jobs[name]{38}"); assertResult("{_class:Vhew,jobs:[{_class:Jhob,name:job97},{_class:Jhob,name:job98},{_class:Jhob,name:job99}]}", v, "jobs[name]{97,}"); }</code><technical_language>If default is IS_NEEDED (as I read it), is _class:Jhob emitted here, is declared element type? this mode is working advertised</technical_language>

Target:
public void testRange() throws Exception { Jhob[] jobs = new Jhob[100]; for (int i=0; i<jobs.length; i++) jobs[i] = new Jhob("job"+i,"aaa","bbb"); Vhew v = new Vhew("view","aaa",jobs); assertResult("{_class:Vhew,jobs:[{name:job0},{name:job1},{name:job2}]}", v, "jobs[name]{,3}"); assertResult("{_class:Vhew,jobs:[{name:job3},{name:job4},{name:job5}]}", v, "jobs[name]{3,6}"); assertResult("{_class:Vhew,jobs:[{name:job38}]}", v, "jobs[name]{38}"); assertResult("{_class:Vhew,jobs:[{name:job97},{name:job98},{name:job99}]}", v, "jobs[name]{97,}"); }
Source:
<code>public void PutUnProcessableEntityIfIncorrectSettings() throws Exception { String token = getAuthToken(admin.getEmail(), password); <START> JSONObject json = createHarvestSettingsJson("METADATA_ONLY", "<LINK_0>", "col_1721.1_114174", "bc"); <END> getClient(token).perform( put("/api/core/collections/" + collection.getID() + "/harvester") .contentType("application/json") .content(json.toString())) .andExpect(status().isUnprocessableEntity()); }</code><technical_language>avoid mention real installation</technical_language>

Target:
public void PutUnProcessableEntityIfIncorrectSettings() throws Exception { String token = getAuthToken(admin.getEmail(), password); JSONObject json = createHarvestSettingsJson("METADATA_ONLY", "<LINK_1>", "col_1721.1_114174", "bc"); getClient(token).perform( put("/api/core/collections/" + collection.getID() + "/harvester") .contentType("application/json") .content(json.toString())) .andExpect(status().isUnprocessableEntity()); }
Source:
<code>private String resolveFile(Bundle bundle, String path) { String prefixedPath = getThemePrefixedPath(path); try { URL url = null; if (prefixedPath != null) { url = bundle.getEntry(prefixedPath); } if (url == null) { url = bundle.getEntry(path); } if (url != null) { URL localURL = FileLocator.toFileURL(url); return localURL.toString(); } <START> } catch (IOException e) { <END> } return null; }</code><technical_language>bug 487713#c11, previous revision return path in case of IOException. Do sense add return statement</technical_language>

Target:
private String resolveFile(Bundle bundle, String path) throws IOException { String prefixedPath = getThemePrefixedPath(path); URL url = null; if (prefixedPath != null) { url = bundle.getEntry(prefixedPath); } if (url == null) { url = bundle.getEntry(path); } if (url != null) { URL localURL = FileLocator.toFileURL(url); return localURL.toString(); } return null; }
Source:
<code>default B with(double data) { <START> return with( ByteBuffer.allocate(Double.BYTES).putDouble( data ).array()); <END> }</code><technical_language>I use: java return with(Double.doubleToRawLongBits(data)); for float</technical_language>

Target:
default B with(double data) { return with( Double.doubleToRawLongBits(data) ); }
Source:
<code>public boolean isNonRefAllele() { <START> return this.equals(Allele.NON_REF_ALLELE) || this.equals(Allele.UNSPECIFIED_ALTERNATE_ALLELE); <END> }</code><technical_language>qualifiers unnecessary this. is implicit Allele scope. suggestion return equals(NON_REF_ALLELE) || equals(UNSPECIFIED_ALTERNATE_ALLELE);</technical_language>

Target:
public boolean isNonRefAllele() { return equals(NON_REF_ALLELE) || equals(UNSPECIFIED_ALTERNATE_ALLELE); }
Source:
<code>public ElasticsearchSplit( @JsonProperty("table") ElasticsearchTableDescription table, @JsonProperty("index") String index, @JsonProperty("shard") int shard, @JsonProperty("searchNode") String searchNode, @JsonProperty("port") int port, @JsonProperty("tupleDomain") TupleDomain<ColumnHandle> tupleDomain) { this.shard = shard; this.table = requireNonNull(table, "table is null"); this.index = requireNonNull(index, "index is null"); this.searchNode = requireNonNull(searchNode, "searchNode is null"); <START> this.port = requireNonNull(port, "port is null"); <END> this.tupleDomain = requireNonNull(tupleDomain, "tupleDomain is null"); }</code><technical_language>port is a primitive, this null check is redundant</technical_language>

Target:
public ElasticsearchSplit( @JsonProperty("table") ElasticsearchTableDescription table, @JsonProperty("index") String index, @JsonProperty("shard") int shard, @JsonProperty("searchNode") String searchNode, @JsonProperty("port") int port, @JsonProperty("tupleDomain") TupleDomain<ColumnHandle> tupleDomain) { this.shard = shard; this.table = requireNonNull(table, "table is null"); this.index = requireNonNull(index, "index is null"); this.searchNode = requireNonNull(searchNode, "searchNode is null"); this.port = port; this.tupleDomain = requireNonNull(tupleDomain, "tupleDomain is null"); }
Source:
<code>public List<File> readKnownWorkspacesPath() { List<File> knownPath = new ArrayList<File>(); File currentWK = new File(applicationFolder + File.separator + ALL_WORKSPACE_FILENAME); if(currentWK.exists()) { BufferedReader fileReader=null; try { fileReader = new BufferedReader(new FileReader( currentWK)); String line; while((line = fileReader.readLine())!=null){ File currentDir = new File(line); if(currentDir.exists()) { knownPath.add(currentDir); } } } catch (IOException e) { <START> throw new RuntimeException("Cannot read the workspace location", e); <END> } finally{ try { if(fileReader!=null) { fileReader.close(); } } catch (IOException e) { throw new RuntimeException("Cannot read the workspace location", e); } } } return knownPath; }</code><technical_language>This exception written in logs in console output. nice add some valuable information : location of file some tips, for instance. "Check content permissions of "+currentWK+"."</technical_language>

Target:
public List<File> readKnownWorkspacesPath() { List<File> knownPath = new ArrayList<File>(); File currentWK = new File(applicationFolder + File.separator + ALL_WORKSPACE_FILENAME); if(currentWK.exists()) { BufferedReader fileReader=null; try { fileReader = new BufferedReader(new FileReader( currentWK)); String line; while((line = fileReader.readLine())!=null){ File currentDir = new File(line); if(currentDir.exists()) { knownPath.add(currentDir); } } } catch (IOException e) { throw new RuntimeException("Cannot read the workspace location "+currentWK+" .", e); } finally{ try { if(fileReader!=null) { fileReader.close(); } } catch (IOException e) { throw new RuntimeException("Cannot close the file at location"+currentWK+" .", e); } } } if(knownPath.isEmpty() && workspaceFolder!=null) { knownPath.add(new File(workspaceFolder)); } if(knownPath.isEmpty()) { knownPath.add(new File(System.getProperty("user.home"),"OrbisGIS"+File.separator)); } return knownPath; }
Source:
<code>public XmlStateProvider(ITmfTrace trace, @NonNull String stateid, IPath file) { super(trace, ITmfEvent.class, stateid); fStateId = stateid; fFilePath = file; <START> Element doc = XmlUtils.getElementInFile(fFilePath.makeAbsolute().toString(), TmfXmlStrings.STATE_PROVIDER, fStateId); <END> if (doc == null) { fLocations = new HashSet<>(); return; } ITmfXmlModelFactory modelFactory = TmfXmlModelFactoryReadWrite.getInstance(); NodeList definedStateNodes = doc.getElementsByTagName(TmfXmlStrings.DEFINED_VALUE); for (int i = 0; i < definedStateNodes.getLength(); i++) { Element element = (Element) definedStateNodes.item(i); fDefinedValues.put(element.getAttribute(TmfXmlStrings.NAME), element.getAttribute(TmfXmlStrings.VALUE)); } NodeList locationNodes = doc.getElementsByTagName(TmfXmlStrings.LOCATION); Set<TmfXmlLocation> locations = new HashSet<>(); for (int i = 0; i < locationNodes.getLength(); i++) { Element element = (Element) locationNodes.item(i); TmfXmlLocation location = modelFactory.createLocation(element, this); locations.add(location); } fLocations = Collections.unmodifiableSet(locations); NodeList nodes = doc.getElementsByTagName(TmfXmlStrings.EVENT_HANDLER); for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); TmfXmlEventHandler handler = modelFactory.createEventHandler(element, this); fEventHandlers.add(handler); } }</code><technical_language>matter in mind toString put slashes Windows i.e. C:/foo/bar.xml. converted IPath after, *should* work. toOSString puts backslashes Windows else I a bit more correct</technical_language>

Target:
public XmlStateProvider(ITmfTrace trace, @NonNull String stateid, IPath file) { super(trace, ITmfEvent.class, stateid); fStateId = stateid; fFilePath = file; Element doc = XmlUtils.getElementInFile(fFilePath.makeAbsolute().toOSString(), TmfXmlStrings.STATE_PROVIDER, fStateId); if (doc == null) { fLocations = new HashSet<>(); return; } ITmfXmlModelFactory modelFactory = TmfXmlModelFactoryReadWrite.getInstance(); NodeList definedStateNodes = doc.getElementsByTagName(TmfXmlStrings.DEFINED_VALUE); for (int i = 0; i < definedStateNodes.getLength(); i++) { Element element = (Element) definedStateNodes.item(i); fDefinedValues.put(element.getAttribute(TmfXmlStrings.NAME), element.getAttribute(TmfXmlStrings.VALUE)); } NodeList locationNodes = doc.getElementsByTagName(TmfXmlStrings.LOCATION); Set<TmfXmlLocation> locations = new HashSet<>(); for (int i = 0; i < locationNodes.getLength(); i++) { Element element = (Element) locationNodes.item(i); TmfXmlLocation location = modelFactory.createLocation(element, this); locations.add(location); } fLocations = Collections.unmodifiableSet(locations); NodeList nodes = doc.getElementsByTagName(TmfXmlStrings.EVENT_HANDLER); for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); TmfXmlEventHandler handler = modelFactory.createEventHandler(element, this); fEventHandlers.add(handler); } }
Source:
<code>public void onCreate() { super.onCreate(); <START> ACRA.init(this); <END> if (BuildConfig.DEBUG) { Traceur.enableLogging(); } ApplicationlessInjection .getInstance(this) .getCommonsApplicationComponent() .inject(this); initTimber(); ImagePipelineConfig config = ImagePipelineConfig.newBuilder(this) .setDownsampleEnabled(true) .build(); try { Fresco.initialize(this, config); } catch (Exception e) { Timber.e(e); } ContributionUtils.emptyTemporaryDirectory(); initAcra(); if (BuildConfig.DEBUG) { Stetho.initializeWithDefaults(this); } createNotificationChannel(this); if (setupLeakCanary() == RefWatcher.DISABLED) { return; } System.setProperty("in.yuvi.http.fluent.PROGRESS_TRIGGER_THRESHOLD", "3.0"); }</code><technical_language>Acra is inited line number 122</technical_language>

Target:
public void onCreate() { super.onCreate(); ACRA.init(this); if (BuildConfig.DEBUG) { Traceur.enableLogging(); } ApplicationlessInjection .getInstance(this) .getCommonsApplicationComponent() .inject(this); initTimber(); ImagePipelineConfig config = ImagePipelineConfig.newBuilder(this) .setDownsampleEnabled(true) .build(); try { Fresco.initialize(this, config); } catch (Exception e) { Timber.e(e); } ContributionUtils.emptyTemporaryDirectory(); if (BuildConfig.DEBUG && !isRoboUnitTest()) { Stetho.initializeWithDefaults(this); } createNotificationChannel(this); if (setupLeakCanary() == RefWatcher.DISABLED) { return; } System.setProperty("in.yuvi.http.fluent.PROGRESS_TRIGGER_THRESHOLD", "3.0"); }
Source:
<code>protected void delete(Context context, Integer id) throws AuthorizeException { Relationship relationship = null; try { relationship = relationshipService.find(context, id); if (relationship != null) { if (authorizeService.authorizeActionBoolean(context, relationship.getLeftItem(), Constants.WRITE) && authorizeService.authorizeActionBoolean(context, relationship.getRightItem(), Constants.WRITE)) { relationshipService.delete(context, relationship); } else { throw new AccessDeniedException("You do not have write rights on this relationship's items"); } } } catch (SQLException e) { <START> log.error(e.getMessage(), e); <END> } }</code><technical_language>prefer log a more descriptive error (again e.getMessage() null). this be: log.error("Error deleting Relationship ID:" + id, e);</technical_language>

Target:
protected void delete(Context context, Integer id) throws AuthorizeException { Relationship relationship = null; try { relationship = relationshipService.find(context, id); if (relationship != null) { try { relationshipService.delete(context, relationship); } catch (AuthorizeException e) { throw new AccessDeniedException("You do not have write rights on this relationship's items"); } } } catch (SQLException e) { log.error("Error deleting Relationship specified by ID:" + id, e); } }
Source:
<code>public void put(PageId pageId, byte[] page) throws IOException { Path p = getFilePath(pageId); if (!Files.exists(p)) { Path parent = Preconditions.checkNotNull(p.getParent(), "parent of cache file should not be null"); Files.createDirectories(parent); Files.createFile(p); } try { try (FileOutputStream fos = new FileOutputStream(p.toFile(), false)) { fos.write(page); } <START> } catch (IOException e) { <END> LOG.error("Failed to create file for page {}", p, pageId); Files.delete(p); } }</code><technical_language>catch throwable here</technical_language>

Target:
public void put(PageId pageId, byte[] page) throws IOException { Path p = getFilePath(pageId); if (!Files.exists(p)) { Path parent = Preconditions.checkNotNull(p.getParent(), "parent of cache file should not be null"); Files.createDirectories(parent); Files.createFile(p); } try { try (FileOutputStream fos = new FileOutputStream(p.toFile(), false)) { fos.write(page); } } catch (Exception e) { Files.deleteIfExists(p); throw new IOException("Failed to write file " + p + " for page " + pageId); } }
Source:
<code><START> public String getSocatContainerImage() { <END> return String.valueOf(properties.getOrDefault("socat.container.image", "alpine/socat:latest")); }</code><technical_language>Perhaps: suggestion return String.valueOf(properties.getOrDefault("socat.container.image", "alpine/socat:latest")).trim();</technical_language>

Target:
public String getSocatContainerImage() { return (String) properties.getOrDefault("socat.container.image", "alpine/socat:latest"); }
Source:
<code>@Override public Object invoke(MethodInvocation methodInvocation) throws Throwable { final Message message = (Message) methodInvocation.getArguments()[1]; final TraceContextOrSamplingFlags extracted = extractTraceContextAndRemoveHeaders(message); final Span consumerSpan = tracer.nextSpan(extracted).kind(CONSUMER).start(); tagReceivedMessageProperties(consumerSpan, message.getMessageProperties()); consumerSpan.finish(); <START> final Span serverSpan = tracer.newChild(consumerSpan.context()).kind(SERVER).start(); <END> tagReceivedMessageProperties(serverSpan, message.getMessageProperties()); try (SpanInScope ws = tracer.withSpanInScope(serverSpan)) { return methodInvocation.proceed(); } catch (Throwable t) { tagErrorSpan(serverSpan, t); throw t; } finally { serverSpan.finish(); } }</code><technical_language>I this confusing due earlier discussion, server a child of consumer, is either/or. remove kind is good (rename serverSpan listenerSpan)</technical_language>

Target:
@Override public Object invoke(MethodInvocation methodInvocation) throws Throwable { final Message message = (Message) methodInvocation.getArguments()[1]; final TraceContextOrSamplingFlags extracted = extractTraceContextAndRemoveHeaders(message); final Span consumerSpan = tracer.nextSpan(extracted).kind(CONSUMER).start(); tagReceivedMessageProperties(consumerSpan, message.getMessageProperties()); String consumerQueue = message.getMessageProperties().getConsumerQueue(); if (consumerQueue != null) consumerSpan.name(consumerQueue); consumerSpan.finish(); final Span listenerSpan = tracer.newChild(consumerSpan.context()).name("on-message").start(); try (SpanInScope ws = tracer.withSpanInScope(listenerSpan)) { return methodInvocation.proceed(); } catch (Throwable t) { tagErrorSpan(listenerSpan, t); throw t; } finally { listenerSpan.finish(); } }
Source:
<code>private boolean allowedNetworkLabelManipulation() { Network oldNetwork = getOldNetwork(); Network newNetwork = getNetwork(); <START> <END> boolean labelNotChanged = Objects.equals(oldNetwork.getLabel(), newNetwork.getLabel()); boolean newLabelAssigned = oldNetwork.getLabel() == null && newNetwork.getLabel() != null; return labelNotChanged || newLabelAssigned; }</code><technical_language>SyncNetworkParametersBuilder contains logic in labelAdded() & labelChanged() reused</technical_language>

Target:
private boolean allowedNetworkLabelManipulation() { boolean labelNotChanged = !new SyncNetworkParametersBuilder(getContext()).labelChanged(); boolean newLabelAssigned = !new SyncNetworkParametersBuilder(getContext()).labelAdded(); return !getNetwork().isExternal() && (labelNotChanged || newLabelAssigned); }
Source:
<code>private void startTrace(BuildData buildData){ if(buildData == null){ return; } Tracer tracer = GlobalTracer.get(); <START> try (Scope scope = tracer.buildSpan("JenkinsBuild").startActive(false)) { final Span span = scope.span(); span.setTag(DDTags.SERVICE_NAME, "jenkins"); DatadogUtilities.severe(logger, null, "startTrace - Cache key: " + buildData.getBuildId(null)); DatadogTraceCache.cache.put(buildData.getBuildId(null), span); } <END> }</code><technical_language>suggestion Span span = tracer.buildSpan("JenkinsBuild").withTag(DDTags.SERVICE_NAME, "jenkins").start(); // Add span cache in order retrieve in endTrace method. DatadogUtilities.severe(logger, null, "startTrace - Cache key: " + buildData.getBuildId(null)); DatadogTraceCache.cache.put(buildData.getBuildId(null), span); need scope interesting work is happening this method returns. consider adding build job id a tag span</technical_language>

Target:
private void startTrace(BuildData buildData){ if(buildData == null){ return; } Tracer tracer = GlobalTracer.get(); Span span = tracer.buildSpan("JenkinsBuild").withTag(DDTags.SERVICE_NAME, "jenkins").start(); String traceId = CorrelationIdentifier.getTraceId(); String spanId = CorrelationIdentifier.getSpanId(); DatadogUtilities.severe(logger, null, "traceId: " + traceId + " | spanId: " + spanId); span.setTag(DDTags.SERVICE_NAME, "jenkins"); DatadogUtilities.severe(logger, null, "startTrace - Cache key: " + buildData.getBuildId(null)); DatadogTraceCache.cache.put(buildData.getBuildId(null), new DatadogTraceCache.AugmentedSpan(span, traceId, spanId)); }
Source:
<code>private static String checkDescription(final String description) { if (description == null || description.isEmpty()) { return ""; <START> } else { <END> for (int i = 0; i < description.length(); i++) { final char c = description.charAt(i); if (Character.isISOControl(c) && c != '\t') { throw new IllegalArgumentException("the input name contains non-tab control characters: '" + description + "'"); } } return description; } }</code><technical_language>unnecessary else return</technical_language>

Target:
private static String checkDescription(final String description) { if (description == null || description.isEmpty()) { return ""; } for (int i = 0; i < description.length(); i++) { final char c = description.charAt(i); if (Character.isISOControl(c) && c != '\t') { throw new IllegalArgumentException("the input name contains non-tab control characters: '" + description + "'"); } } return description; }
Source:
<code>private void runScanner(Runnable action, JavaFileScanner scanner, AnalysisError.Kind kind) throws CheckFailureException { try { action.run(); } catch (IllegalRuleParameterException e) { throw new AnalysisException("Bad configuration of rule parameter", e); } catch (Exception e) { Throwable rootCause = Throwables.getRootCause(e); if (rootCause instanceof InterruptedIOException || rootCause instanceof InterruptedException) { throw e; } String ruleKey = ruleKey(scanner); String message = String.format( "Unable to run check %s - %s on file '%s', To help improve SonarJava, please report this problem to SonarSource : see <LINK_0>", scanner.getClass(), ruleKey, currentFile); LOG.error(message, e); addAnalysisError(e, currentFile, kind); throw new CheckFailureException(message, e); <START> } <END> }</code><technical_language>In current situation, if want implement this behavior, remove try/catch in visitFile(), CheckFailureException catched in JavaAstScanner::simpleScan fail fast if needed. However: - in case of IssuableSubscriptionVisitors, change is step of visit. - do want report issue a file fails SymbolicExecution checks</technical_language>

Target:
private void runScanner(Runnable action, JavaFileScanner scanner, AnalysisError.Kind kind) throws CheckFailureException { try { action.run(); } catch (IllegalRuleParameterException e) { throw new AnalysisException("Bad configuration of rule parameter", e); } catch (Exception e) { Throwable rootCause = Throwables.getRootCause(e); if (rootCause instanceof InterruptedIOException || rootCause instanceof InterruptedException) { throw e; } String message = String.format( "Unable to run check %s - %s on file '%s', To help improve SonarJava, please report this problem to SonarSource : see <LINK_0>", scanner.getClass(), ruleKey(scanner), currentFile); LOG.error(message, e); addAnalysisError(e, currentFile, kind); throw new CheckFailureException(message, e); } }
Source:
<code>public static TicketUtils getInstanceForEngineStoreSigning() throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { File store = EngineLocalConfig.getInstance().getPKIEngineStore(); String password = EngineLocalConfig.getInstance().getPKIEngineStorePassword(); String alias = EngineLocalConfig.getInstance().getPKIEngineStoreAlias(); <START> return new TicketUtils(store, password, alias, 120); <END> }</code><technical_language>Please hard code, ConfigValues</technical_language>

Target:
public static TicketUtils getInstanceForEngineStoreSigning() throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { File store = EngineLocalConfig.getInstance().getPKIEngineStore(); String password = EngineLocalConfig.getInstance().getPKIEngineStorePassword(); String alias = EngineLocalConfig.getInstance().getPKIEngineStoreAlias(); Integer lifetime = Config.<Integer> GetValue (ConfigValues.WebSocketProxyTicketValiditySeconds); return new TicketUtils(store, password, alias, lifetime); }
Source:
<code>private Logger getLogger(final ClassLoader resolvedCtxClassLoader) { if (useThisLoggerContextClassLoader(resolvedCtxClassLoader)) { return originalLogger; } Reference<Logger> loggerReference = loggerCache.get(resolvedCtxClassLoader); Logger logger = loggerReference.get(); if (logger == null) { synchronized (loggerReference) { logger = loggerReference.get(); if (logger == null) { try { logger = resolveLogger(resolvedCtxClassLoader); } catch (RecursiveLoggerContextInstantiationException rle) { <START> return resolveLogger(ClassLoader.getSystemClassLoader()); <END> } loggerReference.set(logger); } } } return logger; }</code><technical_language>static import</technical_language>

Target:
private Logger getLogger(final ClassLoader resolvedCtxClassLoader) { if (useThisLoggerContextClassLoader(resolvedCtxClassLoader)) { return originalLogger; } Reference<Logger> loggerReference = loggerCache.get(resolvedCtxClassLoader); Logger logger = loggerReference.get(); if (logger == null) { synchronized (loggerReference) { logger = loggerReference.get(); if (logger == null) { try { logger = resolveLogger(resolvedCtxClassLoader); } catch (RecursiveLoggerContextInstantiationException rle) { return resolveLogger(this.getClass().getClassLoader()); } loggerReference.set(logger); } } } return logger; }
Source:
<code>public void afterBeanDiscovery(@Observes ExperimentalAfterBeanDiscovery event, BeanManager beanManager) { AnnotatedType<Foo> annotatedType = beanManager.createAnnotatedType(Foo.class); event.<Foo> addBean().read(annotatedType).name("bar"); BeanBuilder<Foo> builder = event.<Foo> beanBuilder().read(annotatedType); builder.id("BAZinga").addQualifier(Juicy.Literal.INSTANCE); event.addBean(builder.build()); event.<Integer> addBean().addType(Integer.class).addQualifier(Random.Literal.INSTANCE) .produceWith(() -> new java.util.Random().nextInt(1000)).disposeWith((i) -> DISPOSED.set(true)); event.<Long> addBean().addType(Long.class).addQualifier(AnotherRandom.Literal.INSTANCE) <START> .produceWith((i) -> i.select(Foo.class, Juicy.Literal.INSTANCE).get().getId() * 2); <END> }</code><technical_language>I API</technical_language>

Target:
public void afterBeanDiscovery(@Observes ExperimentalAfterBeanDiscovery event, BeanManager beanManager) { AnnotatedType<Foo> annotatedType = beanManager.createAnnotatedType(Foo.class); event.<Foo> addBean().beanClass(Foo.class).read(beanManager.createBeanAttributes(annotatedType)).name("bar") .stereotypes(Collections.emptySet()).scope(Dependent.class).produceWith(() -> { Foo foo = new Foo(); foo.postConstruct(); return foo; }); BeanBuilder<Foo> builder = event.<Foo> beanBuilder().read(annotatedType); builder.id("BAZinga").addQualifier(Juicy.Literal.INSTANCE); event.addBean(builder.build()); event.<Integer> addBean().addType(Integer.class).addQualifier(Random.Literal.INSTANCE) .produceWith(() -> new java.util.Random().nextInt(1000)).disposeWith((i) -> DISPOSED.set(true)); event.<Long> addBean().addType(Long.class).addQualifier(AnotherRandom.Literal.INSTANCE) .produceWith((i) -> i.select(Foo.class, Juicy.Literal.INSTANCE).get().getId() * 2); }