auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected Event doExecute(final RequestContext requestContext) { val uid = WebUtils.getAuthentication(requestContext).getPrincipal().getId(); val credential = WebUtils.getCredential(requestContext, OneTimeTokenCredential.class); if (!StringUtils.isNumeric(credential.getToken())) { LOGGER.error("Non-numeric OTP token provided: [{}]", credential.getToken()); return error(); } val token = Integer.parseInt(credential.getToken()); val account = requestContext.getFlowScope().get("key", OneTimeTokenAccount.class); LOGGER.debug("Attempting to validate OTP token with [{}]", token, account); val isCodeValid = this.googleAuthenticatorInstance.authorize(account.getSecretKey(), token); if (!isCodeValid && account.getScratchCodes().contains(token)) { LOGGER.warn("User attempted to use scratch code during OTP registration; this is likely a mistake.", uid); return error(); } if (isCodeValid) { LOGGER.debug("Validated OTP token to register user [{}]", token, uid); repository.save(uid, account.getSecretKey(), account.getValidationCode(), account.getScratchCodes()); return success(); } LOGGER.warn("Failed to validate token to register user [{}]", token, uid); return error(); }

Target:
protected Event doExecute(final RequestContext requestContext) { val account = requestContext.getFlowScope() .get(OneTimeTokenAccountCheckRegistrationAction.FLOW_SCOPE_ATTR_ACCOUNT, OneTimeTokenAccount.class); val uid = WebUtils.getAuthentication(requestContext).getPrincipal().getId(); val credential = WebUtils.getCredential(requestContext, OneTimeTokenCredential.class); val token = tokenValidator.parseToken(credential); LOGGER.debug("Attempting to validate OTP token with [{}]", token, account); val isCodeValid = tokenValidator.isValid(account, token); if (isCodeValid) { LOGGER.debug("Validated OTP token to register user [{}]", token, uid); repository.save(uid, account.getSecretKey(), account.getValidationCode(), account.getScratchCodes()); return success(); } if (account.getScratchCodes().contains(token)) { LOGGER.warn("User attempted to use scratch code during OTP registration; this is likely a mistake.", uid); return register(); } LOGGER.warn("Failed to validate token to register user [{}]", token, uid); return register(); }
Source:
public MongoDBSession(MongoDBDirectory directory) { super(directory, MongoDBReference.class); MongoDBConnectionService mongoService = Framework.getService(MongoDBConnectionService.class); database = mongoService.getDatabase("directory/" + directory.getDescriptor().name); countersCollectionName = directory.getCountersCollectionName(); }

Target:
public MongoDBSession(MongoDBDirectory directory) { super(directory, MongoDBReference.class); MongoDBConnectionService mongoService = Framework.getService(MongoDBConnectionService.class); database = mongoService.getDatabase(DIRECTORY_CONNECTION_PREFIX + directory.getDescriptor().name); countersCollectionName = directory.getCountersCollectionName(); }
Source:
private TDigest(double compression) { checkArgument(!isNaN(compression)); checkArgument(compression <= MAX_COMPRESSION_FACTOR, "Compression factor cannot exceed %s", MAX_COMPRESSION_FACTOR); this.publicCompression = max(compression, 10); this.compression = 2 * publicCompression; maxBufferSize = 5 * (int) ceil(this.publicCompression + sizeFudge); maxCentroidCount = (int) ceil(this.compression + sizeFudge); weight = new double[4]; mean = new double[4]; tempWeight = new double[8]; tempMean = new double[8]; order = new int[8]; activeCentroids = 0; }

Target:
private TDigest(double compression) { checkArgument(compression <= MAX_COMPRESSION_FACTOR, "Compression factor cannot exceed %s", MAX_COMPRESSION_FACTOR); this.publicCompression = max(compression, 10); this.compression = 2 * publicCompression; int bufferSize = 5 * (int) ceil(this.publicCompression + sizeFudge); int size = (int) ceil(this.compression + sizeFudge); weight = new double[size]; mean = new double[size]; tempWeight = new double[bufferSize]; tempMean = new double[bufferSize]; order = new int[bufferSize]; activeCentroids = 0; }
Source:
public void testUpdate() throws IOException, OmiseException { Request<Customer> request = new Customer.UpdateRequestBuilder(CUSTOMER_ID) .email("john.doe.the.second@example.com") .build(); Customer customer = getTestRequester().sendRequest(request); assertRequested("PATCH", "/customers/" + CUSTOMER_ID, 200); assertEquals("cust_test_4yq6txdpfadhbaqnwp3", customer.getId()); assertEquals("john.doe.the.second@example.com", customer.getEmail()); }

Target:
public void testUpdate() throws IOException, OmiseException { Request<Customer> request = new Customer.UpdateRequestBuilder(CUSTOMER_ID) .email("john.doe.the.second@example.com") .build(); Customer customer = getTestRequester().sendRequest(request); assertRequested("PATCH", "/customers/" + CUSTOMER_ID, 200); assertEquals(CUSTOMER_ID, customer.getId()); assertEquals("john.doe.the.second@example.com", customer.getEmail()); }
Source:
public void deleteCandidateGroups(CandidateGroupsPayload candidateGroupsPayload) { Task task; try { task = task(candidateGroupsPayload.getTaskId()); } catch (IllegalStateException ex) { throw new IllegalStateException("The authenticated user cannot update the task" + candidateGroupsPayload.getTaskId() + " due it is not the current assignee"); } if (candidateGroupsPayload.getCandidateGroups() != null && !candidateGroupsPayload.getCandidateGroups().isEmpty()) { for (String g : candidateGroupsPayload.getCandidateGroups()) { taskService.deleteCandidateGroup(task.getId(), g); } } }

Target:
public void deleteCandidateGroups(CandidateGroupsPayload candidateGroupsPayload) { if (candidateGroupsPayload.getCandidateGroups() != null && !candidateGroupsPayload.getCandidateGroups().isEmpty()) { for (String g : candidateGroupsPayload.getCandidateGroups()) { taskService.deleteCandidateGroup(candidateGroupsPayload.getTaskId(), g); } } }
Source:
public PluginContainer getPlugin() { return parent.getPlugin(); }

Target:
public PluginContainer getPlugin() { return this.parent.getPlugin(); }
Source:
public @ResponseBody String getAppointmentByApplicantId(@PathVariable String applicantId) { return jsonUtil.toJson(appointmentService.getAppointmentByApplicantId(applicantId)); }

Target:
public Appointment getAppointmentByApplicantId(@PathVariable String applicantId) { return appointmentService.getAppointmentByApplicantId(applicantId); }
Source:
public Statement apply(Statement base, Description description) { try { SplunkServer splunkServer = new SplunkServer(); splunkServer.setPassword("admin"); splunkServer.setUsername("admin"); SplunkServiceFactory splunkServiceFactory = new SplunkServiceFactory(splunkServer); splunkServiceFactory.getService().open(splunkServer.getPort()); } catch (Exception e) { logger.warn("Not executing tests because basic connectivity test failed"); Assume.assumeNoException(e); } return super.apply(base, description); }

Target:
public Statement apply(Statement base, Description description) { try { SplunkServer splunkServer = new SplunkServer(); splunkServer.setPassword("admin"); splunkServer.setUsername("admin"); SplunkServiceFactory splunkServiceFactory = new SplunkServiceFactory( splunkServer); splunkServiceFactory.getService().open(port); } catch (Exception e) { logger.warn( "Not executing tests because basic connectivity test failed"); Assume.assumeNoException(e); } return super.apply(base, description); }
Source:
public static boolean promptChangeVersion(AbstractWorkflowArtifact sma, VersionReleaseType versionReleaseType, VersionLockedType versionLockType) { if (AtsClientService.get().getUserService().isAtsAdmin() && !sma.isTeamWorkflow()) { AWorkbench.popup("ERROR ", "Cannot set version for: \n\n" + sma.getName()); return false; } if (promptChangeVersion(Arrays.asList((TeamWorkFlowArtifact) sma), versionReleaseType, versionLockType)) { IAtsChangeSet changes = AtsClientService.get().createChangeSet("ATS Prompt Change Version"); AtsClientService.get().getVersionService().setTargetedVersion((TeamWorkFlowArtifact) sma, getSelectedVersion(), changes); changes.execute(); ArtifactQuery.reloadArtifacts(Arrays.asList((TeamWorkFlowArtifact) sma)); return true; } return false; }

Target:
public static boolean promptChangeVersion(AbstractWorkflowArtifact sma, VersionReleaseType versionReleaseType, VersionLockedType versionLockType) { if (AtsClientService.get().getUserService().isAtsAdmin() && !sma.isTeamWorkflow()) { AWorkbench.popup("ERROR ", "Cannot set version for: \n\n" + sma.getName()); return false; } if (promptChangeVersion(Arrays.asList((TeamWorkFlowArtifact) sma), versionReleaseType, versionLockType)) { IAtsChangeSet changes = AtsClientService.get().createChangeSet("ATS Prompt Change Version"); AtsClientService.get().getVersionService().setTargetedVersion((TeamWorkFlowArtifact) sma, getSelectedVersion(), changes); changes.executeIfNeeded(); ArtifactQuery.reloadArtifacts(Arrays.asList((TeamWorkFlowArtifact) sma)); return true; } return false; }
Source:
public void launch() { AbstractMongoDBServer server = getServer(); String host = server.getAttribute(AbstractMongoDBServer.HOSTNAME); Integer port = server.getAttribute(AbstractMongoDBServer.PORT); for (String scriptName : entity.getConfig(MongoDBClient.DEFAULT_SCRIPTS)) { runScript("", scriptName, host, port); } isRunning = true; }

Target:
public void launch() { AbstractMongoDBServer server = getServer(); String host = server.getAttribute(AbstractMongoDBServer.HOSTNAME); Integer port = server.getAttribute(AbstractMongoDBServer.PORT); for (String scriptName : entity.getConfig(MongoDBClient.STARTUP_JS_SCRIPTS)) { runScript("", scriptName, host, port); } isRunning = true; }
Source:
private void createShowFirstParentOnlyAction() { showFirstParentOnlyAction = new ShowFirstParentOnlyPrefAction(); showFirstParentOnlyAction .setImageDescriptor(UIIcons.FIRST_PARENT_ONLY); showFirstParentOnlyAction .setToolTipText(UIText.GitHistoryPage_showFirstParentOnly); actionsToDispose.add(showFirstParentOnlyAction); }

Target:
private void createShowFirstParentOnlyAction() { showFirstParentOnlyAction = new ShowFirstParentOnlyPrefAction(); actionsToDispose.add(showFirstParentOnlyAction); }
Source:
public void testDataProviderswithDP(@NoInjection final Method method, final Class clazz) throws IllegalAccessException, InstantiationException { Object instance = clazz.newInstance(); Set<Method> methodSet = Sets.newHashSet(); methodSet.addAll(Arrays.asList(clazz.getDeclaredMethods())); methodSet.addAll(Arrays.asList(clazz.getMethods())); for (final Method otherMethod : methodSet) { if (otherMethod.isAnnotationPresent(BeforeSuite.class)) { try { otherMethod.setAccessible(true); otherMethod.invoke(instance); } catch (IllegalAccessException | InvocationTargetException e) { throw new IllegalStateException(String.format("@BeforeClass threw an exception (%s::%s). Dependent tests will be skipped. Please fix.", clazz.getName(), method.getName()), e); } } if (otherMethod.isAnnotationPresent(BeforeClass.class)) { try { otherMethod.setAccessible(true); otherMethod.invoke(instance); } catch (IllegalAccessException | InvocationTargetException e) { throw new IllegalStateException(String.format("@BeforeSuite threw an exception (%s::%s). Dependent tests will be skipped. Please fix.", clazz.getName(), method.getName()), e); } } } try { method.setAccessible(true); method.invoke(instance); } catch (IllegalAccessException | InvocationTargetException e) { throw new IllegalStateException(String.format("@DataProvider threw an exception (%s::%s). Dependent tests will be skipped. Please fix.", clazz.getName(), method.getName()), e); } }

Target:
public void testDataProviderswithDP(@NoInjection final Method method, final Class clazz) throws IllegalAccessException, InstantiationException { Object instance = clazz.newInstance(); Set<Method> methodSet = new HashSet<>(); methodSet.addAll(Arrays.asList(clazz.getDeclaredMethods())); methodSet.addAll(Arrays.asList(clazz.getMethods())); if (methodSet.stream().anyMatch(m->m.isAnnotationPresent(BeforeSuite.class))) return; for (final Method otherMethod : methodSet) { if (otherMethod.isAnnotationPresent(BeforeClass.class)) { try { otherMethod.setAccessible(true); otherMethod.invoke(instance); } catch (IllegalAccessException | InvocationTargetException e) { throw new IllegalStateException(String.format("@BeforeClass threw an exception (%s::%s). Dependent tests will be skipped. Please fix.", clazz.getName(), method.getName()), e); } } } try { method.setAccessible(true); method.invoke(instance); } catch (IllegalAccessException | InvocationTargetException e) { throw new IllegalStateException(String.format("@DataProvider threw an exception (%s::%s). Dependent tests will be skipped. Please fix.", clazz.getName(), method.getName()), e); } }
Source:
private <C extends DataWriteCommand & MetadataAwareCommand> Object handleDataWriteCommand(InvocationContext ctx, C command) { EntryVersion version; if (command.isReturnValueExpected()) { if (!(responseValue instanceof MetadataImmortalCacheValue)) { throw new CacheException("Expected MetadataImmortalCacheValue as response but it is " + responseValue); } MetadataImmortalCacheValue micv = (MetadataImmortalCacheValue) responseValue; version = micv.getMetadata().version(); returnValue = micv.getValue(); } else { if (!(responseValue instanceof EntryVersion)) { throw new CacheException("Expected NumericVersion as response but it is " + responseValue); } version = (EntryVersion) responseValue; returnValue = null; } Metadata metadata = addVersion(command.getMetadata(), version); entryFactory.wrapExternalEntry(ctx, command.getKey(), null, false, true); cacheEntry = ctx.lookupEntry(command.getKey()); cacheEntry.setMetadata(metadata); command.setValueMatcher(ValueMatcher.MATCH_ALWAYS); return invokeNextThenApply(ctx, command, this); }

Target:
private <C extends DataWriteCommand & MetadataAwareCommand> Object handleDataWriteCommand(InvocationContext ctx, C command) { EntryVersion version; if (command.isReturnValueExpected()) { if (!(responseValue instanceof MetadataImmortalCacheValue)) { throw new CacheException("Expected MetadataImmortalCacheValue as response but it is " + responseValue); } MetadataImmortalCacheValue micv = (MetadataImmortalCacheValue) responseValue; version = micv.getMetadata().version(); returnValue = micv.getValue(); } else { if (!(responseValue instanceof EntryVersion)) { throw new CacheException("Expected EntryVersion as response but it is " + responseValue); } version = (EntryVersion) responseValue; returnValue = null; } Metadata metadata = addVersion(command.getMetadata(), version); entryFactory.wrapExternalEntry(ctx, command.getKey(), null, false, true); cacheEntry = ctx.lookupEntry(command.getKey()); cacheEntry.setMetadata(metadata); command.setValueMatcher(ValueMatcher.MATCH_ALWAYS); return invokeNextThenApply(ctx, command, this); }
Source:
private InterpreterResult reLoginFromKeytab(String propertyKey, String sql, InterpreterContext interpreterContext, InterpreterResult interpreterResult) { String user = interpreterContext.getAuthenticationInfo().getUser(); try { closeDBPool(user, propertyKey); } catch (SQLException e) { } UserGroupInformation.AuthenticationMethod authType = JDBCSecurityImpl.getAuthtype(property); if (authType.equals(KERBEROS)) { try { if (UserGroupInformation.isLoginKeytabBased()) { UserGroupInformation.getLoginUser().reloginFromKeytab(); } else if (UserGroupInformation.isLoginTicketBased()) { UserGroupInformation.getLoginUser().reloginFromTicketCache(); } } catch (IOException e) { logger.error("Cannot reloginFromKeytab " + sql, e); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); e.printStackTrace(ps); String errorMsg = new String(baos.toByteArray(), StandardCharsets.UTF_8); interpreterResult.add(errorMsg); return new InterpreterResult(Code.ERROR, interpreterResult.message()); } } return executeSql(propertyKey, sql, interpreterContext); }

Target:
private InterpreterResult reLoginFromKeytab(String propertyKey, String sql, InterpreterContext interpreterContext, InterpreterResult interpreterResult) { String user = interpreterContext.getAuthenticationInfo().getUser(); try { closeDBPool(user, propertyKey); } catch (SQLException e) { logger.error("Error, could not close DB pool in reLoginFromKeytab ", e); } UserGroupInformation.AuthenticationMethod authType = JDBCSecurityImpl.getAuthtype(property); if (authType.equals(KERBEROS)) { try { if (UserGroupInformation.isLoginKeytabBased()) { UserGroupInformation.getLoginUser().reloginFromKeytab(); } else if (UserGroupInformation.isLoginTicketBased()) { UserGroupInformation.getLoginUser().reloginFromTicketCache(); } } catch (IOException e) { logger.error("Cannot reloginFromKeytab " + sql, e); interpreterResult.add(e.getMessage()); return new InterpreterResult(Code.ERROR, interpreterResult.message()); } } return executeSql(propertyKey, sql, interpreterContext); }
Source:
public synchronized void update() { int n = getMembers().size(); for (int i = 0; i < n; i++) { log.info("Update cassandra cluster member of {}", i, n); CassandraServer server = (CassandraServer) Iterables.get(getMembers(), i); BigInteger token = BigInteger.valueOf(2L).pow(127).divide(BigInteger.valueOf(n)).multiply(BigInteger.valueOf(i)); server.setToken(token.toString()); } }

Target:
public void update() { }
Source:
public void testBuiltMessageRedisplayLimit() throws JSONException { OSTestInAppMessage message = InAppMessagingHelpers.buildTestMessageWitRedisplay( LIMIT, DELAY ); for (int i = 0; i < LIMIT; i++) { assertTrue( message.shouldDisplayAgain()); message.incrementDisplayQuantity(); } }

Target:
public void testBuiltMessageRedisplayLimit() throws JSONException { OSTestInAppMessage message = InAppMessagingHelpers.buildTestMessageWitRedisplay( LIMIT, DELAY ); for (int i = 0; i < LIMIT; i++) { assertTrue(message.getDisplayStats().shouldDisplayAgain()); message.getDisplayStats().incrementDisplayQuantity(); } message.getDisplayStats().incrementDisplayQuantity(); assertFalse(message.getDisplayStats().shouldDisplayAgain()); }
Source:
private void parseSuite(String suitePath) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("suiteXmlPath: \"" + suitePath + "\""); } try { Collection<XmlSuite> allSuites = Parser.parse(suitePath, getProcessor()); for (XmlSuite s : allSuites) { if (this.m_parallelMode != null) { s.setParallel(this.m_parallelMode); } if (this.m_threadCount > 0) { s.setThreadCount(this.m_threadCount); } if (m_testNames != null) { m_suites.add(XmlSuiteUtils.cloneIfContainsTestsWithNamesMatchingAny(s, m_testNames)); } else { m_suites.add(s); } } } catch (IOException e) { e.printStackTrace(System.out); } catch (Exception ex) { Throwable t = ex; while (t.getCause() != null) { t = t.getCause(); } if (t instanceof TestNGException) { throw (TestNGException) t; } throw new TestNGException(t); } }

Target:
private void parseSuite(String suitePath) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("suiteXmlPath: \"" + suitePath + "\""); } try { Collection<XmlSuite> allSuites = Parser.parse(suitePath, getProcessor()); for (XmlSuite s : allSuites) { if (this.m_parallelMode != null) { s.setParallel(this.m_parallelMode); } if (this.m_threadCount > 0) { s.setThreadCount(this.m_threadCount); } if (m_testNames == null) { m_suites.add(s); continue; } TestNamesMatcher testNamesMatcher = new TestNamesMatcher(s, m_testNames); List<String> missMatchedTestname = testNamesMatcher.getMissMatchedTestNames(); if (!missMatchedTestname.isEmpty()) { throw new TestNGException("The test(s) <" + missMatchedTestname + "> cannot be found."); } m_suites.addAll(testNamesMatcher.getSuitesMatchingTestNames()); } } catch (IOException e) { e.printStackTrace(System.out); } catch (Exception ex) { Throwable t = ex; while (t.getCause() != null) { t = t.getCause(); } if (t instanceof TestNGException) { throw (TestNGException) t; } throw new TestNGException(t); } }
Source:
public static void serializeMetadataContentRecord(ByteBuffer outputBuffer, List<StoreKey> keys) { int keySize = keys.get(0).sizeInBytes(); for (StoreKey storeKey : keys) { if (storeKey.sizeInBytes() != keySize) { throw new IllegalArgumentException("Keys are not of same size"); } } outputBuffer.putShort(Metadata_Content_Version_V1); outputBuffer.putInt(keys.size()); for (StoreKey storeKey : keys) { outputBuffer.put(storeKey.toBytes()); } }

Target:
public static void serializeMetadataContentRecord(ByteBuffer outputBuffer, List<StoreKey> keys) { int keySize = keys.get(0).sizeInBytes(); outputBuffer.putShort(Metadata_Content_Version_V1); outputBuffer.putInt(keys.size()); for (StoreKey storeKey : keys) { if (storeKey.sizeInBytes() != keySize) { throw new IllegalArgumentException("Keys are not of same size"); } outputBuffer.put(storeKey.toBytes()); } }
Source:
private Set<String> getSenseBlackList() { final Jedis jedis = jedisPool.getResource(); try { return jedis.smembers(BlackListDevicesConfiguration.SENSE_BLACK_LIST_KEY); } catch (Exception e) { return new HashSet(Arrays.asList()); } finally { jedisPool.returnResource(jedis); } }

Target:
private Set<String> getSenseBlackList() { if (lastBlackListFetchDateTime.plusMinutes(REFRESH_PERIOD_MINUTES).isBeforeNow() || blackListUpdateCount == 0){ lastBlackListFetchDateTime = DateTime.now(DateTimeZone.UTC); Jedis jedis = null; try { jedis = jedisPool.getResource(); senseBlackList = jedis.smembers(BlackListDevicesConfiguration.SENSE_BLACK_LIST_KEY); LOGGER.info("Refreshed sense black list"); } catch (JedisDataException e) { LOGGER.error("Failed to get data from redis - {}", e.getMessage()); if (jedis != null) { jedisPool.returnBrokenResource(jedis); } } catch (Exception e) { LOGGER.error("Failed to refresh sense black list because {}", e.getMessage()); if (jedis != null) { jedisPool.returnBrokenResource(jedis); } } finally { if (jedis != null) { jedisPool.returnResource(jedis); } } } blackListUpdateCount += 1; return senseBlackList; }
Source:
public String validate(String parameterValue, ModelValidatorContext context) throws ValidationException { if (context == null || context.getScheduler() == null) { logger.warn(String.format("Can't check the validity of the variable value, because missing the access to the scheduler third-party credentials", parameterValue)); return parameterValue; } try { Set<String> credentialKeys = context.getScheduler().thirdPartyCredentialsKeySet(); if (!credentialKeys.contains(parameterValue)) { throw new ValidationException("Expected value should exist in the third-party credentials."); } } catch (NotConnectedException | PermissionException e) { throw new ValidationException("Exception during getting the third-party credentials.", e); } return parameterValue; }

Target:
public String validate(String parameterValue, ModelValidatorContext context) throws ValidationException { if (context == null || context.getScheduler() == null) { logger.debug(String.format("Can't check the validity of the variable value, because missing the access to the scheduler third-party credentials", parameterValue)); return parameterValue; } try { Set<String> credentialKeys = context.getScheduler().thirdPartyCredentialsKeySet(); if (!credentialKeys.contains(parameterValue)) { throw new ValidationException(String.format("Could not find the key named [%s] in the third-party credentials. Please add it into the scheduler third-party credentials or change the variable value to a valid key.", parameterValue)); } } catch (NotConnectedException | PermissionException e) { throw new ValidationException("Could not read third party-credentials from the scheduler, make sure you are connected and you have permission rights to read third-party credentials.", e); } return parameterValue; }
Source:
public boolean accept(TreeWalkerAuditEvent event) { return fileNameAndModuleAndCheckNameMismatches(event) || isXpathQueryMatching(event); }

Target:
public boolean accept(TreeWalkerAuditEvent event) { return !isFileNameAndModuleAndCheckNameMatching(event) || !isXpathQueryMatching(event); }
Source:
public void linkAccount(Long sourceId, String username, String password, String properties) { CoreService service = ServiceCreator.createCoreService(); final LinkAccountRequest input = new LinkAccountRequest(); input.accessCode = ACCESS_CODE; input.session = SessionController.get().getSessionForApiCall(); input.username = username; input.password = password; input.properties = properties; DataSource source = new DataSource(); source.id = sourceId; input.source = source; service.linkAccount(input, new AsyncCallback<LinkAccountResponse>() { @Override public void onSuccess(LinkAccountResponse output) { if (output.status == StatusType.StatusTypeSuccess) { rows.add(output.account); addLinkedAccountsToLookup(Arrays.asList(output.account)); addDataSourceToLookup(Arrays.asList(output.account.source)); if (pager == null) { pager = new Pager(); pager.count = (long) Integer.MAX_VALUE; pager.sortDirection = SortDirectionType.SortDirectionTypeDescending; pager.totalCount = Long.valueOf(0); } pager.totalCount = pager.totalCount + Long.valueOf(1); pager.start = Long.valueOf(0); mCount = pager.totalCount; updateRowCount((int) mCount, true); updateRowData(0, rows.subList(0, Math.min(pager.count.intValue(), pager.totalCount.intValue()))); } EventController.get().fireEventFromSource(new LinkAccountSuccess(input, output), LinkedAccountController.this); } @Override public void onFailure(Throwable caught) { EventController.get().fireEventFromSource(new LinkAccountFailure(input, caught), LinkedAccountController.this); } }); }

Target:
public void linkAccount(Long sourceId, String username, String password, String properties) { CoreService service = ServiceCreator.createCoreService(); final LinkAccountRequest input = new LinkAccountRequest(); input.accessCode = ACCESS_CODE; input.session = SessionController.get().getSessionForApiCall(); input.username = username; input.password = password; input.properties = properties; DataSource source = new DataSource(); source.id = sourceId; input.source = source; if (pager == null) { pager = new Pager(); pager.count = Long.valueOf(Integer.MAX_VALUE); pager.start = Long.valueOf(0); pager.sortDirection = SortDirectionType.SortDirectionTypeDescending; pager.totalCount = Long.valueOf(0); } service.linkAccount(input, new AsyncCallback<LinkAccountResponse>() { @Override public void onSuccess(LinkAccountResponse output) { if (output.status == StatusType.StatusTypeSuccess) { rows.add(output.account); addLinkedAccountsToLookup(Arrays.asList(output.account)); addDataSourceToLookup(Arrays.asList(output.account.source)); pager.totalCount = Long.valueOf(pager.totalCount.longValue() + 1); mCount = pager.totalCount; updateRowCount((int) mCount, true); updateRowData(0, rows.subList(0, Math.min(pager.count.intValue(), pager.totalCount.intValue()))); } EventController.get().fireEventFromSource(new LinkAccountSuccess(input, output), LinkedAccountController.this); } @Override public void onFailure(Throwable caught) { EventController.get().fireEventFromSource(new LinkAccountFailure(input, caught), LinkedAccountController.this); } }); }
Source:
public Boolean isRebalancerEnabled() { return Optional.of(rebalancerEnabled).or(DEFAULT_REBALANCER_ENABLED); }

Target:
public Boolean isRebalancerEnabled() { return Optional.fromNullable(rebalancer).or(DEFAULT_REBALANCER_ENABLED); }
Source:
public ResponseEntity<HalResource> addAttachmentToComponent(@PathVariable("componentId") String componentId, OAuth2Authentication oAuth2Authentication, @RequestPart("file") MultipartFile file, @RequestPart("attachment") Attachment newAttachment) throws TException { final User sw360User = restControllerHelper.getSw360UserFromAuthentication(oAuth2Authentication); Attachment attachment; try { attachment = attachmentService.uploadAttachment(file, newAttachment, sw360User); } catch (IOException e) { log.error(e.getMessage()); throw new RuntimeException(e); } final Component component = componentService.getComponentForUserById(componentId, sw360User); component.addToAttachments(attachment); componentService.updateComponent(component, sw360User); final HalResource halRelease = createHalComponent(component, sw360User); return new ResponseEntity<>(halRelease, HttpStatus.OK); }

Target:
public ResponseEntity<HalResource> addAttachmentToComponent(@PathVariable("componentId") String componentId, OAuth2Authentication oAuth2Authentication, @RequestPart("file") MultipartFile file, @RequestPart("attachment") Attachment newAttachment) throws TException { final User sw360User = restControllerHelper.getSw360UserFromAuthentication(oAuth2Authentication); Attachment attachment; try { attachment = attachmentService.uploadAttachment(file, newAttachment, sw360User); } catch (IOException e) { log.error("failed to upload attachment", e); throw new RuntimeException("failed to upload attachment", e); } final Component component = componentService.getComponentForUserById(componentId, sw360User); component.addToAttachments(attachment); componentService.updateComponent(component, sw360User); final HalResource halRelease = createHalComponent(component, sw360User); return new ResponseEntity<>(halRelease, HttpStatus.OK); }
Source:
private void performSingleNodeSolrBackup() throws URISyntaxException { verifySingleNodeBackupInput(); httpBuilder = new org.codice.solr.factory.impl.HttpClientBuilder(encryptionService); String url = AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty("solr.http.url")); String backupUrl = String.format("%s/%s/%s", url, coreName, "replication"); URIBuilder uriBuilder = new URIBuilder(backupUrl); uriBuilder.addParameter("command", "backup"); if (StringUtils.isNotBlank(backupLocation)) { uriBuilder.addParameter("location", backupLocation); } if (numberToKeep > 0) { uriBuilder.addParameter("numberToKeep", Integer.toString(numberToKeep)); } URI backupUri = uriBuilder.build(); processResponse(sendGetRequest(backupUri)); }

Target:
private void performSingleNodeSolrBackup() throws URISyntaxException { verifySingleNodeBackupInput(); httpBuilder = new org.codice.solr.factory.impl.HttpClientBuilder(encryptionService); String url = AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty("solr.http.url")); String backupUrl = String.format("%s/%s/replication", url, coreName); URIBuilder uriBuilder = new URIBuilder(backupUrl); uriBuilder.addParameter("command", "backup"); if (StringUtils.isNotBlank(backupLocation)) { uriBuilder.addParameter("location", backupLocation); } if (numberToKeep > 0) { uriBuilder.addParameter("numberToKeep", Integer.toString(numberToKeep)); } URI backupUri = uriBuilder.build(); processResponse(sendGetRequest(backupUri)); }
Source:
public void testSimpleRename() throws IOException { SimpleFeatureSource fs = store.getFeatureSource(BUILDINGS.getLocalPart()); SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder(); tb.init(fs.getSchema()); tb.setName("houses"); SimpleFeatureType target = tb.buildFeatureType(); SimpleFeatureSource retyped = RetypingFeatureSource.getRetypingSource(fs, target); assertEquals(target, retyped.getSchema()); assertEquals(target, ((DataStore) retyped.getDataStore()).getSchema("houses")); assertEquals(target, retyped.getFeatures().getSchema()); SimpleFeatureIterator it = retyped.getFeatures().features(); SimpleFeature f = it.next(); it.close(); assertEquals(target, f.getType()); }

Target:
public void testSimpleRename() throws IOException { SimpleFeatureSource fs = store.getFeatureSource(BUILDINGS.getLocalPart()); SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder(); tb.init(fs.getSchema()); tb.setName("houses"); SimpleFeatureType target = tb.buildFeatureType(); SimpleFeatureSource retyped = RetypingFeatureSource.getRetypingSource(fs, target); assertTrue(retyped instanceof SimpleFeatureLocking); assertEquals(target, retyped.getSchema()); assertEquals(target, ((DataStore) retyped.getDataStore()).getSchema("houses")); assertEquals(target, retyped.getFeatures().getSchema()); SimpleFeatureIterator it = retyped.getFeatures().features(); SimpleFeature f = it.next(); it.close(); assertEquals(target, f.getType()); }
Source:
public void testUserTask() throws Exception { Long processInstanceId = startProcessInstance(PROCESS_ID); UserTransaction ut = InitialContext.doLookup(USER_TRANSACTION_NAME); ut.begin(); List<TaskSummary> taskSummaries = null; try { processService.signalProcessInstance(processInstanceId, "start", "usertask"); taskSummaries = runtimeDataService.getTasksAssignedAsPotentialOwner("john", new QueryFilter()); Assertions.assertThat(taskSummaries).isNotNull().hasSize(1); userTaskService.start(taskSummaries.get(0).getId(), "john"); userTaskService.complete(taskSummaries.get(0).getId(), "john", new HashMap<String, Object>()); Assertions.assertThat(hasNodeLeft(processInstanceId, "User Task")).isTrue(); } catch (Exception e) { ut.rollback(); throw e; } ut.rollback(); ut = InitialContext.doLookup(USER_TRANSACTION_NAME); ut.begin(); try { processService.signalProcessInstance(processInstanceId, "start", "usertask"); taskSummaries = runtimeDataService.getTasksAssignedAsPotentialOwner("john", new QueryFilter()); Assertions.assertThat(taskSummaries).isNotNull().hasSize(1); userTaskService.start(taskSummaries.get(0).getId(), "john"); userTaskService.complete(taskSummaries.get(0).getId(), "john", new HashMap<String, Object>()); } catch (Exception e) { ut.rollback(); throw e; } ut.commit(); Assertions.assertThat(hasNodeLeft(processInstanceId, "User Task")).isTrue(); Assertions.assertThat(hasTaskCompleted(taskSummaries.get(0).getId())); Assertions.assertThat(hasProcessInstanceCompleted(processInstanceId)).isFalse(); }

Target:
public void testUserTask() throws Exception { Long processInstanceId = startProcessInstance(PROCESS_ID); UserTransaction ut = InitialContext.doLookup(USER_TRANSACTION_NAME); ut.begin(); List<TaskSummary> taskSummaries = null; try { processService.signalProcessInstance(processInstanceId, "start", "usertask"); taskSummaries = startAndCompleteHumanTask(processInstanceId); } catch (Exception e) { ut.rollback(); throw e; } ut.rollback(); Assertions.assertThat(runtimeDataService.getTaskById(taskSummaries.get(0).getId())).isNull(); ut = InitialContext.doLookup(USER_TRANSACTION_NAME); ut.begin(); try { processService.signalProcessInstance(processInstanceId, "start", "usertask"); taskSummaries = startAndCompleteHumanTask(processInstanceId); } catch (Exception e) { ut.rollback(); throw e; } ut.commit(); Assertions.assertThat(hasNodeLeft(processInstanceId, "User Task")).isTrue(); Assertions.assertThat(hasTaskCompleted(taskSummaries.get(0).getId())); Assertions.assertThat(hasProcessInstanceCompleted(processInstanceId)).isFalse(); }
Source:
public void clearCandidates() { fTraceTypes.clear(); fTraceFiles.clear(); }

Target:
public synchronized void clearCandidates() { fTraceTypes.clear(); fTraceFiles.clear(); }
Source:
public void testChild() { final Object child = new ParseTreeTablePModel(null).getChild(tree, 0); Assert.assertTrue(child instanceof DetailAST); Assert.assertSame(((DetailAST) child).getType(), TokenTypes.MODIFIERS); }

Target:
public void testChild() { final Object child = new ParseTreeTablePModel(null).getChild(tree, 1); Assert.assertTrue(child instanceof DetailAST); Assert.assertEquals(TokenTypes.BLOCK_COMMENT_BEGIN, ((AST) child).getType()); }
Source:
public boolean isValid(T value, ConstraintValidatorContext context) { if ( value == null ) { return true; } long result = this.getCurrentAge( value ) - this.referenceAge; return isValid( result ); }

Target:
public boolean isValid(T value, ConstraintValidatorContext context) { if ( value == null ) { return true; } int result = getInstant( value ).atZone( ZoneOffset.ofHours( 0 ) ).toLocalDate() .compareTo( LocalDate.now( referenceClock ).minus( referenceAge, unit ) ); return isValid( result ); }
Source:
public void executeCallback(final String callbackId) { if (callbackId.equals("callback-dom-loaded")) { mWebView.post(new Runnable() { public void run() { String htmlFile = ""; try { htmlFile = getStringFromAsset("example-content.html"); htmlFile = htmlFile.replace("\\", "\\\\"); htmlFile = htmlFile.replace("\"", "\\\""); htmlFile = htmlFile.replace("'", "\\'"); htmlFile = htmlFile.replace("\r", "\\r"); htmlFile = htmlFile.replace("\n", "\\n"); } catch (IOException e) { AppLog.e(T.EDITOR, e.getMessage()); } mWebView.loadUrl("JavaScript:ZSSEditor.getField('zss_field_title').setHTML('" + "I\\'m editing a post!" + "');"); mWebView.loadUrl("JavaScript:ZSSEditor.getField('zss_field_content').setHTML('" + htmlFile + "');"); } }); } }

Target:
public void executeCallback(final String callbackId) { if (callbackId.equals("callback-dom-loaded")) { mWebView.post(new Runnable() { public void run() { String title = "I'm editing a post!"; String contentHtml = getHtmlFromFile("example-content.html"); mWebView.loadUrl("javascript:ZSSEditor.getField('zss_field_title').setHTML('" + Utils.escapeHtml(title) + "');"); mWebView.loadUrl("javascript:ZSSEditor.getField('zss_field_content').setHTML('" + Utils.escapeHtml(contentHtml) + "');"); } }); } }
Source:
public void run() { while (true) { try { NativeObjectReference reference = (NativeObjectReference) referenceQueue.remove(); reference.cleanup(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }

Target:
public void run() { while (true) { try { NativeObjectReference reference = (NativeObjectReference) referenceQueue.remove(); reference.cleanup(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); RealmLog.fatal("The FinalizerRunnable thread has been interrupted." + " Native resources cannot be freed anymore"); break; } } }
Source:
public TidalControl(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{1}{U}{U}"); this.addAbility(new CumulativeUpkeepAbility(new ManaCostsImpl("{2}"))); SimpleActivatedAbility ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new CounterTargetEffect(), new PayLifeCost(2)); ability.addTarget(new TargetSpell(filter)); ability.setMayActivate(TargetController.ANY); ability.addEffect(new InfoEffect("Any player may activate this ability")); this.addAbility(ability); ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new CounterTargetEffect(), new ManaCostsImpl("{2}")); ability.addTarget(new TargetSpell(filter)); ability.setMayActivate(TargetController.ANY); ability.addEffect(new InfoEffect("Any player may activate this ability")); this.addAbility(ability); }

Target:
public TidalControl(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{1}{U}{U}"); this.addAbility(new CumulativeUpkeepAbility(new ManaCostsImpl("{2}"))); SimpleActivatedAbility ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new CounterTargetEffect(), new OrCost(new PayLifeCost(2), new ManaCostsImpl("{2}"), "pay 2 life or pay {2}")); ability.addTarget(new TargetSpell(filter)); ability.setMayActivate(TargetController.ANY); ability.addEffect(new InfoEffect("Any player may activate this ability")); this.addAbility(ability); }
Source:
long retrieveStore( StoreFileStreams storeFileStreams, StoreId expectedStoreId ) throws StoreCopyFailedException { long latestTxNumber = storeCopyClient.copyStoreFiles( fromAddress, expectedStoreId, storeFileStreams ); try { storeFileStreams.close(); } catch ( Exception e ) { throw new RuntimeException( e ); } return latestTxNumber; }

Target:
long retrieveStore( StoreFileStreams storeFileStreams, StoreId expectedStoreId ) throws StoreCopyFailedException { long latestTxNumber = storeCopyClient.copyStoreFiles( fromAddress, expectedStoreId, storeFileStreams ); try { storeFileStreams.close(); } catch ( Exception e ) { throw Exceptions.launderedException(e); } return latestTxNumber; }
Source:
static <R, T> KeyValue<R, T> create(R k, T v) { return new KeyValue<R, T>(k, v); }

Target:
public static <R, T> KeyValue<R, T> create(R k, T v) { return new KeyValue<R, T>(k, v); }
Source:
private void checkFailedCoordinatorNode(SegmentationPolicy segPlc) throws Exception { try { this.segPlc = segPlc; IgniteEx coord = (IgniteEx)startGridsMultiThreaded(3); UUID coordId = coord.localNode().id(); IgniteEx ignite1 = grid(1); AtomicBoolean coordSegmented = new AtomicBoolean(); coord.events().localListen(evt -> { assertEquals(EVT_NODE_SEGMENTED, evt.type()); UUID nodeId = ((DiscoveryEvent)evt).eventNode().id(); if (coordId.equals(nodeId)) coordSegmented.set(true); return true; }, EVT_NODE_SEGMENTED); CountDownLatch failedLatch = new CountDownLatch(2); IgnitePredicate<Event> failLsnr = evt -> { assertEquals(EVT_NODE_FAILED, evt.type()); UUID nodeId = ((DiscoveryEvent)evt).eventNode().id(); if (coordId.equals(nodeId)) failedLatch.countDown(); return true; }; ignite1.events().localListen(failLsnr, EVT_NODE_FAILED); grid(2).events().localListen(failLsnr, EVT_NODE_FAILED); ignite1.configuration().getDiscoverySpi().failNode(coordId, null); assertTrue(failedLatch.await(ignite1.configuration().getFailureDetectionTimeout() + 50, MILLISECONDS)); assertTrue(coordSegmented.get()); if (segPlc == SegmentationPolicy.STOP) { assertTrue(coord.context().isStopping()); waitNodeStop(coord.name()); } else assertFalse(coord.context().isStopping()); assertEquals(2, ignite1.context().discovery().allNodes().size()); } finally { stopAllGrids(); } }

Target:
private void checkFailedCoordinatorNode(SegmentationPolicy segPlc) throws Exception { try { this.segPlc = segPlc; IgniteEx coord = (IgniteEx)startGridsMultiThreaded(3); UUID coordId = coord.localNode().id(); IgniteEx ignite1 = grid(1); AtomicBoolean coordSegmented = new AtomicBoolean(); coord.events().localListen(evt -> { assertEquals(EVT_NODE_SEGMENTED, evt.type()); UUID nodeId = ((DiscoveryEvent)evt).eventNode().id(); if (coordId.equals(nodeId)) coordSegmented.set(true); return true; }, EVT_NODE_SEGMENTED); CountDownLatch failedLatch = new CountDownLatch(2); IgnitePredicate<Event> failLsnr = evt -> { assertEquals(EVT_NODE_FAILED, evt.type()); UUID nodeId = ((DiscoveryEvent)evt).eventNode().id(); if (coordId.equals(nodeId)) failedLatch.countDown(); return true; }; ignite1.events().localListen(failLsnr, EVT_NODE_FAILED); grid(2).events().localListen(failLsnr, EVT_NODE_FAILED); ignite1.configuration().getDiscoverySpi().failNode(coordId, null); assertTrue(failedLatch.await(2000, MILLISECONDS)); assertTrue(coordSegmented.get()); if (segPlc == SegmentationPolicy.STOP) { assertTrue(coord.context().isStopping()); waitNodeStop(coord.name()); } else assertFalse(coord.context().isStopping()); assertEquals(2, ignite1.context().discovery().allNodes().size()); } finally { stopAllGrids(); } }
Source:
public JMSSettingsModifyEvent(SettingsInfo source, List<String> propertyNames, List<Object> oldValues, List<Object> newValues, JMSEventType eventType) { super(source, propertyNames, oldValues, newValues); this.eventType = eventType; }

Target:
public JMSSettingsModifyEvent(SettingsInfo source, List<String> propertyNames, List<Object> oldValues, List<Object> newValues, JMSEventType eventType) { super(source, propertyNames, oldValues, newValues, eventType); }
Source:
HttpRequest replaceAuthorizationHeader(HttpRequest request, String signature) { if (request.getEndpoint().toString().contains("Signature")) { return request; } request = request.toBuilder() .replaceHeader(HttpHeaders.AUTHORIZATION, authTag + " " + creds.get().identity + ":" + signature).build(); return request; }

Target:
HttpRequest replaceAuthorizationHeader(HttpRequest request, String signature) { if (Queries.queryParser().apply(request.getEndpoint().getQuery()).containsKey("Signature")) { return request; } request = request.toBuilder() .replaceHeader(HttpHeaders.AUTHORIZATION, authTag + " " + creds.get().identity + ":" + signature).build(); return request; }
Source:
private synchronized void checkForUpdates() { if (!forceReload && (reloadCheckIntervalInMs < 0 || System.currentTimeMillis() < (lastReloadCheck + reloadCheckIntervalInMs))) { return; } lastReloadCheck = System.currentTimeMillis(); if (providers.size() < 1) { return; } boolean shouldReload = forceReload; for (ConfigurationProviderState provider : providers) { if (provider.shouldReload()) { shouldReload = true; } } if (!shouldReload) { return; } reload(); }

Target:
private synchronized void checkForUpdates() { if (!forceReload && (reloadCheckIntervalInMs < 0 || System.currentTimeMillis() < (lastReloadCheck + reloadCheckIntervalInMs))) { return; } lastReloadCheck = System.currentTimeMillis(); if (providers.size() < 1) { return; } if (forceReload || providers.stream().anyMatch(ConfigurationProviderState::shouldReload)) { reload(); } }
Source:
private void rotate() { if ( rotating.getAndSet( true ) ) { return; } Runnable runnable = () -> { synchronized ( outRef ) { OutputStream oldStream = outRef.get(); try { oldStream.flush(); oldStream.close(); } catch ( Exception e ) { rotationListener.rotationError( e, outRef.get() ); rotating.set( false ); return; } OutputStream newStream; try { if ( fileSystem.fileExists( outputFile ) ) { shiftArchivedOutputFiles(); fileSystem.renameFile( outputFile, archivedOutputFile( 1 ) ); } newStream = openOutputFile(); } catch ( Exception e ) { rotationListener.rotationError( e, outRef.get() ); rotating.set( false ); return; } rotationListener.outputFileCreated( newStream, oldStream ); if ( !closed.get() ) { outRef.set( newStream ); removeCollectedReferences( archivedStreams ); archivedStreams.add( new WeakReference<>( oldStream ) ); } if ( rotationDelay > 0 ) { earliestRotationTimeRef.set( currentTimeSupplier.getAsLong() + rotationDelay ); } rotationListener.rotationCompleted( newStream, oldStream ); rotating.set( false ); } }; try { rotationExecutor.execute( runnable ); } catch ( Exception e ) { rotationListener.rotationError( e, outRef.get() ); rotating.set( false ); } }

Target:
private void rotate() { if ( rotating.getAndSet( true ) ) { return; } Runnable runnable = () -> { logFileLock.writeLock().lock(); try { try { try { outRef.flush(); outRef.close(); outRef = nullStream; } catch ( Exception e ) { rotationListener.rotationError( e, streamWrapper ); return; } try { if ( fileSystem.fileExists( outputFile ) ) { shiftArchivedOutputFiles(); fileSystem.renameFile( outputFile, archivedOutputFile( 1 ) ); } } catch ( Exception e ) { rotationListener.rotationError( e, streamWrapper ); return; } } finally { try { if ( !closed.get() && outRef.equals( nullStream ) ) { outRef = openOutputFile(); rotationListener.outputFileCreated( streamWrapper ); } } catch ( IOException e ) { System.err.println( "Failed to open log file after log rotation: " + e.getMessage() ); rotationListener.rotationError( e, streamWrapper ); } } if ( rotationDelay > 0 ) { earliestRotationTimeRef.set( currentTimeSupplier.getAsLong() + rotationDelay ); } rotationListener.rotationCompleted( streamWrapper ); } finally { rotating.set( false ); logFileLock.writeLock().unlock(); } }; try { rotationExecutor.execute( runnable ); } catch ( Exception e ) { rotationListener.rotationError( e, streamWrapper ); rotating.set( false ); } }