auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private CompletableFuture<RestResponse> getCounter(RestRequest request) throws RestResponseException { String counterName = request.variables().get("counterName"); String accept = request.getAcceptHeader(); MediaType contentType = accept == null ? MediaType.TEXT_PLAIN : negotiateMediaType(accept); NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); CounterConfiguration configuration = counterManager.getConfiguration(counterName); if (configuration == null) { return CompletableFuture.completedFuture(responseBuilder.status(HttpResponseStatus.NOT_FOUND.code()).entity("Counter not found").build()); } else { responseBuilder.contentType(contentType).header(HttpHeaderNames.CACHE_CONTROL.toString(), CacheControl.noCache()); CompletableFuture<Long> response; if (configuration.type() == CounterType.WEAK) { response = CompletableFuture.completedFuture(counterManager.getWeakCounter(counterName).getValue()); } else { response = counterManager.getStrongCounter(counterName).getValue(); } return response.thenApply(res -> responseBuilder.entity(Long.toString(res)).build()); } }

Target:
private CompletionStage<RestResponse> getCounter(RestRequest request) throws RestResponseException { String counterName = request.variables().get("counterName"); String accept = request.getAcceptHeader(); MediaType contentType = accept == null ? MediaType.TEXT_PLAIN : negotiateMediaType(accept); NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); CounterConfiguration configuration = counterManager.getConfiguration(counterName); if (configuration == null) { return CompletableFuture.completedFuture(responseBuilder.status(HttpResponseStatus.NOT_FOUND.code()).entity("Counter not found").build()); } responseBuilder.contentType(contentType).header(HttpHeaderNames.CACHE_CONTROL.toString(), CacheControl.noCache()); CompletionStage<Long> response; if (configuration.type() == CounterType.WEAK) { response = CompletableFuture.completedFuture(counterManager.getWeakCounter(counterName).getValue()); } else { response = counterManager.getStrongCounter(counterName).getValue(); } return response.thenApply(res -> responseBuilder.entity(Long.toString(res)).build()); }
Source:
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.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; } }); }

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:
public boolean awaitInactivity(long timeout, TimeUnit unit) throws InterruptedException { final Thread thread = this.thread; if (thread == null) { throw new IllegalStateException("thread was not started"); } thread.join(ObjectUtil.checkNotNull(unit, "unit").toMillis(timeout)); return !thread.isAlive(); }

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:
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; RevWalk revWalk = new RevWalk(repository); 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; }

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:
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) { throw new IOException("Unable to retrieve resource because no resource URI was given"); } LOGGER.debug("Retrieving resource at : {}", resourceUri); return resourceReader.retrieveResource(resourceUri, requestProperties); }

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:
long createDetectionConfig(@NotNull String payload, long startTime, long endTime) throws Exception { if (!this.onboardingRateLimiter.tryAcquire()) { throw new RuntimeException("Server is busy handling create detection requests. Please retry later."); } 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(); }

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:
public void onActivityPaused(Activity activity) { if (clientInstance == null) { Log.e(TAG, NULLMSG); return; } clientInstance.refreshSessionTime(getCurrentTimeMillis()); clientInstance.setInForeground(false); }

Target:
public void onActivityPaused(Activity activity) { if (clientInstance == null) { Log.e(TAG, NULLMSG); return; } clientInstance.onExitForeground(getCurrentTimeMillis()); }
Source:
private DataProviderLookup loadProviderLookup(Class<?> holderType) { Stream<DataProvider> stream = this.dataProviders.keySet().stream() .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))); }

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:
public void onMessage(String message) { System.out.println(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); } }

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:
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()){ s_logger.info("QuotaTariffDaoImpl::findTariffPlanByUsageType: Missing quota type " + quotaType); } return null; } }

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:
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; int metric = Integer.parseInt(fields[3]); if(isGateway && (metric < minMetric)){ minMetric = metric; gateway = fields[1]; } } catch (NumberFormatException ignored){} } } return gateway; }

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:
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.log(Level.WARNING, "Exception while getting expiry for creation. Fallback to default duration eternal.", t); 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()); } }

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:
public List<Integer> getListOfSurahWithStartingOnPage(int page) { List<Integer> result = new ArrayList<>(); for (int i = 0; i < Constants.SURAS_COUNT; i++) { if(suraPageStart[i] == page) { result.add(i + 1); } } return result; }

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:
public String getInvalidityInfoForNationality(String nationality) { Assumption.assertTrue("Non-null value expected", nationality != null); if (!NationalityHelper.getNationalities().contains(nationality)) { return String.format(NATIONALITY_ERROR_MESSAGE, nationality); } return ""; }

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:
protected List<? extends Module> getModules() { return ImmutableList.<Module>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) ); } ); }

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:
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()) { getVmStaticDao().incrementDbGeneration(vmId); } } }

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:
private 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); } }

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:
private void postDragEventQueue(int type, Event event) { if (dragDetectionQueue == null) dragDetectionQueue = new Event [4]; event.type = type; int index = 0; int length = dragDetectionQueue.length; 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; } dragDetectionQueue [index] = event; }

Target:
private void postDragEventQueue(int type, Event event) { if (dragDetectionQueue == null) dragDetectionQueue = new LinkedList<>(); event.type = type; dragDetectionQueue.add(event); }
Source:
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( String.format( "%s %s failed with %s: %s", new RqMethod.Base(req).method(), new RqHref.Base(req).href(), req.code(), baos.toString("UTF-8") ) ); }

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:
private PomModel resolvePom(String path) throws Exception { try (InputStream pomInputStream = this.getClass().getClassLoader().getResourceAsStream(path)) { return PomModelResolver.resolveFromPom(pomInputStream); } catch (Exception e) { throw e; } }

Target:
private PomModel resolvePom(String path) throws Exception { InputStream pomInputStream = this.getClass().getClassLoader().getResourceAsStream(path); return PomModelResolver.resolveFromPom(pomInputStream); }
Source:
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 (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; }

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:
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( "jvm_safepoint_total_time_seconds", "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; }

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:
void should_fail_if_actual_has_message_containing_description() { 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())); } }

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:
public void testThrowErrorWithoutErrorCode() { try { repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.testThrowErrorWithoutErrorCode.bpmn20.xml").deploy(); fail("ActivitiException expected"); } catch (ActivitiException re) { } }

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:
private void unloadAllResources(IProgressMonitor monitor) { ResourceSet rs = transactionalEditingDomain.getResourceSet(); for (Resource resource : new ArrayList<Resource>(rs.getResources())) { ResourceStrategy.INSTANCE.unload(resource, monitor); rs.getResources().remove(resource); } super.getAnalyses().clear(); super.getResources().clear(); super.getControlledResources().clear(); }

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:
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.ENTITY_NOT_FOUND.getCode() | responseCode == CatalogResponse.ResponseMessage.EXCEPTION.getCode()) { throw new RuntimeException("Error occurred while removing tag for entity : "+ getResponseMessage(response)); } }

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:
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); } if (isAdminMode) { anonymousFilter.doFilter(request, response, filterChain); } else if (proxyManager != null) { proxyManager.getFilterChainProxy().doFilter(request, response, filterChain); } else { super.doFilter(request, response, filterChain); } }

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:
private void handleContainerStop(String containerID, String resourceID, String preferredHost, int exitStatus) { if (standbyContainerManager.isPresent()) { standbyContainerManager.get().handleContainerStop(containerID, resourceID, preferredHost, exitStatus, containerAllocator); return; } containerAllocator.requestResource(containerID, preferredHost); }

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:
public Artifact(GeneralInfo generalInfo, Set<Issue> issues, Set<License> licenses) { this.generalInfo = new GeneralInfo(generalInfo); this.issues.addAll(issues .stream() .map(Issue::new) .collect(Collectors.toSet())); this.licenses.addAll(licenses .stream() .map(License::new) .collect(Collectors.toSet())); }

Target:
public Artifact(GeneralInfo generalInfo, Set<Issue> issues, Set<License> licenses) { this.generalInfo = generalInfo; this.issues = issues; this.licenses = licenses; }
Source:
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); setDefaultCloseOperation(DISPOSE_ON_CLOSE); pack(); setVisible(true); }

Target:
public ImportFromFileDialog(JFrame parent, ExtensionOpenApi caller) { super( parent, caller, Constant.messages.getString(MESSAGE_PREFIX + "title"), Constant.messages.getString(MESSAGE_PREFIX + "labelfile")); }
Source:
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() .map(requestedDim -> query.getSchema().getDimension(requestedDim.getName())) .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; }

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:
protected DefaultEcsClient( final EcsClientConfig config, final AmazonECSClient client, final AWSLogs logs) { this.config = config; this.client = client; this.logs = logs; this.rateLimitMaxRetry = 60; this.rateLimitMaxJitterSecs = 10; this.rateLimitMaxBaseWaitSecs = 50; }

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

Target:
private ArgumentMatcher<RefundEntity> aRefundEntity(long amount, ChargeEntity chargeEntity) { return (RefundEntity refundEntity) -> refundEntity.getAmount() == amount && refundEntity.getChargeEntity().equals(chargeEntity); }
Source:
public void shouldRaiseAlertGivenUriEncodedJsoMagicBytesAreDetectedInCookieOfRequest() 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)); }

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:
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.split(1, SubMonitor.SUPPRESS_BEGINTASK | SubMonitor.SUPPRESS_ISCANCELED)); else fCUnit.makeConsistent(subMonitor.split(1)); } } }

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:
public static XMLStreamReader createXMLStreamReader(InputStream inputStream) { try { return XML_INPUT_FACTORY.createXMLStreamReader(inputStream); } catch (Exception e) { throw new XmlBeanDefinitionException("Error occurred creating a new XMLStreamReader from a java.io.InputStream.", e); } }

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

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); } } }
Source:
private void deletePageContents(@NonNull ReadingListPage page) { PageTitle pageTitle = ReadingListPage.toPageTitle(page); reqPageLead(CacheControl.FORCE_CACHE, OfflineCacheInterceptor.SAVE_HEADER_DELETE, pageTitle) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(leadRsp -> { PageLead lead = leadRsp.body(); if (lead != null) { List<String> imageUrls = pageImageUrlParser.parse(lead); if (!TextUtils.isEmpty(pageTitle.getThumbUrl())) { imageUrls.add(pageTitle.getThumbUrl()); } for (String url : imageUrls) { try { Request request = makeImageRequest(pageTitle.getWikiSite(), url) .addHeader(OfflineCacheInterceptor.SAVE_HEADER, OfflineCacheInterceptor.SAVE_HEADER_DELETE) .build(); OkHttpConnectionFactory.getClient().newCall(request).execute(); } catch (IOException ignore) { } } } }, L::d); reqPageSections(CacheControl.FORCE_CACHE, OfflineCacheInterceptor.SAVE_HEADER_DELETE, pageTitle) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(sectionsRsp -> { PageRemaining sections = sectionsRsp.body(); if (sections != null) { for (String url : pageImageUrlParser.parse(sections)) { try { Request request = makeImageRequest(pageTitle.getWikiSite(), url) .addHeader(OfflineCacheInterceptor.SAVE_HEADER, OfflineCacheInterceptor.SAVE_HEADER_DELETE) .build(); OkHttpConnectionFactory.getClient().newCall(request).execute(); } catch (IOException ignore) { } } } }, L::d); }

Target:
private void deletePageContents(@NonNull ReadingListPage page) { PageTitle pageTitle = ReadingListPage.toPageTitle(page); reqPageLead(CacheControl.FORCE_CACHE, OfflineCacheInterceptor.SAVE_HEADER_DELETE, pageTitle) .subscribeOn(Schedulers.io()) .subscribe(leadRsp -> { PageLead lead = leadRsp.body(); if (lead != null) { List<String> imageUrls = pageImageUrlParser.parse(lead); if (!TextUtils.isEmpty(pageTitle.getThumbUrl())) { imageUrls.add(pageTitle.getThumbUrl()); } for (String url : imageUrls) { Request request = makeImageRequest(pageTitle.getWikiSite(), url) .addHeader(OfflineCacheInterceptor.SAVE_HEADER, OfflineCacheInterceptor.SAVE_HEADER_DELETE) .build(); OkHttpConnectionFactory.getClient().newCall(request).execute(); } } }, L::d); reqPageSections(CacheControl.FORCE_CACHE, OfflineCacheInterceptor.SAVE_HEADER_DELETE, pageTitle) .subscribeOn(Schedulers.io()) .subscribe(sectionsRsp -> { PageRemaining sections = sectionsRsp.body(); if (sections != null) { for (String url : pageImageUrlParser.parse(sections)) { Request request = makeImageRequest(pageTitle.getWikiSite(), url) .addHeader(OfflineCacheInterceptor.SAVE_HEADER, OfflineCacheInterceptor.SAVE_HEADER_DELETE) .build(); OkHttpConnectionFactory.getClient().newCall(request).execute(); } } }, L::d); }
Source:
public void mergeLoginMethods(String rawToken, User existantUser, MethodType type) { LoginMethod Login = LoginMethod.newLogin(existantUser, existantUser.getEmail(), rawToken, type); existantUser.add(Login); loginMethods.save(Login); access.login(existantUser); }

Target:
public void mergeLoginMethods(String rawToken, User existantUser, MethodType type) { LoginMethod login = LoginMethod.newLogin(existantUser, existantUser.getEmail(), rawToken, type); existantUser.add(login); loginMethods.save(login); access.login(existantUser); }
Source:
static <E extends Enum<E>> Optional<Class<?>> ifEnum(Type type) { return Optional.of(type) .map(GenericTypes::getErasedType) .filter(Class::isEnum) .map(c -> (Class<E>) c); }

Target:
static <E extends Enum<E>> Optional<Class<E>> ifEnum(Type type) { return Optional.of(type) .map(GenericTypes::getErasedType) .filter(Class::isEnum) .map(c -> (Class<E>) c); }