auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void send(final RequestMessage requestMessage, final String messageType, final int messagePriority, final Long scheduleTime, final boolean bypassRetry) { this.osgpCoreRequestsJmsTemplate.setPriority(messagePriority); <START> this.osgpCoreRequestsJmsTemplate.send(new MessageCreator() { <END> @Override public Message createMessage(final Session session) throws JMSException { final ObjectMessage objectMessage = session.createObjectMessage(); objectMessage.setJMSType(messageType); objectMessage.setJMSCorrelationID(requestMessage.getCorrelationUid()); objectMessage.setStringProperty(Constants.ORGANISATION_IDENTIFICATION, requestMessage.getOrganisationIdentification()); objectMessage.setStringProperty(Constants.DEVICE_IDENTIFICATION, requestMessage.getDeviceIdentification()); objectMessage.setBooleanProperty(Constants.BY_PASS_RETRY, bypassRetry); if (scheduleTime != null) { objectMessage.setLongProperty(Constants.SCHEDULE_TIME, scheduleTime); } objectMessage.setStringProperty(Constants.IP_ADDRESS, requestMessage.getIpAddress()); objectMessage.setObject(requestMessage.getRequest()); return objectMessage; } }); }</code><technical_language>![MAJOR](<LINK_1> Reduce this anonymous class number of lines 22 20, a named class. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public void send(final RequestMessage requestMessage, final String messageType, final int messagePriority, final Long scheduleTime, final boolean bypassRetry) { this.osgpCoreRequestsJmsTemplate.setPriority(messagePriority); this.osgpCoreRequestsJmsTemplate.send(new MessageCreator() { @Override public Message createMessage(final Session session) throws JMSException { final ObjectMessage objectMessage = session.createObjectMessage(); objectMessage.setJMSType(messageType); objectMessage.setJMSCorrelationID(requestMessage.getCorrelationUid()); objectMessage.setStringProperty(Constants.ORGANISATION_IDENTIFICATION, requestMessage.getOrganisationIdentification()); objectMessage.setStringProperty(Constants.DEVICE_IDENTIFICATION, requestMessage.getDeviceIdentification()); objectMessage.setBooleanProperty(Constants.BYPASS_RETRY, bypassRetry); if (scheduleTime != null) { objectMessage.setLongProperty(Constants.SCHEDULE_TIME, scheduleTime); } objectMessage.setStringProperty(Constants.IP_ADDRESS, requestMessage.getIpAddress()); objectMessage.setObject(requestMessage.getRequest()); return objectMessage; } }); }
Source:
<code>public boolean awaitInactivity(long timeout, TimeUnit unit) throws InterruptedException { final Thread thread = this.thread; if (thread == null) { throw new IllegalStateException("thread was not started"); } <START> thread.join(ObjectUtil.checkNotNull(unit, "unit").toMillis(timeout)); <END> return !thread.isAlive(); }</code><technical_language>move null check action in method change behaviour</technical_language>

Target:
public boolean awaitInactivity(long timeout, TimeUnit unit) throws InterruptedException { ObjectUtil.checkNotNull(unit, "unit"); final Thread thread = this.thread; if (thread == null) { throw new IllegalStateException("thread was not started"); } thread.join(unit.toMillis(timeout)); return !thread.isAlive(); }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { Repository repository = getRepository(event); if (repository != null) for (Object selected : getSelection(getPage()).toList()) try { RevCommit selectedCommit = (RevCommit) selected; <START> RevWalk revWalk = new RevWalk(repository); <END> RevCommit reparsedCommit = revWalk.parseCommit(selectedCommit.getId()); CommitEditor.open(new RepositoryCommit(repository, reparsedCommit)); } catch (IOException e) { Activator.showError("Error opening commit viewer", e); } catch (PartInitException e) { Activator.showError("Error opening commit viewer", e); } return null; }</code><technical_language>RevWalk instance for selected commits</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { Repository repository = getRepository(event); if (repository != null) { RevWalk revWalk = new RevWalk(repository); for (Object selected : getSelection(getPage()).toList()) try { RevCommit selectedCommit = (RevCommit) selected; RevCommit reparsedCommit = revWalk.parseCommit(selectedCommit.getId()); CommitEditor.open(new RepositoryCommit(repository, reparsedCommit)); } catch (IOException e) { Activator.showError("Error opening commit viewer", e); } catch (PartInitException e) { Activator.showError("Error opening commit viewer", e); } } return null; }
Source:
<code>public ResourceResponse retrieveResource( URI resourceUri, Map<String, Serializable> requestProperties) throws IOException, ResourceNotFoundException, ResourceNotSupportedException { Serializable serializableId = null; String username = cswSourceConfiguration.getUsername(); String password = cswSourceConfiguration.getPassword(); if (requestProperties != null) { serializableId = requestProperties.get(Core.ID); if (StringUtils.isNotBlank(username)) { requestProperties.put(USERNAME_PROPERTY, username); requestProperties.put(PASSWORD_PROPERTY, password); } } else { requestProperties = new HashMap<>(); } if (canRetrieveResourceById()) { if (serializableId == null) { throw new ResourceNotFoundException( "Unable to retrieve resource because no metacard ID was found."); } String metacardId = serializableId.toString(); LOGGER.debug("Retrieving resource for ID : {}", metacardId); ResourceResponse response = retrieveResourceById(requestProperties, metacardId); if (response != null) { return response; } } if (resourceUri == null) { <START> throw new IOException("Unable to retrieve resource because no resource URI was given"); <END> } LOGGER.debug("Retrieving resource at : {}", resourceUri); return resourceReader.retrieveResource(resourceUri, requestProperties); }</code><technical_language>consider IllegalArgumentException</technical_language>

Target:
public ResourceResponse retrieveResource( URI resourceUri, Map<String, Serializable> requestProperties) throws IOException, ResourceNotFoundException, ResourceNotSupportedException { if (resourceUri == null) { throw new IllegalArgumentException( "Unable to retrieve resource because no resource URI was given"); } Serializable serializableId = null; String username = cswSourceConfiguration.getUsername(); String password = cswSourceConfiguration.getPassword(); if (requestProperties != null) { serializableId = requestProperties.get(Core.ID); if (StringUtils.isNotBlank(username)) { requestProperties.put(USERNAME_PROPERTY, username); requestProperties.put(PASSWORD_PROPERTY, password); } } else { requestProperties = new HashMap<>(); } if (canRetrieveResourceById()) { if (serializableId == null) { throw new ResourceNotFoundException( "Unable to retrieve resource because no metacard ID was found."); } String metacardId = serializableId.toString(); LOGGER.debug("Retrieving resource for ID : {}", metacardId); ResourceResponse response = retrieveResourceById(requestProperties, metacardId); if (response != null) { return response; } } LOGGER.debug("Retrieving resource at : {}", resourceUri); return resourceReader.retrieveResource(resourceUri, requestProperties); }
Source:
<code>long createDetectionConfig(@NotNull String payload, long startTime, long endTime) throws Exception { if (!this.onboardingRateLimiter.tryAcquire()) { <START> throw new RuntimeException("Server is busy handling create detection requests. Please retry later."); <END> } DetectionConfigDTO detectionConfig = buildDetectionConfigFromYaml(startTime, endTime, payload, null); List<DetectionConfigDTO> detectionConfigDTOS = detectionConfigDAO .findByPredicate(Predicate.EQ("name", detectionConfig.getName())); Preconditions.checkArgument(detectionConfigDTOS.isEmpty(), "Detection name is already taken. Please use a different detectionName."); detectionValidator.validateConfig(detectionConfig); Long id = this.detectionConfigDAO.save(detectionConfig); Preconditions.checkNotNull(id, "Error while saving the detection pipeline"); createYamlOnboardingTask(detectionConfig.getId(), startTime, endTime); return detectionConfig.getId(); }</code><technical_language>put rate limit in error message</technical_language>

Target:
long createDetectionConfig(@NotNull String payload, long startTime, long endTime) throws Exception { if (!this.onboardingRateLimiter.tryAcquire()) { throw new RuntimeException( String.format("Server is busy handling create detection requests. Please retry later. QPS quota: %f", this.onboardingRateLimiter.getRate())); } DetectionConfigDTO detectionConfig = buildDetectionConfigFromYaml(startTime, endTime, payload, null); List<DetectionConfigDTO> detectionConfigDTOS = detectionConfigDAO .findByPredicate(Predicate.EQ("name", detectionConfig.getName())); Preconditions.checkArgument(detectionConfigDTOS.isEmpty(), "Detection name is already taken. Please use a different detectionName."); detectionValidator.validateConfig(detectionConfig); Long id = this.detectionConfigDAO.save(detectionConfig); Preconditions.checkNotNull(id, "Error while saving the detection pipeline"); createYamlOnboardingTask(detectionConfig.getId(), startTime, endTime); return detectionConfig.getId(); }
Source:
<code>public void onActivityPaused(Activity activity) { if (clientInstance == null) { Log.e(TAG, NULLMSG); return; } <START> clientInstance.refreshSessionTime(getCurrentTimeMillis()); <END> clientInstance.setInForeground(false); }</code><technical_language>I feel this class delegate a clientInstance.onExitForeground(...) / clientInstance.onEnterForeground(...) lines in methods</technical_language>

Target:
public void onActivityPaused(Activity activity) { if (clientInstance == null) { Log.e(TAG, NULLMSG); return; } clientInstance.onExitForeground(getCurrentTimeMillis()); }
Source:
<code>private DataProviderLookup loadProviderLookup(Class<?> holderType) { <START> Stream<DataProvider> stream = this.dataProviders.keySet().stream() <END> .map(key -> this.getProvider((Key) key, holderType)) .filter(provider -> !(provider instanceof EmptyDataProvider)); return new DataProviderLookup(stream.collect(Collectors.toMap(p -> (Key<?>) p.getKey(), p -> (DataProvider<?, ?>) p))); }</code><technical_language>suggestion final Stream<DataProvider> stream = this.dataProviders.keySet().stream()</technical_language>

Target:
private DataProviderLookup loadProviderLookup(Class<?> holderType) { final Stream<DataProvider> stream = this.dataProviders.keySet().stream() .map(key -> this.getProvider((Key) key, holderType)) .filter(provider -> !(provider instanceof EmptyDataProvider)); final Map<Key<?>, DataProvider<?, ?>> map = stream.collect(Collectors.toMap(p -> (Key<?>) p.getKey(), p -> (DataProvider<?, ?>) p)); return new DataProviderLookup(map); }
Source:
<code>public void onMessage(String message) { <START> System.out.println(message); <END> logger.debug("[{}]: Message received: {}", xbmc.getHostname(), message); Map<String, Object> json; try { json = mapper.readValue(message, Map.class); } catch (JsonParseException e) { logger.error("Error parsing JSON", e); return; } catch (JsonMappingException e) { logger.error("Error mapping JSON", e); return; } catch (IOException e) { logger.error("An I/O error occured while decoding JSON", e); return; } try { if (json.containsKey("method")) { String method = (String)json.get("method"); if (method.startsWith("Player.On")) { processPlayerStateChanged(method, json); } else if (method.startsWith("Application.On")) { processApplicationStateChanged(method, json); } else if (method.startsWith("System.On")) { processSystemStateChanged(method, json); }else if (method.startsWith("GUI.OnScreensaver")){ processScreensaverStateChanged(method, json); } } } catch (Exception e) { logger.error("Error handling player state change message", e); } }</code><technical_language>This println here,</technical_language>

Target:
public void onMessage(String message) { logger.debug("[{}]: Message received: {}", xbmc.getHostname(), message); Map<String, Object> json; try { json = mapper.readValue(message, Map.class); } catch (JsonParseException e) { logger.error("Error parsing JSON", e); return; } catch (JsonMappingException e) { logger.error("Error mapping JSON", e); return; } catch (IOException e) { logger.error("An I/O error occured while decoding JSON", e); return; } try { if (json.containsKey("method")) { String method = (String)json.get("method"); if (method.startsWith("Player.On")) { processPlayerStateChanged(method, json); } else if (method.startsWith("Application.On")) { processApplicationStateChanged(method, json); } else if (method.startsWith("System.On")) { processSystemStateChanged(method, json); }else if (method.startsWith("GUI.OnScreensaver")){ processScreensaverStateChanged(method, json); } } } catch (Exception e) { logger.error("Error handling player state change message", e); } }
Source:
<code>public QuotaTariffVO findTariffPlanByUsageType(final int quotaType, final Date effectiveDate) { final short opendb = TransactionLegacy.currentTxn().getDatabaseId(); List<QuotaTariffVO> result = new ArrayList<>(); try (TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB)) { final Filter filter = new Filter(QuotaTariffVO.class, "effectiveOn", false, 0L, 1L); final SearchCriteria<QuotaTariffVO> sc = listAllIncludedUsageType.create(); sc.setParameters("onorbefore", effectiveDate); sc.setParameters("quotatype", quotaType); result = search(sc, filter); } catch (Exception e) { throw new CloudRuntimeException("Unable to find tariff plan by usage type"); } finally { TransactionLegacy.open(opendb).close(); } if (result.size() > 0) { if (s_logger.isDebugEnabled()){ s_logger.debug("QuotaTariffDaoImpl::findTariffPlanByUsageType: " + effectiveDate + "quota type " + quotaType + " val=" + result.get(0).getCurrencyValue()); } return result.get(0); } else { if (s_logger.isDebugEnabled()){ <START> s_logger.info("QuotaTariffDaoImpl::findTariffPlanByUsageType: Missing quota type " + quotaType); <END> } return null; } }</code><technical_language>This log statement is wrapped in a isDebugEnabled check, logged INFO. logged DEBUG isDebugEnabled check removed</technical_language>

Target:
public QuotaTariffVO findTariffPlanByUsageType(final int quotaType, final Date effectiveDate) { return Transaction.execute(TransactionLegacy.USAGE_DB, new TransactionCallback<QuotaTariffVO>() { @Override public QuotaTariffVO doInTransaction(final TransactionStatus status) { List<QuotaTariffVO> result = new ArrayList<>(); final Filter filter = new Filter(QuotaTariffVO.class, "updatedOn", false, 0L, 1L); final SearchCriteria<QuotaTariffVO> sc = listAllIncludedUsageType.create(); sc.setParameters("onorbefore", effectiveDate); sc.setParameters("quotatype", quotaType); result = search(sc, filter); if (result != null && !result.isEmpty()) { return result.get(0); } else { if (s_logger.isDebugEnabled()) { s_logger.debug("QuotaTariffDaoImpl::findTariffPlanByUsageType: Missing quota type " + quotaType); } return null; } } }); }
Source:
<code>public String getIpv6DefaultGateway() { List<String> routes = ExecutingCommand.runNative("route -A inet6 -n"); if(routes.size() <= 2){ return ""; } String gateway = ""; int minMetric = Integer.MAX_VALUE; for(int i = 2; i < routes.size(); i++){ String[] fields = routes.get(i).split("\\s+"); if(fields.length > 3 && fields[0].equals("::/0")) { try{ boolean isGateway = fields[2].indexOf('G') != -1; <START> int metric = Integer.parseInt(fields[3]); <END> if(isGateway && (metric < minMetric)){ minMetric = metric; gateway = fields[1]; } } catch (NumberFormatException ignored){} } } return gateway; }</code><technical_language>ParseUtil.parseIntOrDefault() handles exception simplify code</technical_language>

Target:
public String getIpv6DefaultGateway() { List<String> routes = ExecutingCommand.runNative("route -A inet6 -n"); if (routes.size() <= 2) { return ""; } String gateway = ""; int minMetric = Integer.MAX_VALUE; for (int i = 2; i < routes.size(); i++) { String[] fields = routes.get(i).split("\\s+"); if (fields.length > 3 && fields[0].equals(IPV6_DEFAULT_DEST)) { boolean isGateway = fields[2].indexOf('G') != -1; int metric = ParseUtil.parseIntOrDefault(fields[3], Integer.MAX_VALUE); if (isGateway && (metric < minMetric)) { minMetric = metric; gateway = fields[1]; } } } return gateway; }
Source:
<code>public static Duration getExpiry(ExpiryPolicy policy, Operation op) { if (policy == null) { return getDefaultDuration(); } switch (op) { case CREATION: try { return policy.getExpiryForCreation(); } catch (Throwable t) { <START> log.log(Level.WARNING, "Exception while getting expiry for creation. Fallback to default duration eternal.", t); <END> return getDefaultDuration(); } case ACCESS: try { return policy.getExpiryForAccess(); } catch (Throwable t) { log.log(Level.WARNING, "Exception while getting expiry for access. Fallback to null.", t); return null; } case UPDATE: try { return policy.getExpiryForUpdate(); } catch (Exception e) { log.log(Level.WARNING, "Exception while getting expiry for update. Fallback to null.", e); return null; } default: throw log.unknownExpiryOperation(op.toString()); } }</code><technical_language>messages info level need localized; please default: case for example (that throws localized exception, plain messages different)</technical_language>

Target:
public static Duration getExpiry(ExpiryPolicy policy, Operation op) { if (policy == null) { return getDefaultDuration(); } switch (op) { case CREATION: try { return policy.getExpiryForCreation(); } catch (Throwable t) { log.getExpiryHasThrown(t); return getDefaultDuration(); } case ACCESS: try { return policy.getExpiryForAccess(); } catch (Throwable t) { log.getExpiryHasThrown(t); return null; } case UPDATE: try { return policy.getExpiryForUpdate(); } catch (Throwable t) { log.getExpiryHasThrown(t); return null; } default: throw log.unknownExpiryOperation(op.toString()); } }
Source:
<code>public List<Integer> getListOfSurahWithStartingOnPage(int page) { <START> List<Integer> result = new ArrayList<>(); <END> for (int i = 0; i < Constants.SURAS_COUNT; i++) { if(suraPageStart[i] == page) { result.add(i + 1); } } return result; }</code><technical_language>this more efficient if do like: int startSura = pageSuraStart[page - 1]; start loop i = startSura instead of 0. also, hit a sura start page > page, break out of loop</technical_language>

Target:
public List<Integer> getListOfSurahWithStartingOnPage(int page) { int startIndex = pageSuraStart[page - 1] - 1; List<Integer> result = new ArrayList<>(); for (int i = startIndex; i < Constants.SURAS_COUNT; i++) { if (suraPageStart[i] == page) { result.add(i + 1); } else if (suraPageStart[i] > page) break; } return result; }
Source:
<code>public String getInvalidityInfoForNationality(String nationality) { <START> Assumption.assertTrue("Non-null value expected", nationality != null); <END> if (!NationalityHelper.getNationalities().contains(nationality)) { return String.format(NATIONALITY_ERROR_MESSAGE, nationality); } return ""; }</code><technical_language>Change this Assumption.assertNotNull</technical_language>

Target:
public String getInvalidityInfoForNationality(String nationality) { Assumption.assertNotNull("Non-null value expected", nationality); if (!NationalityHelper.getNationalities().contains(nationality)) { return String.format(NATIONALITY_ERROR_MESSAGE, nationality); } return ""; }
Source:
<code>protected List<? extends Module> getModules() { return ImmutableList.<Module>of( new DruidProcessingModule(), new QueryableModule(), new QueryRunnerFactoryModule(), binder -> { JsonConfigProvider.bindInstance( <START> binder, Key.get(MetadataStorageConnectorConfig.class), new MetadataStorageConnectorConfig() <END> { @Override public String getConnectURI() { return connectURI; } @Override public String getUser() { return user; } @Override public String getPassword() { return password; } } ); JsonConfigProvider.bindInstance( binder, Key.get(MetadataStorageTablesConfig.class), MetadataStorageTablesConfig.fromBase(base) ); JsonConfigProvider.bindInstance( binder, Key.get(DruidNode.class, Self.class), new DruidNode("tools", "localhost", -1, null, true, false) ); } ); }</code><technical_language>Please break line comma below: binder, Key.get(MetadataStorageConnectorConfig.class), new MetadataStorageConnectorConfig() { }</technical_language>

Target:
protected List<? extends Module> getModules() { return ImmutableList.of( new DruidProcessingModule(), new QueryableModule(), new QueryRunnerFactoryModule(), binder -> { JsonConfigProvider.bindInstance( binder, Key.get(MetadataStorageConnectorConfig.class), new MetadataStorageConnectorConfig() { @Override public String getConnectURI() { return connectURI; } @Override public String getUser() { return user; } @Override public String getPassword() { return password; } } ); JsonConfigProvider.bindInstance( binder, Key.get(MetadataStorageTablesConfig.class), MetadataStorageTablesConfig.fromBase(base) ); JsonConfigProvider.bindInstance( binder, Key.get(DruidNode.class, Self.class), new DruidNode("tools", "localhost", -1, null, true, false) ); } ); }
Source:
<code>private void saveDevicesToDb(Change change) { if (!change.getDevicesToUpdate().isEmpty()) { getVmDeviceDao().updateAllInBatch(change.getDevicesToUpdate()); } if (!change.getDeviceIdsToRemove().isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, () -> { getVmDeviceDao().removeAll(change.getDeviceIdsToRemove()); return null; }); } if (!change.getDevicesToAdd().isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, () -> { getVmDeviceDao().saveAll(change.getDevicesToAdd()); return null; }); } if (!change.getVmsToSaveHash().isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, () -> { getVmDynamicDao().updateDevicesHashes(change.getVmsToSaveHash().stream() .map(vmId -> new Pair<>(vmId, vmDevicesStatuses.get(vmId).getHash())) .collect(Collectors.toList())); return null; }); for(Guid vmId : change.getVmsToSaveHash()) { <START> getVmStaticDao().incrementDbGeneration(vmId); <END> } } }</code><technical_language>performance: 1. is a bad practice call a dao a loop. 2. ideally generation in vm_dynamic table, belongs, updated hash generation in call. unfortunately, is defined in vm_static table requires more calls database. correctness: for nitpicking is engine restarted persisting hash updating db generation. in case, engine start again, ovf created devices change again. I care correctness part in this case (msivak - do you?). performance part bothers me. I suggest realistic options: 1. introduce another procedure increment generation of multiple VMs, updateDevicesHashes (this improves performance) + move this call in transaction call updateDevicesHashes (correctness) 2. increment DB generation stored procedure is called updateDevicesHashes - readable I know, need rename it. I prefer #2 I point in updating hashes in a transaction - a mistake. updating generation in stored procedure this of device hash - achieve desired atomicity able drop redundant transaction</technical_language>

Target:
private void saveDevicesToDb(Change change) { if (!change.getDevicesToUpdate().isEmpty()) { getVmDeviceDao().updateAllInBatch(change.getDevicesToUpdate()); } if (!change.getDeviceIdsToRemove().isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, () -> { getVmDeviceDao().removeAll(change.getDeviceIdsToRemove()); return null; }); } if (!change.getDevicesToAdd().isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, () -> { getVmDeviceDao().saveAll(change.getDevicesToAdd()); return null; }); } if (!change.getVmsToSaveHash().isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, () -> { getVmDynamicDao().updateDevicesHashes(change.getVmsToSaveHash().stream() .map(vmId -> new Pair<>(vmId, vmDevicesStatuses.get(vmId).getHash())) .collect(Collectors.toList())); return null; }); TransactionSupport.executeInScope(TransactionScopeOption.Required, () -> { getVmStaticDao().incrementDbGenerationForVms(change.getVmsToSaveHash()); return null; }); } }
Source:
<code>private UserSession getUserSessionNewVersion(String sessionToken) { checkNotNull(sessionToken); <START> try { <END> CacheKey tokenToUserIdKey = CacheKey.tokenToUserId(sessionToken); String userId = jedisOps.get(tokenToUserIdKey.toString()); if (userId != null) { CacheKey userIdToSessionKey = CacheKey.userIdToSession(userId); String ser = jedisOps.get(userIdToSessionKey.toString()); if (ser != null) { UserSession session = BridgeObjectMapper.get().readValue(ser, UserSession.class); if (session.getSessionToken().equals(sessionToken)) { return session; } jedisOps.del(tokenToUserIdKey.toString()); } } return null; } catch (Throwable e) { promptToStartRedisIfLocal(e); throw new BridgeServiceException(e); } }</code><technical_language>Do need unit tests for new get methods? include cases: * session token * user ID session * session ID mismatch * session successfully retrieved</technical_language>

Target:
UserSession getUserSessionNewVersion(String sessionToken) { checkNotNull(sessionToken); try { CacheKey tokenToUserIdKey = CacheKey.tokenToUserId(sessionToken); String userId = jedisOps.get(tokenToUserIdKey.toString()); if (userId != null) { CacheKey userIdToSessionKey = CacheKey.userIdToSession(userId); String ser = jedisOps.get(userIdToSessionKey.toString()); if (ser != null) { UserSession session = BridgeObjectMapper.get().readValue(ser, UserSession.class); if (session.getSessionToken().equals(sessionToken)) { return session; } jedisOps.del(tokenToUserIdKey.toString()); } } return null; } catch (Throwable e) { promptToStartRedisIfLocal(e); throw new BridgeServiceException(e); } }
Source:
<code>private void postDragEventQueue(int type, Event event) { if (dragDetectionQueue == null) dragDetectionQueue = new Event [4]; event.type = type; int index = 0; int length = dragDetectionQueue.length; <START> while (index < length) { if (dragDetectionQueue [index] == null) break; index++; } if (index == length) { Event newQueue = new Event [length + 4]; System.arraycopy (dragDetectionQueue, 0, newQueue, 0, length); dragDetectionQueue = newQueue; } <END> dragDetectionQueue [index] = event; }</code><technical_language>I this replaced LinkedList instead. For efficiency clarity</technical_language>

Target:
private void postDragEventQueue(int type, Event event) { if (dragDetectionQueue == null) dragDetectionQueue = new LinkedList<>(); event.type = type; dragDetectionQueue.add(event); }
Source:
<code>private static void log(final RqFallback req) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final Throwable error = req.throwable(); final PrintWriter writer = new PrintWriter(baos); error.printStackTrace(writer); writer.close(); FbLog4j.LOGGER.error( <START> String.format( <END> "%s %s failed with %s: %s", new RqMethod.Base(req).method(), new RqHref.Base(req).href(), req.code(), baos.toString("UTF-8") ) ); }</code><technical_language>@piddubnyi this entire String.format block moved (4 spaces)</technical_language>

Target:
private static void log(final RqFallback req) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final Throwable error = req.throwable(); final PrintWriter writer = new PrintWriter(baos); error.printStackTrace(writer); writer.close(); Logger.getLogger(FbLog4j.class).error( String.format( "%s %s failed with %s: %s", new RqMethod.Base(req).method(), new RqHref.Base(req).href(), req.code(), baos.toString("UTF-8") ) ); }
Source:
<code>private PomModel resolvePom(String path) throws Exception { try (InputStream pomInputStream = this.getClass().getClassLoader().getResourceAsStream(path)) { return PomModelResolver.resolveFromPom(pomInputStream); <START> } catch (Exception e) { <END> throw e; } }</code><technical_language>remove catch clause rethrows exception</technical_language>

Target:
private PomModel resolvePom(String path) throws Exception { InputStream pomInputStream = this.getClass().getClassLoader().getResourceAsStream(path); return PomModelResolver.resolveFromPom(pomInputStream); }
Source:
<code>public boolean equals(Object obj) { <START> if (this == obj) <END> return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; QueryEvaluationHint other = (QueryEvaluationHint) obj; if (backendHintSettings == null) { if (other.backendHintSettings != null) return false; } else if (!backendHintSettings.equals(other.backendHintSettings)) return false; if (queryBackendFactory == null) { if (other.queryBackendFactory != null) return false; } else if (!queryBackendFactory.equals(other.queryBackendFactory)) return false; return true; }</code><technical_language>Objects.equals() instead (available Java 7). this kind of code more compact readable</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; QueryEvaluationHint other = (QueryEvaluationHint) obj; if (!Objects.equals(backendHintSettings, other.backendHintSettings)) return false; if (!Objects.equals(queryBackendFactory, other.queryBackendFactory)) return false; return true; }
Source:
<code>public List<MetricFamilySamples> collect() { CounterMetricFamily safepointCount = new CounterMetricFamily( "jvm_safepoint_count", "The number of safepoints taken place since the JVM started.", hotspotRuntimeMBean.getSafepointCount()); CounterMetricFamily safepointTime = new CounterMetricFamily( <START> "jvm_safepoint_total_time_seconds", <END> "The accumulated time spent at safepoints in seconds. This is the accumulated elapsed time that the application has been stopped for safepoint operations.", hotspotRuntimeMBean.getTotalSafepointTime() / MILLISECONDS_PER_SECOND); CounterMetricFamily safepointSyncTime = new CounterMetricFamily( "jvm_safepoint_sync_time_seconds", "The accumulated time spent getting to safepoints in seconds.", hotspotRuntimeMBean.getSafepointSyncTime() / MILLISECONDS_PER_SECOND); List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>(); mfs.add(safepointCount); mfs.add(safepointTime); mfs.add(safepointSyncTime); return mfs; }</code><technical_language>total is a confusing, remove it. more sense Summary</technical_language>

Target:
public List<MetricFamilySamples> collect() { SummaryMetricFamily safepoint = new SummaryMetricFamily( "jvm_safepoint_seconds", "The accumulated time spent at safepoints in seconds. This is the accumulated elapsed time that the application has been stopped for safepoint operations. (count: The number of safepoints taken place since the JVM started.", Collections.EMPTY_LIST); safepoint.addMetric( Collections.EMPTY_LIST, hotspotRuntimeMBean.getSafepointCount(), hotspotRuntimeMBean.getTotalSafepointTime() / MILLISECONDS_PER_SECOND); CounterMetricFamily safepointSyncTime = new CounterMetricFamily( "jvm_safepoint_sync_time_seconds", "The accumulated time spent getting to safepoints in seconds.", hotspotRuntimeMBean.getSafepointSyncTime() / MILLISECONDS_PER_SECOND); List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>(); mfs.add(safepoint); mfs.add(safepointSyncTime); return mfs; }
Source:
<code><START> void should_fail_if_actual_has_message_containing_description() { <END> AssertionInfo info = someInfo(); try { throwables.assertHasMessageNotContaining(info, actual, "message"); fail("AssertionError expected"); } catch (AssertionError err) { verify(failures).failure(info, shouldNotContain(actual.getMessage(), "message", StandardComparisonStrategy.instance())); } }</code><technical_language>thanks AssertionsUtil.expectAssertionError, this written in a way, Objects_assertHasAllNullFieldsOrPropertiesExcept_Test example (you rebase branch origin/master): java import static org.assertj.core.util.AssertionsUtil.expectAssertionError; @Test void should_fail_if_one_field_or_property_is_set_even_if_another_is_ignored() { // Jedi jedi = new Jedi("Kenobi", "blue"); // expectAssertionError(() -> objects.assertHasAllNullFieldsOrPropertiesExcept(someInfo(), jedi, "name")); // verify(failures).failure(INFO, shouldHaveAllNullFields(jedi, list("lightSaberColor"), list("name"))); }</technical_language>

Target:
void should_fail_if_actual_has_message_containing_description() { AssertionInfo info = someInfo(); expectAssertionError(() -> throwables.assertHasMessageNotContaining(info, actual, "message")); verify(failures).failure(info, shouldNotContain(actual.getMessage(), "message", StandardComparisonStrategy.instance())); }
Source:
<code>public void testThrowErrorWithoutErrorCode() { try { repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.testThrowErrorWithoutErrorCode.bpmn20.xml").deploy(); <START> fail("ActivitiException expected"); <END> } catch (ActivitiException re) { } }</code><technical_language>I this class is this pattern test exceptions, do mind migrate catchThrowable AssertJ. more readable in option. find example <LINK_0></technical_language>

Target:
public void testThrowErrorWithoutErrorCode() { Throwable throwable = catchThrowable(() -> repositoryService .createDeployment() .addClasspathResource("org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.testThrowErrorWithoutErrorCode.bpmn20.xml") .deploy()); assertThat(throwable).isInstanceOf(ActivitiException.class) .hasMessageContaining("activiti-error-missing-error-code"); }
Source:
<code>private void unloadAllResources(IProgressMonitor monitor) { ResourceSet rs = transactionalEditingDomain.getResourceSet(); for (Resource resource : new ArrayList<Resource>(rs.getResources())) { <START> ResourceStrategy.INSTANCE.unload(resource, <END> monitor); rs.getResources().remove(resource); } super.getAnalyses().clear(); super.getResources().clear(); super.getControlledResources().clear(); }</code><technical_language>want additional singleton</technical_language>

Target:
private void unloadAllResources(IProgressMonitor monitor) { ResourceSet rs = transactionalEditingDomain.getResourceSet(); for (Resource resource : new ArrayList<Resource>(rs.getResources())) { ResourceStrategy.INSTANCE.unloadAtResourceSetDispose(resource, monitor); rs.getResources().remove(resource); } super.getAnalyses().clear(); super.getResources().clear(); super.getControlledResources().clear(); }
Source:
<code>public void removeTagForEntity(TaggedEntity taggedEntity, Long tagId) { String entityTagUrl = String.format("%s/%s/%s/%s/%s", tagRootUrl, tagId, "entities", taggedEntity.getNamespace(), taggedEntity.getId()); Response responseObject = client.target(entityTagUrl).request().delete(); String response = responseObject.readEntity(String.class); int responseCode = getResponseCode(response); <START> if (responseCode == CatalogResponse.ResponseMessage.ENTITY_NOT_FOUND.getCode() <END> | responseCode == CatalogResponse.ResponseMessage.EXCEPTION.getCode()) { throw new RuntimeException("Error occurred while removing tag for entity : "+ getResponseMessage(response)); } }</code><technical_language>@omkreddy similar changes well?. I missed this in previous review</technical_language>

Target:
public void removeTagForEntity(TaggedEntity taggedEntity, Long tagId) { String entityTagUrl = String.format("%s/%s/%s/%s/%s", tagRootUrl, tagId, "entities", taggedEntity.getNamespace(), taggedEntity.getId()); Response responseObject = client.target(entityTagUrl).request().delete(); String response = responseObject.readEntity(String.class); int responseCode = getResponseCode(response); if (responseCode != CatalogResponse.ResponseMessage.SUCCESS.getCode()) { throw new RuntimeException("Error occurred while removing tag for entity : "+ getResponseMessage(response)); } }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException { WebApplicationContext context = super.findWebApplicationContext(); MotechProxyManager proxyManager = context.getBean(MotechProxyManager.class); if (request instanceof HttpServletRequest) { traceRequest((HttpServletRequest) request); <START> } <END> if (isAdminMode) { anonymousFilter.doFilter(request, response, filterChain); } else if (proxyManager != null) { proxyManager.getFilterChainProxy().doFilter(request, response, filterChain); } else { super.doFilter(request, response, filterChain); } }</code><technical_language>is else possible? log someting if a type of request</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException { WebApplicationContext context = super.findWebApplicationContext(); MotechProxyManager proxyManager = context.getBean(MotechProxyManager.class); traceRequest(request); if (isAdminMode) { anonymousFilter.doFilter(request, response, filterChain); } else if (proxyManager != null) { proxyManager.getFilterChainProxy().doFilter(request, response, filterChain); } else { super.doFilter(request, response, filterChain); } }
Source:
<code>private void handleContainerStop(String containerID, String resourceID, String preferredHost, int exitStatus) { if (standbyContainerManager.isPresent()) { standbyContainerManager.get().handleContainerStop(containerID, resourceID, preferredHost, exitStatus, containerAllocator); <START> return; <END> } containerAllocator.requestResource(containerID, preferredHost); }</code><technical_language>replace early-return if .. else</technical_language>

Target:
private void handleContainerStop(String containerID, String resourceID, String preferredHost, int exitStatus) { if (standbyContainerManager.isPresent()) { standbyContainerManager.get().handleContainerStop(containerID, resourceID, preferredHost, exitStatus, containerAllocator); } else { containerAllocator.requestResource(containerID, preferredHost); } }
Source:
<code>public Artifact(GeneralInfo generalInfo, Set<Issue> issues, Set<License> licenses) { <START> this.generalInfo = new GeneralInfo(generalInfo); <END> this.issues.addAll(issues .stream() .map(Issue::new) .collect(Collectors.toSet())); this.licenses.addAll(licenses .stream() .map(License::new) .collect(Collectors.toSet())); }</code><technical_language>Question - a simple assignment sufficient here? - this.generalInfo = generalInfo; Do need a clone of GeneralInfo here? If so, constructor in GeneralInfo accepts another GeneralInfo redundant. question for *this.issues* *this.licenses* in method - aggregating issues licenses (with addAll) this is a time assignment</technical_language>

Target:
public Artifact(GeneralInfo generalInfo, Set<Issue> issues, Set<License> licenses) { this.generalInfo = generalInfo; this.issues = issues; this.licenses = licenses; }
Source:
<code>public ImportFromFileDialog(JFrame parent, ExtensionOpenApi caller) { super(parent, true); this.setTitle(Constant.messages.getString(MESSAGE_PREFIX + "title")); this.caller = caller; if (parent != null) { Dimension parentSize = parent.getSize(); Point p = parent.getLocation(); setLocation(p.x + parentSize.width / 4, p.y + parentSize.height / 4); } setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.WEST; constraints.insets = new Insets(5, 5, 5, 5); buttonImport.addActionListener(this); buttonCancel.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ImportFromFileDialog.this.setVisible(false); ImportFromFileDialog.this.dispose(); } }); constraints.gridx = 0; constraints.gridy = 0; add(new JLabel(Constant.messages.getString(MESSAGE_PREFIX + "labelfile")), constraints); constraints.gridx = 1; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.weightx = 1.0; constraints.gridwidth = 2; fieldFile = UIUtils.addContextMenu(fieldFile); add(fieldFile, constraints); constraints.gridx = 0; constraints.gridy = 1; constraints.gridwidth = 1; add(new JLabel(Constant.messages.getString(MESSAGE_PREFIX + "labeltarget")), constraints); constraints.gridx = 1; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.weightx = 1.0; constraints.gridwidth = 2; fieldTarget = UIUtils.addContextMenu(fieldTarget); add(fieldTarget, constraints); constraints.gridwidth = 1; constraints.gridy = 2; constraints.anchor = GridBagConstraints.CENTER; add(buttonCancel, constraints); constraints.gridx = 2; constraints.gridy = 2; constraints.anchor = GridBagConstraints.CENTER; add(buttonImport, constraints); buttonChooseFile.addActionListener(this::fileChooserActionHandler); constraints.gridx = 3; constraints.gridy = 0; add(buttonChooseFile, constraints); <START> <END> setDefaultCloseOperation(DISPOSE_ON_CLOSE); pack(); setVisible(true); }</code><technical_language>Need handle null parent</technical_language>

Target:
public ImportFromFileDialog(JFrame parent, ExtensionOpenApi caller) { super( parent, caller, Constant.messages.getString(MESSAGE_PREFIX + "title"), Constant.messages.getString(MESSAGE_PREFIX + "labelfile")); }
Source:
<code>private String extractProjection(Query query) { List<String> metricProjections = query.getMetrics().entrySet().stream() .map((entry) -> { Metric metric = entry.getKey(); Class<? extends Aggregation> agg = entry.getValue(); return metric.getMetricExpression(agg) + " AS " + metric.getName(); }) .collect(Collectors.toList()); List<String> dimensionProjections = query.getDimensions().stream() <START> .map(requestedDim -> query.getSchema().getDimension(requestedDim.getName())) <END> .map((SQLDimension.class::cast)) .map(SQLDimension::getColumnReference) .collect(Collectors.toList()); String projectionClause = metricProjections.stream() .collect(Collectors.joining(",")); if (!dimensionProjections.isEmpty()) { projectionClause = projectionClause + "," + dimensionProjections.stream() .collect(Collectors.joining(",")); } return projectionClause; }</code><technical_language>Line 448-452 471-475 same, a method for it</technical_language>

Target:
private String extractProjection(Query query) { List<String> metricProjections = query.getMetrics().entrySet().stream() .map((entry) -> { Metric metric = entry.getKey(); Class<? extends Aggregation> agg = entry.getValue(); return metric.getMetricExpression(agg) + " AS " + metric.getName(); }) .collect(Collectors.toList()); List<String> dimensionProjections = extractDimensionProjections(query); String projectionClause = metricProjections.stream() .collect(Collectors.joining(",")); if (!dimensionProjections.isEmpty()) { projectionClause = projectionClause + "," + dimensionProjections.stream() .collect(Collectors.joining(",")); } return projectionClause; }
Source:
<code>protected DefaultEcsClient( final EcsClientConfig config, final AmazonECSClient client, final AWSLogs logs) { this.config = config; this.client = client; this.logs = logs; <START> this.rateLimitMaxRetry = 60; <END> this.rateLimitMaxJitterSecs = 10; this.rateLimitMaxBaseWaitSecs = 50; }</code><technical_language>this(config, client, logs, 60, 10, 50)</technical_language>

Target:
protected DefaultEcsClient( final EcsClientConfig config, final AmazonECSClient client, final AWSLogs logs) { this(config, client, logs, 60, 10, 50, 10); }
Source:
<code>private ArgumentMatcher<RefundEntity> aRefundEntity(long amount, ChargeEntity chargeEntity) { return (RefundEntity object) -> object.getAmount() == amount && <START> object.getChargeEntity().equals(chargeEntity); <END> }</code><technical_language>Please rename object refundEntity</technical_language>

Target:
private ArgumentMatcher<RefundEntity> aRefundEntity(long amount, ChargeEntity chargeEntity) { return (RefundEntity refundEntity) -> refundEntity.getAmount() == amount && refundEntity.getChargeEntity().equals(chargeEntity); }
Source:
<code><START> public void shouldRaiseAlertGivenUriEncodedJsoMagicBytesAreDetectedInCookieOfRequest() <END> throws Exception { HttpMessage msg = new HttpMessage(); String jso = Base64.getEncoder().encodeToString(createJso()); msg.setRequestHeader("GET / HTTP/1.1\r\n" + "Cookie: CRUNCHY=" + URI_ENCODED_JSO + "\r\n"); rule.scanHttpRequestSend(msg, -1); assertThat(alertsRaised, hasSize(1)); }</code><technical_language>This moved shouldRaiseAlertGivenJsoMagicBytesAreDetectedInCookieOfRequest related tests closer</technical_language>

Target:
public void shouldRaiseAlertGivenUriEncodedJsoMagicBytesAreDetectedInCookieOfRequest() throws Exception { HttpMessage msg = new HttpMessage(); msg.setRequestHeader( "GET / HTTP/1.1\r\n" + "Cookie: CRUNCHY=" + createUriEncodedJso() + "\r\n"); rule.scanHttpRequestSend(msg, -1); assertThat(alertsRaised, hasSize(1)); }
Source:
<code>protected void releaseDocument(IDocument document, IProgressMonitor pm) throws CoreException { boolean isModified= isDocumentModified(); SubMonitor subMonitor= SubMonitor.convert(pm, 2); super.releaseDocument(document, subMonitor.split(1)); try { fCUnit.discardWorkingCopy(); } finally { if (isModified && !isDocumentAcquired()) { if (fCUnit.isWorkingCopy()) fCUnit.reconcile( ICompilationUnit.NO_AST, false , null , <START> subMonitor.split(1, <END> SubMonitor.SUPPRESS_BEGINTASK | SubMonitor.SUPPRESS_ISCANCELED)); else fCUnit.makeConsistent(subMonitor.split(1)); } } }</code><technical_language>newChild split, want a cancellation check</technical_language>

Target:
protected void releaseDocument(IDocument document, IProgressMonitor pm) throws CoreException { boolean isModified= isDocumentModified(); SubMonitor subMonitor= SubMonitor.convert(pm, 2); super.releaseDocument(document, subMonitor.split(1)); try { fCUnit.discardWorkingCopy(); } finally { if (isModified && !isDocumentAcquired()) { if (fCUnit.isWorkingCopy()) fCUnit.reconcile( ICompilationUnit.NO_AST, false , null , subMonitor.newChild(1)); else fCUnit.makeConsistent(subMonitor.newChild(1)); } } }
Source:
<code>public static XMLStreamReader createXMLStreamReader(InputStream inputStream) { try { return XML_INPUT_FACTORY.createXMLStreamReader(inputStream); } catch (Exception e) { <START> throw new XmlBeanDefinitionException("Error occurred creating a new XMLStreamReader from a java.io.InputStream.", e); <END> } }</code><technical_language>Error occurred while creating a new XMLStreamReader InputStream</technical_language>

Target:
public static XMLStreamReader createXMLStreamReader(InputStream inputStream) { try { return XML_INPUT_FACTORY.createXMLStreamReader(inputStream); } catch (Exception e) { throw new XmlBeanDefinitionException("Error occurred while creating a new XMLStreamReader from InputStream.", e); } }
Source:
<code>public void insertPastState(long stateStartTime, long stateEndTime, int quark, ITmfStateValue value) throws TimeRangeException { fInterval.add(new HTInterval(stateStartTime, stateEndTime, quark, (TmfStateValue) value)); <START> if (fInterval.size() == INTERVAL_CHUNK_SIZE) { <END> try { intervalQueue.put(fInterval); fInterval = new ArrayList<>(INTERVAL_CHUNK_SIZE); } catch (InterruptedException e) { Activator.getDefault().logError("State system interrupted", e); } } }</code><technical_language>I tend put ">=" for kinds of things, juuust in case weird happens. me</technical_language>

Target:
public void insertPastState(long stateStartTime, long stateEndTime, int quark, ITmfStateValue value) throws TimeRangeException { fCurrentChunk.add(new HTInterval(stateStartTime, stateEndTime, quark, (TmfStateValue) value)); if (fCurrentChunk.size() >= INTERVAL_CHUNK_SIZE) { try { intervalQueue.put(fCurrentChunk); fCurrentChunk = new ArrayList<>(INTERVAL_CHUNK_SIZE); } catch (InterruptedException e) { Activator.getDefault().logError("State system interrupted", e); } } }