auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public UserAccount getUser(UserFilter userFilter) { String username = ""; String name = ""; String announcement; String closedDateAsString; String data = USER + String.format(QUERY_USER_ATTRIBUTES, userFilter.getUid()); Log.d(TAG, String.format("getUserAttributesApiCall(%s) -> %s", USER, data)); try { String response = executeCall(DHIS_PULL_API+data); JsonNode jsonNode = parseResponse(response); JsonNode jsonNodeArray = jsonNode.get(ATTRIBUTEVALUES); String newMessage = ""; String closeDate = ""; for (int i = 0; i < jsonNodeArray.size(); i++) { newMessage = getUserAnnouncement(jsonNodeArray, newMessage, i, UserDB.ATTRIBUTE_USER_ANNOUNCEMENT); closeDate = getUserCloseDate(jsonNodeArray, closeDate, i); } announcement =newMessage; closedDateAsString=closeDate; username = getUsername(jsonNode); name = getName(jsonNode); } catch (Exception ex) { Log.e(TAG, "Cannot read user last updated from server with"); ex.printStackTrace(); return null; } UserAccount userAccount = new UserAccount(name, username, userFilter.getUid(), announcement, parseClosedDate(closedDateAsString)); return userAccount; }

Target:
public UserAccount getUser(UserFilter userFilter) throws GetUserAccountException { String username = ""; String name = ""; String announcement; String closedDateAsString; String data = USER + String.format(QUERY_USER_ATTRIBUTES, userFilter.getUid()); Log.d(TAG, String.format("getUserAttributesApiCall(%s) -> %s", USER, data)); try { String response = executeCall(DHIS_PULL_API+data); JsonNode jsonNode = parseResponse(response); JsonNode jsonNodeArray = jsonNode.get(ATTRIBUTEVALUES); String newMessage = ""; String closeDate = ""; for (int i = 0; i < jsonNodeArray.size(); i++) { newMessage = getUserAnnouncement(jsonNodeArray, newMessage, i, UserDB.ATTRIBUTE_USER_ANNOUNCEMENT); closeDate = getUserCloseDate(jsonNodeArray, closeDate, i); } announcement =newMessage; closedDateAsString=closeDate; username = getUsername(jsonNode); name = getName(jsonNode); } catch (Exception ex) { Log.e(TAG, "Cannot read user last updated from server with"); ex.printStackTrace(); throw new GetUserAccountException(); } UserAccount userAccount = new UserAccount(name, username, userFilter.getUid(), announcement, parseClosedDate(closedDateAsString)); return userAccount; }
Source:
public VeirfyBulkJobResult call() throws Exception { try{ final Ds3ClientHelpers helper = getClientHelpers(); final Iterable<Contents> bulkContents = helper.listObjects(this.bucketName, this.prefix); if (bulkContents == null || !bulkContents.iterator().hasNext()) { throw new CommandException("No objects in bucket '" + this.bucketName + "' with prefix '" + this.prefix + "'"); } final List<Ds3Object> objectList = new ArrayList<>(); for (final Contents contents : bulkContents) { objectList.add(new Ds3Object(contents.getKey(), contents.getSize())); } final VerifyBulkJobSpectraS3Response verifyResponse = getClient().verifyBulkJobSpectraS3(new VerifyBulkJobSpectraS3Request(this.bucketName, objectList )); return new VeirfyBulkJobResult(this.bucketName, verifyResponse.getMasterObjectListResult().getObjects().iterator()); } catch (final FailedRequestException e) { if (e.getStatusCode() == 500) { throw new CommandException("Error: Cannot communicate with the remote DS3 appliance.", e); } else if (e.getStatusCode() == 404) { throw new CommandException("Cannot locate bucket: " + this.bucketName, e); } else { throw new CommandException("Encountered an unknown error of ("+ e.getStatusCode() +") while accessing the remote DS3 appliance.", e); } } }

Target:
public VerifyBulkJobResult call() throws Exception { try{ final Ds3ClientHelpers helper = getClientHelpers(); final Iterable<Contents> bulkContents = helper.listObjects(this.bucketName, this.prefix); if (bulkContents == null || !bulkContents.iterator().hasNext()) { throw new CommandException("No objects in bucket '" + this.bucketName + "' with prefix '" + this.prefix + "'"); } final List<Ds3Object> objectList = new ArrayList<>(); for (final Contents contents : bulkContents) { objectList.add(new Ds3Object(contents.getKey(), contents.getSize())); } final VerifyBulkJobSpectraS3Response verifyResponse = getClient().verifyBulkJobSpectraS3(new VerifyBulkJobSpectraS3Request(this.bucketName, objectList )); return new VerifyBulkJobResult(this.bucketName, verifyResponse.getMasterObjectListResult().getObjects().iterator()); } catch (final FailedRequestException e) { if (e.getStatusCode() == 500) { throw new CommandException("Error: Cannot communicate with the remote DS3 appliance.", e); } else if (e.getStatusCode() == 404) { throw new CommandException("Cannot locate bucket: " + this.bucketName, e); } else { throw new CommandException("Encountered an unknown error of ("+ e.getStatusCode() +") while accessing the remote DS3 appliance.", e); } } }
Source:
private Set<K> determineExcludedKeys(Map<Integer, Set<K>> keysToExclude, IntSet segmentsToUse) { if (keysToExclude.isEmpty()) { return Collections.emptySet(); } return segmentsToUse.intStream() .boxed() .flatMap(s -> { Set<K> keysForSegment = keysToExclude.get(s); if (keysForSegment != null) { return keysForSegment.stream(); } return null; }) .collect(Collectors.toSet()); }

Target:
private Set<K> determineExcludedKeys(Map<Integer, Set<K>> keysToExclude, IntSet segmentsToUse) { if (keysToExclude.isEmpty()) { return Collections.emptySet(); } Set<K> excludedKeys = new HashSet<>(); for (PrimitiveIterator.OfInt segmentIterator = segmentsToUse.iterator(); segmentIterator.hasNext(); ) { Integer segment = segmentIterator.nextInt(); Set<K> keysForSegment = keysToExclude.get(segment); if (keysForSegment != null) { excludedKeys.addAll(keysForSegment); } } return excludedKeys; }
Source:
public ActivationKeyDTO addPoolToKey( @PathParam("activation_key_id") @Verify(ActivationKey.class) String activationKeyId, @PathParam("pool_id") @Verify(Pool.class) String poolId, @QueryParam("quantity") Long quantity) { ActivationKey key = this.fetchActivationKey(activationKeyId); Pool pool = findPool(poolId); activationKeyRules.validatePoolForActivationKey(key, pool, quantity) .ifPresent(message -> { throw new BadRequestException(message); }); if (key.hasPool(pool)) { throw new BadRequestException( i18n.tr("Pool ID \"{0}\" has already been registered with this activation key", poolId) ); } key.addPool(pool, quantity); activationKeyCurator.update(key); return this.translator.translate(key, ActivationKeyDTO.class); }

Target:
public ActivationKeyDTO addPoolToKey( @PathParam("activation_key_id") @Verify(ActivationKey.class) String activationKeyId, @PathParam("pool_id") @Verify(Pool.class) String poolId, @QueryParam("quantity") Long quantity) { ActivationKey key = this.fetchActivationKey(activationKeyId); Pool pool = findPool(poolId); String message = activationKeyRules.validatePoolForActivationKey(key, pool, quantity); if (message != null) { throw new BadRequestException(message); } if (key.hasPool(pool)) { throw new BadRequestException( i18n.tr("Pool ID \"{0}\" has already been registered with this activation key", poolId) ); } key.addPool(pool, quantity); activationKeyCurator.update(key); return this.translator.translate(key, ActivationKeyDTO.class); }
Source:
public T getLastValue() { synchronized (arguments) { if (arguments.isEmpty()) { throw noArgumentValueWasCaptured(); } return (T) arguments.get(arguments.size() - 1); } }

Target:
public T getLastValue() { readLock.lock(); try { if (arguments.isEmpty()) { throw noArgumentValueWasCaptured(); } return (T) arguments.get(arguments.size() - 1); } finally { readLock.unlock(); } }
Source:
public Map<String, String> getCustomValues() { addCustomValue("ClusterName", getVdsGroupName()); return super.getCustomValues(); }

Target:
public Map<String, String> getCustomValues() { return super.getCustomValues(); }
Source:
public TransportClientFactory newTransportClientFactory(final EurekaClientConfig clientConfig, final Collection<ClientRequestFilter> additionalFilters, final InstanceInfo myInstanceInfo) { final TransportClientFactory jerseyFactory = Jersey2ApplicationClientFactory.create( clientConfig, additionalFilters, myInstanceInfo, new EurekaClientIdentity(myInstanceInfo.getIPAddr()) ); final TransportClientFactory metricsFactory = MetricsCollectingEurekaHttpClient.createFactory(jerseyFactory); return new TransportClientFactory() { @Override public EurekaHttpClient newClient(EurekaEndpoint serviceUrl) { return metricsFactory.newClient(serviceUrl); } @Override public void shutdown() { metricsFactory.shutdown(); jerseyFactory.shutdown(); } }; }

Target:
public TransportClientFactory newTransportClientFactory(final EurekaClientConfig clientConfig, final Collection<ClientRequestFilter> additionalFilters, final InstanceInfo myInstanceInfo) { final TransportClientFactory jerseyFactory = Jersey2ApplicationClientFactory.create( clientConfig, additionalFilters, myInstanceInfo, new EurekaClientIdentity(myInstanceInfo.getIPAddr(), "Jersey2DefaultClient") ); final TransportClientFactory metricsFactory = MetricsCollectingEurekaHttpClient.createFactory(jerseyFactory); return new TransportClientFactory() { @Override public EurekaHttpClient newClient(EurekaEndpoint serviceUrl) { return metricsFactory.newClient(serviceUrl); } @Override public void shutdown() { metricsFactory.shutdown(); jerseyFactory.shutdown(); } }; }
Source:
public ActionResult execute() throws EntityDoesNotExistException { String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); Assumption.assertNotNull(courseId); String studentEmail = getRequestParamValue(Const.ParamsNames.STUDENT_EMAIL); Assumption.assertNotNull(studentEmail); InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, account.googleId); new GateKeeper().verifyAccessible( instructor, logic.getCourse(courseId), Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_STUDENT); StudentAttributes student = logic.getStudentForEmail(courseId, studentEmail); if (student == null) { statusToUser.add(new StatusMessage(Const.StatusMessages.STUDENT_NOT_FOUND_EDIT, StatusMessageColor.DANGER)); isError = true; return createRedirectResult(Const.ActionURIs.INSTRUCTOR_HOME_PAGE); } boolean hasSection = logic.hasIndicatedSections(courseId); InstructorCourseStudentDetailsEditPageData data = new InstructorCourseStudentDetailsEditPageData(account, student, student.email, hasSection); statusToAdmin = "instructorCourseStudentEdit Page Load<br>" + "Editing Student <span class=\"bold\">" + studentEmail +"'s</span> details " + "in Course <span class=\"bold\">[" + courseId + "]</span>"; return createShowPageResult(Const.ViewURIs.INSTRUCTOR_COURSE_STUDENT_EDIT, data); }

Target:
public ActionResult execute() throws EntityDoesNotExistException { String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); Assumption.assertNotNull(courseId); String studentEmail = getRequestParamValue(Const.ParamsNames.STUDENT_EMAIL); Assumption.assertNotNull(studentEmail); InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, account.googleId); new GateKeeper().verifyAccessible( instructor, logic.getCourse(courseId), Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_STUDENT); StudentAttributes student = logic.getStudentForEmail(courseId, studentEmail); if (student == null) { statusToUser.add(new StatusMessage(Const.StatusMessages.STUDENT_NOT_FOUND_FOR_EDIT, StatusMessageColor.DANGER)); isError = true; return createRedirectResult(Const.ActionURIs.INSTRUCTOR_HOME_PAGE); } boolean hasSection = logic.hasIndicatedSections(courseId); InstructorCourseStudentDetailsEditPageData data = new InstructorCourseStudentDetailsEditPageData(account, student, student.email, hasSection); statusToAdmin = "instructorCourseStudentEdit Page Load<br>" + "Editing Student <span class=\"bold\">" + studentEmail +"'s</span> details " + "in Course <span class=\"bold\">[" + courseId + "]</span>"; return createShowPageResult(Const.ViewURIs.INSTRUCTOR_COURSE_STUDENT_EDIT, data); }
Source:
public void rebootUtilTest() throws Exception { final int PORT_0 = 9000; final String SERVER_0 = "localhost:" + PORT_0; final int retries = 3; Process corfuServer = runPersistentServer(corfuSingleNodeHost, PORT_0, true); runtime = createDefaultRuntime(); Layout layout = incrementClusterEpoch(runtime); RebootUtil.restart(SERVER_0, runtime.getParameters(), retries, PARAMETERS.TIMEOUT_LONG); waitForEpochChange(epoch -> epoch >= layout.getEpoch() + 1, runtime); assertThat(shutdownCorfuServer(corfuServer)).isTrue(); runtime.shutdown(); corfuServer = runPersistentServer(corfuSingleNodeHost, PORT_0, true); runtime = createDefaultRuntime(); incrementClusterEpoch(runtime); RebootUtil.reset(SERVER_0, runtime.getParameters(), retries, PARAMETERS.TIMEOUT_LONG); runtime = createDefaultRuntime(); waitForEpochChange(epoch -> epoch == 0, runtime); assertThat(shutdownCorfuServer(corfuServer)).isTrue(); }

Target:
public void rebootUtilTest() throws Exception { final int PORT_0 = 9000; final String SERVER_0 = "localhost:" + PORT_0; final int retries = 3; Process corfuServer = runPersistentServer(corfuSingleNodeHost, PORT_0, true); runtime = createDefaultRuntime(); Layout layout = incrementClusterEpoch(runtime); RebootUtil.restart(SERVER_0, runtime.getParameters(), retries, PARAMETERS.TIMEOUT_LONG); waitForEpochChange(epoch -> epoch >= layout.getEpoch() + 1, runtime); runtime = createDefaultRuntime(); RebootUtil.reset(SERVER_0, runtime.getParameters(), retries, PARAMETERS.TIMEOUT_LONG); runtime = createDefaultRuntime(); waitForEpochChange(epoch -> epoch == 0, runtime); assertThat(shutdownCorfuServer(corfuServer)).isTrue(); }
Source:
private static String[] zipEntryContent(byte[] zipData, String path) throws IOException { final ZipInputStream in = new ZipInputStream( new ByteArrayInputStream(zipData)); ZipEntry e; while ((e = in.getNextEntry()) != null) { if (!e.getName().equals(path)) continue; final List<String> l = new ArrayList<String>(); final BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) l.add(line); return l.toArray(new String[l.size()]); } return null; }

Target:
private static String[] zipEntryContent(byte[] zipData, String path) throws IOException { final ZipInputStream in = new ZipInputStream( new ByteArrayInputStream(zipData)); ZipEntry e; while ((e = in.getNextEntry()) != null) { if (!e.getName().equals(path)) continue; final List<String> l = new ArrayList<String>(); final BufferedReader reader = new BufferedReader( new InputStreamReader(in, "UTF-8")); String line; while ((line = reader.readLine()) != null) l.add(line); return l.toArray(new String[l.size()]); } return null; }
Source:
public int getGroupingKeySize() { return Doubles.BYTES; }

Target:
public int getGroupingKeySize() { return Double.BYTES; }
Source:
public Jwt encode(JoseHeader headers, JwtClaimsSet claims) throws JwtEncodingException { Assert.notNull(headers, "headers cannot be null"); Assert.notNull(claims, "claims cannot be null"); headers = JoseHeader.from(headers) .type(JOSEObjectType.JWT.getType()) .keyId(this.jwk.getKeyID()) .build(); JWSHeader jwsHeader = JWS_HEADER_CONVERTER.convert(headers); claims = JwtClaimsSet.from(claims) .id(UUID.randomUUID().toString()) .build(); JWTClaimsSet jwtClaimsSet = JWT_CLAIMS_SET_CONVERTER.convert(claims); SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaimsSet); try { signedJWT.sign(this.jwsSigner); } catch (JOSEException ex) { throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex); } String jws = signedJWT.serialize(); return new Jwt(jws, claims.getIssuedAt(), claims.getExpiresAt(), headers.getHeaders(), claims.getClaims()); }

Target:
public Jwt encode(JoseHeader headers, JwtClaimsSet claims) throws JwtEncodingException { Assert.notNull(headers, "headers cannot be null"); Assert.notNull(claims, "claims cannot be null"); JWK jwk = this.jwkSelector.apply(headers); if (jwk == null) { throw new JwtEncodingException( String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to select a JWK signing key")); } else if (!StringUtils.hasText(jwk.getKeyID())) { throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "The \"kid\" (key ID) from the selected JWK cannot be empty")); } JWSSigner jwsSigner = this.jwsSigners.computeIfAbsent(jwk, (key) -> { try { return JWS_SIGNER_FACTORY.createJWSSigner(key); } catch (JOSEException ex) { throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to create a JWS Signer -> " + ex.getMessage()), ex); } }); JoseHeader.Builder headersBuilder = JoseHeader.from(headers) .type(JOSEObjectType.JWT.getType()) .keyId(jwk.getKeyID()); JwtClaimsSet.Builder claimsBuilder = JwtClaimsSet.from(claims) .id(UUID.randomUUID().toString()); this.jwtCustomizer.accept(headersBuilder, claimsBuilder); headers = headersBuilder.build(); claims = claimsBuilder.build(); JWSHeader jwsHeader = JWS_HEADER_CONVERTER.convert(headers); JWTClaimsSet jwtClaimsSet = JWT_CLAIMS_SET_CONVERTER.convert(claims); SignedJWT signedJwt = new SignedJWT(jwsHeader, jwtClaimsSet); try { signedJwt.sign(jwsSigner); } catch (JOSEException ex) { throw new JwtEncodingException( String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to sign the JWT -> " + ex.getMessage()), ex); } String jws = signedJwt.serialize(); return new Jwt(jws, claims.getIssuedAt(), claims.getExpiresAt(), headers.getHeaders(), claims.getClaims()); }
Source:
public List<PropertyEditorCategory> getPropertyCategories() { List<PropertyEditorCategory> result = new ArrayList<>(); PropertyEditorCategory category = layoutCssHelper.createCategory(LayoutEditorCssHelper.CSS_CATEGORY_PANEL); category.withField(layoutCssHelper.createField(this, CssProperty.WIDTH)); category.withField(layoutCssHelper.createField(this, CssProperty.HEIGHT)); category.withField(layoutCssHelper.createField(this, CssProperty.BACKGROUND_COLOR)); result.add(category); category = layoutCssHelper.createCategory(LayoutEditorCssHelper.CSS_CATEGORY_MARGIN); category.withField(layoutCssHelper.createField(this, CssProperty.MARGIN_TOP)); category.withField(layoutCssHelper.createField(this, CssProperty.MARGIN_BOTTOM)); category.withField(layoutCssHelper.createField(this, CssProperty.MARGIN_LEFT)); category.withField(layoutCssHelper.createField(this, CssProperty.MARGIN_RIGHT)); result.add(category); category = layoutCssHelper.createCategory(LayoutEditorCssHelper.CSS_CATEGORY_PADDING); category.withField(layoutCssHelper.createField(this, CssProperty.PADDING_TOP)); category.withField(layoutCssHelper.createField(this, CssProperty.PADDING_BOTTOM)); category.withField(layoutCssHelper.createField(this, CssProperty.PADDING_LEFT)); category.withField(layoutCssHelper.createField(this, CssProperty.PADDING_RIGHT)); result.add(category); return result; }

Target:
public List<PropertyEditorCategory> getPropertyCategories() { return layoutCssHelper.getRowPropertyCategories(this); }
Source:
private void stopLogReplication() { switch(localClusterDescriptor.getRole()) { case ACTIVE: log.info("This cluster has lost leadership. Stopping lof replication, according to role {}", localClusterDescriptor.getRole()); replicationManager.stop(); break; case STANDBY: log.info("This cluster has lost leadership. Stopping lof replication, according to role {}", localClusterDescriptor.getRole()); interClusterReplicationService.getLogReplicationServer().setLeadership(false); break; default: log.warn("Invalid role type {}. Failed to stop replication if any running.", localClusterDescriptor.getRole()); break; } }

Target:
private void stopLogReplication() { switch(localClusterDescriptor.getRole()) { case ACTIVE: log.info("This cluster has lost leadership. Stopping log replication, according to role {}", localClusterDescriptor.getRole()); replicationManager.stop(); break; case STANDBY: log.info("This cluster has lost leadership. Stopping log replication, according to role {}", localClusterDescriptor.getRole()); interClusterReplicationService.getLogReplicationServer().setLeadership(false); break; default: log.warn("Invalid role type {}. Failed to stop replication if any running.", localClusterDescriptor.getRole()); break; } }
Source:
private void update(Username username, PackageDefinition packageDeinition, HttpLocalizedOperationResult result, EntityConfigUpdateCommand command) { try { goConfigService.updateConfig(command, username); } catch (Exception e) { if (e instanceof GoConfigInvalidException && !result.hasMessage()) { result.unprocessableEntity(entityConfigValidationFailed(packageDeinition.getClass().getAnnotation(ConfigTag.class).value(), packageDeinition.getId(), e.getMessage())); } else if (e instanceof RulesViolationException || e instanceof SecretResolutionFailureException) { LOGGER.error(e.getMessage(), e); result.unprocessableEntity(saveFailedWithReason(e.getMessage())); } else { if (!result.hasMessage()) { LOGGER.error(e.getMessage(), e); result.internalServerError(saveFailedWithReason("An error occurred while saving the package config. Please check the logs for more information.")); } } } }

Target:
private void update(Username username, PackageDefinition packageDeinition, HttpLocalizedOperationResult result, EntityConfigUpdateCommand command) { try { goConfigService.updateConfig(command, username); } catch (Exception e) { if (e instanceof GoConfigInvalidException && !result.hasMessage()) { result.unprocessableEntity(entityConfigValidationFailed(packageDeinition.getClass().getAnnotation(ConfigTag.class).value(), packageDeinition.getId(), e.getMessage())); } else if (e instanceof RulesViolationException || e instanceof SecretResolutionFailureException) { result.unprocessableEntity(saveFailedWithReason(e.getMessage())); } else { if (!result.hasMessage()) { LOGGER.error(e.getMessage(), e); result.internalServerError(saveFailedWithReason("An error occurred while saving the package config. Please check the logs for more information.")); } } } }
Source:
protected ValueBlock(CustomUIPane pane, Type type, String value, String fxml) { super(pane); this.value = new SimpleStringProperty(value); this.output = new OutputAnchor(this); this.type = type; this.loadFXML(fxml); outputSpace.setCenter(this.getOutputAnchor().get()); outputSpace.toFront(); this.valueType.setText("hoi"); }

Target:
protected ValueBlock(CustomUIPane pane, Type type, String value, String fxml) { super(pane); this.value = new SimpleStringProperty(value); this.output = new OutputAnchor(this); this.type = type; this.loadFXML(fxml); outputSpace.setCenter(this.getOutputAnchor().get()); outputSpace.toFront(); }
Source:
default Object getDetail(String attribute) { return getDetail(new ResultErrorBuilder.ErrorAttribute(attribute)); }

Target:
default Object getDetail(String attribute) { return getDetail(asAttribute(attribute)); }
Source:
public void shouldThrowForUnknownTopic() { final String unknownTopic = "unknownTopic"; final byte[] nullValue = null; testDriver = new TopologyTestDriver(new Topology(), config); try { pipeRecord(unknownTopic, new TestRecord<byte[], byte[]>(nullValue)); fail("Should have throw IllegalArgumentException"); } catch (final IllegalArgumentException exception) { assertEquals("Unknown topic: " + unknownTopic, exception.getMessage()); } }

Target:
public void shouldThrowForUnknownTopic() { final String unknownTopic = "unknownTopic"; final byte[] nullValue = null; testDriver = new TopologyTestDriver(new Topology(), config); assertThrows(IllegalArgumentException.class, () -> { pipeRecord(unknownTopic, new TestRecord<byte[], byte[]>(nullValue)); }); }
Source:
private CellEditor[] createTransitionViewerCellEditors(Table table) { BasicFBType fbType = getBasicFBType(); return new CellEditor[] { ComboBoxWidgetFactory.createComboBoxCellEditor(table, ECCContentAndLabelProvider.getInputEventNames(fbType).toArray(new String[0]), SWT.READ_ONLY), ComboBoxWidgetFactory.createComboBoxCellEditor(table, ECCContentAndLabelProvider.getInputEventNames(fbType).toArray(new String[0]), SWT.READ_ONLY), ComboBoxWidgetFactory.createComboBoxCellEditor(table, ECCContentAndLabelProvider.getTransitionConditionEventNames(fbType).toArray(new String[0]), SWT.READ_ONLY), new TextCellEditor(table), new TextCellEditor(table) }; }

Target:
private CellEditor[] createTransitionViewerCellEditors(Table table) { BasicFBType fbType = getBasicFBType(); return new CellEditor[] { null, null, ComboBoxWidgetFactory.createComboBoxCellEditor(table, ECCContentAndLabelProvider.getTransitionConditionEventNames(fbType).toArray(new String[0]), SWT.READ_ONLY), new TextCellEditor(table), new TextCellEditor(table) }; }
Source:
private void updateColors(Display display) { if (display == null) display = fComposite.getDisplay(); Color bgColor = null; if (fBackground != null) bgColor = getColor(display, fBackground); if (fAncestor != null) fAncestor.setBackgroundColor(bgColor); if (fLeft != null) fLeft.setBackgroundColor(bgColor); if (fRight != null) fRight.setBackgroundColor(bgColor); Color fgColor = null; if (fForeground != null) fgColor = getColor(display, fForeground); if (fAncestor != null) fAncestor.setForegroundColor(fgColor); if (fLeft != null) fLeft.setForegroundColor(fgColor); if (fRight != null) fRight.setForegroundColor(fgColor); ColorRegistry registry= JFaceResources.getColorRegistry(); RGB bg= getBackground(display); incomingPalette = new ColorPalette(bg, INCOMING_COLOR, new RGB(0, 0, 255)); outgoingPalette = new ColorPalette(bg, OUTGOING_COLOR, new RGB(0, 0, 0)); conflictPalette = new ColorPalette(bg, CONFLICTING_COLOR, new RGB(255, 0, 0)); additionPalette = new ColorPalette(bg, ADDITION_COLOR, new RGB(0, 255, 0)); deletionPalette = new ColorPalette(bg, DELETION_COLOR, new RGB(255, 0, 0)); editionPalette = outgoingPalette; RESOLVED= registry.getRGB(RESOLVED_COLOR); if (RESOLVED == null) RESOLVED= new RGB(0, 255, 0); updatePresentation(); }

Target:
private void updateColors(Display display) { if (display == null) display = fComposite.getDisplay(); Color bgColor = null; if (fBackground != null) bgColor = getColor(display, fBackground); if (fAncestor != null) fAncestor.setBackgroundColor(bgColor); if (fLeft != null) fLeft.setBackgroundColor(bgColor); if (fRight != null) fRight.setBackgroundColor(bgColor); Color fgColor = null; if (fForeground != null) fgColor = getColor(display, fForeground); if (fAncestor != null) fAncestor.setForegroundColor(fgColor); if (fLeft != null) fLeft.setForegroundColor(fgColor); if (fRight != null) fRight.setForegroundColor(fgColor); ColorRegistry registry= JFaceResources.getColorRegistry(); RGB bg= getBackground(display); incomingPalette = new ColorPalette(bg, INCOMING_COLOR, new RGB(0, 0, 255)); outgoingPalette = new ColorPalette(bg, OUTGOING_COLOR, new RGB(0, 0, 0)); conflictPalette = new ColorPalette(bg, CONFLICTING_COLOR, new RGB(255, 0, 0)); additionPalette = new ColorPalette(bg, ADDITION_COLOR, new RGB(0, 255, 0)); deletionPalette = new ColorPalette(bg, DELETION_COLOR, new RGB(255, 0, 0)); editionPalette = new ColorPalette(bg, EDITION_COLOR, new RGB(0, 0, 0)); RESOLVED= registry.getRGB(RESOLVED_COLOR); if (RESOLVED == null) RESOLVED= new RGB(0, 255, 0); updatePresentation(); }
Source:
public void testListHardwareHdds() throws InterruptedException { assertNodeAvailable(currentServer); Thread.sleep(60000); List<Hdd> hdds = serverApi().listHdds(currentServer.id()); for (Hdd hdd : hdds) { if (!hdd.isMain()) { currentHdd = hdd; break; } } assertNotNull(hdds); assertFalse(hdds.isEmpty()); Assert.assertTrue(hdds.size() > 0); }

Target:
public void testListHardwareHdds() throws InterruptedException { assertNodeAvailable(currentServer); List<Hdd> hdds = serverApi().listHdds(currentServer.id()); for (Hdd hdd : hdds) { if (!hdd.isMain()) { currentHdd = hdd; break; } } assertNotNull(hdds); assertFalse(hdds.isEmpty()); Assert.assertTrue(hdds.size() > 0); }
Source:
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { if(!fromUser) { return; } if (rating < 1.0f) { ratingBar.setRating(1.0f); } else if (rating > 1.0f && rating <= 2.0f) { ratingBar.setRating(2.0f); } else if (rating > 2.0f && rating <= 3.0f) { ratingBar.setRating(3.0f); } else if (rating > 3.0f && rating <= 4.0f) { ratingBar.setRating(4.0f); } else if (rating > 4.0f && rating <= 5.0f) { ratingBar.setRating(5.0f); } if (inputChangedListener != null) { Map<String, Object> dataMap = new HashMap<>(); dataMap.put(model.getTag(), ratingBar.getRating()); inputChangedListener.onContentChanged(dataMap, model); } }

Target:
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { if(!fromUser) { return; } if (rating < 1.0f) { ratingBar.setRating(1.0f); } else { float rounded = (float) Math.ceil(rating); ratingBar.setRating(rounded); } if (inputChangedListener != null) { Map<String, Object> dataMap = new HashMap<>(); dataMap.put(model.getTag(), ratingBar.getRating()); inputChangedListener.onContentChanged(dataMap, model); } }
Source:
private static boolean hasReachedAnyLocalQuorum(Map<String, Integer> totalNumberInDcs, Map<String, Integer> currentNumberInDcs) { for (String dcName : totalNumberInDcs.keySet()) { int totalNum = totalNumberInDcs.get(dcName); if (currentNumberInDcs.containsKey(dcName)) { int currentNum = currentNumberInDcs.get(dcName); if (totalNum != 1 && currentNum > totalNum / 2) { return true; } } } return false; }

Target:
static boolean hasReachedAnyLocalQuorum(Map<String, Integer> totalNumberInDcs, Map<String, Integer> currentNumberInDcs) { for (String dcName : totalNumberInDcs.keySet()) { int totalNum = totalNumberInDcs.get(dcName); if (currentNumberInDcs.containsKey(dcName)) { int currentNum = currentNumberInDcs.get(dcName); if (currentNum > totalNum / 2) { return true; } } } return false; }
Source:
public static String getPackageNameByNameSpaceURI(String nameSpaceURI) { int idx = nameSpaceURI.indexOf(':'); String scheme = ""; if (idx >= 0) { scheme = nameSpaceURI.substring(0, idx); if ("http".equalsIgnoreCase(scheme) || "urn".equalsIgnoreCase(scheme)) { nameSpaceURI = nameSpaceURI.substring(idx + 1); } } List<String> tokens = tokenize(nameSpaceURI, "/: "); if (tokens.isEmpty()) { return null; } if (tokens.size() > 1) { String lastToken = tokens.get(tokens.size() - 1); idx = lastToken.lastIndexOf('.'); if (idx > 0) { lastToken = lastToken.substring(0, idx); tokens.set(tokens.size() - 1, lastToken); } } String domain = tokens.get(0); idx = domain.indexOf(':'); if (idx >= 0) { domain = domain.substring(0, idx); } List<String> r = tokenize(domain, "urn".equals(scheme) ? ".-" : "."); if ("www".equalsIgnoreCase(r.get(0))) { r.remove(0); } Collections.reverse(r); tokens.addAll(1, r); tokens.remove(0); for (int i = 0; i < tokens.size(); i++) { String token = tokens.get(i); token = removeIllegalIdentifierChars(token); if (containsReservedKeywords(token)) { token = '_' + token; } tokens.set(i, token.toLowerCase()); } return String.join(".", tokens); }

Target:
public static String getPackageNameByNameSpaceURI(String nameSpaceURI) { int idx = nameSpaceURI.indexOf(':'); boolean urnScheme = false; if (idx >= 0) { final String scheme = nameSpaceURI.substring(0, idx); urnScheme = "urn".equalsIgnoreCase(scheme); if ("http".equalsIgnoreCase(scheme) || urnScheme) { nameSpaceURI = nameSpaceURI.substring(idx + (urnScheme ? 1 : 3)); } } List<String> tokens = tokenize(nameSpaceURI, "/:"); if (tokens.isEmpty()) { return null; } if (tokens.size() > 1) { String lastToken = tokens.get(tokens.size() - 1); idx = lastToken.lastIndexOf('.'); if (idx > 0) { lastToken = lastToken.substring(0, idx); tokens.set(tokens.size() - 1, lastToken); } } String domain = tokens.remove(0); List<String> r = tokenize(domain, urnScheme ? ".-" : "."); Collections.reverse(r); if ("www".equalsIgnoreCase(r.get(r.size() - 1))) { r.remove(r.size() - 1); } tokens.addAll(0, r); for (int i = 0; i < tokens.size(); i++) { String token = tokens.get(i); token = removeIllegalIdentifierChars(token); if (JavaUtils.isJavaKeyword(token)) { token = '_' + token; } tokens.set(i, token.toLowerCase()); } return String.join(".", tokens); }
Source:
public void testReplaceNicsMacSequenceInBootArgs() throws Exception { String bootArgs = "nic_macs=02:00:65:b5:00:03|7C02:00:4f:1b:00:15|7C1e:00:54:00:00:0f|7C02:00:35:fa:00:11|7C02:00:47:40:00:12"; doReturn(bootArgs).when(vmSpec).getBootArgs(); String oldMacSequence = "7C02:00:35:fa:00:11|7C02:00:47:40:00:12"; String newMacSequence = "7C02:00:0c:1d:00:1d|7C02:00:68:0f:00:1e"; String updatedBootArgs = _resource.replaceNicsMacSequenceInBootArgs(oldMacSequence, newMacSequence, vmSpec); String newBootArgs = "nic_macs=02:00:65:b5:00:03|7C02:00:4f:1b:00:15|7C1e:00:54:00:00:0f|7C02:00:0c:1d:00:1d|7C02:00:68:0f:00:1e"; assertEquals(newBootArgs, updatedBootArgs); }

Target:
public void testReplaceNicsMacSequenceInBootArgs() { String bootArgs = "nic_macs=02:00:65:b5:00:03|7C02:00:4f:1b:00:15|7C1e:00:54:00:00:0f|7C02:00:35:fa:00:11|7C02:00:47:40:00:12"; doReturn(bootArgs).when(vmSpec).getBootArgs(); String oldMacSequence = "7C02:00:35:fa:00:11|7C02:00:47:40:00:12"; String newMacSequence = "7C02:00:0c:1d:00:1d|7C02:00:68:0f:00:1e"; String updatedBootArgs = _resource.replaceNicsMacSequenceInBootArgs(oldMacSequence, newMacSequence, vmSpec); String newBootArgs = "nic_macs=02:00:65:b5:00:03|7C02:00:4f:1b:00:15|7C1e:00:54:00:00:0f|7C02:00:0c:1d:00:1d|7C02:00:68:0f:00:1e"; assertEquals(newBootArgs, updatedBootArgs); }
Source:
protected Operation(Builder builder) { operationId = checkNotNull(builder.operationId, "operationId"); status = checkNotNull(builder.status, "status"); type = checkNotNull(builder.type, "type"); direction = checkNotNull(builder.direction, "direction"); title = checkNotNull(builder.title, "title"); patternId = builder.patternId; amount = checkNotNull(builder.amount, "amount"); amountDue = builder.amountDue; fee = builder.fee; datetime = checkNotNull(builder.datetime, "datetime"); sender = builder.sender; recipient = builder.recipient; recipientType = builder.recipientType; message = builder.message; comment = builder.comment; codepro = builder.codepro; protectionCode = builder.protectionCode; expires = builder.expires; answerDatetime = builder.answerDatetime; label = builder.label; details = builder.details; repeatable = builder.repeatable; paymentParameters = Collections.unmodifiableMap(checkNotNull(builder.paymentParameters,"paymentParameters")); favorite = builder.favorite; digitalGoods = builder.digitalGoods; categories = Collections.unmodifiableList(builder.categories); format = builder.format; }

Target:
protected Operation(Builder builder) { operationId = checkNotNull(builder.operationId, "operationId"); status = checkNotNull(builder.status, "status"); type = checkNotNull(builder.type, "type"); direction = checkNotNull(builder.direction, "direction"); title = checkNotNull(builder.title, "title"); patternId = builder.patternId; amount = checkNotNull(builder.amount, "amount"); amountDue = builder.amountDue; fee = builder.fee; datetime = checkNotNull(builder.datetime, "datetime"); sender = builder.sender; recipient = builder.recipient; recipientType = builder.recipientType; message = builder.message; comment = builder.comment; codepro = builder.codepro; protectionCode = builder.protectionCode; expires = builder.expires; answerDatetime = builder.answerDatetime; label = builder.label; details = builder.details; repeatable = builder.repeatable; paymentParameters = Collections.unmodifiableMap(checkNotNull(builder.paymentParameters,"paymentParameters")); favorite = builder.favorite; digitalGoods = builder.digitalGoods; categories = Collections.unmodifiableList(checkNotNull(builder.categories, "categories")); format = builder.format; }
Source:
public static String join(Iterable<?> iterable, String separator) { StringBuilder sb = new StringBuilder(); boolean isFirst = true; for ( Object object : iterable ) { if ( !isFirst ) { sb.append( separator ); } else { isFirst = false; } sb.append( object ); } return sb.toString(); }

Target:
public static String join(Iterable<?> iterable, String separator) { if ( iterable == null ) { return null; } StringBuilder sb = new StringBuilder(); boolean isFirst = true; for ( Object object : iterable ) { if ( !isFirst ) { sb.append( separator ); } else { isFirst = false; } sb.append( object ); } return sb.toString(); }
Source:
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { List<IHyperlink> links = new ArrayList<IHyperlink>(); IFile file = getFile(); if(file == null) return null; StructuredModelWrapper smw = new StructuredModelWrapper(); smw.init(textViewer.getDocument()); try { Document xmlDocument = smw.getDocument(); if (xmlDocument == null) return null; Node n = findNodeForOffset(xmlDocument, region.getOffset()); if(n != null){ if(n.getNodeType() == Node.ELEMENT_NODE && n instanceof ElementImpl){ ITextRegion textRegion = ((ElementImpl)n).getStartStructuredDocumentRegion(); Region nodeRegion = new Region(textRegion.getStart(), textRegion.getLength()); String id = findID(n); if(id != null){ String url = "file:/ String shortName = file.getName()+"#"+id; links.add(new OpenWithBrowserSimHyperlink(textViewer.getDocument(), nodeRegion, shortName, url)); } } } if (links.size() == 0) return null; return (IHyperlink[])links.toArray(new IHyperlink[links.size()]); } finally { smw.dispose(); } }

Target:
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { List<IHyperlink> links = new ArrayList<IHyperlink>(); IFile file = getFile(); if(file == null) return null; StructuredModelWrapper smw = new StructuredModelWrapper(); smw.init(textViewer.getDocument()); try { Document xmlDocument = smw.getDocument(); if (xmlDocument == null) return null; Node n = findNodeForOffset(xmlDocument, region.getOffset()); if(n != null){ if(n.getNodeType() == Node.ELEMENT_NODE && n instanceof ElementImpl){ ITextRegion textRegion = ((ElementImpl)n).getStartStructuredDocumentRegion(); Region nodeRegion = new Region(textRegion.getStart(), textRegion.getLength()); String id = findID(n); if(id != null){ String url = file.getLocation().toFile().toURI()+"#"+id; String shortName = file.getName()+"#"+id; links.add(new OpenWithBrowserSimHyperlink(textViewer.getDocument(), nodeRegion, shortName, url)); links.add(new OpenWithBrowserHyperlink(textViewer.getDocument(), nodeRegion, shortName, url)); } } } if (links.size() == 0) return null; return (IHyperlink[])links.toArray(new IHyperlink[links.size()]); } finally { smw.dispose(); } }
Source:
public void fireEventListeners(final Event event) { final ArrayList<EventListener> listeners = new ArrayList<>(this.listeners); for (final EventListener listener : listeners) { try { listener.handleEvent(event); } catch (Exception e) { logger.warn("Error while calling handleEvent for: " + listener.getClass()); logger.warn(e.getMessage(), e); } } }

Target:
public void fireEventListeners(final Event event) { final ArrayList<EventListener> listeners = new ArrayList<>(this.listeners); for (final EventListener listener : listeners) { try { listener.handleEvent(event); } catch (RuntimeException e) { logger.warn("Error while calling handleEvent for: " + listener.getClass()); logger.warn(e.getMessage(), e); } } }
Source:
private static StatementTree getBody(StatementTree tree, int expectedSize) { StatementTree statement = tree; if (statement.is(Kind.BLOCK)) { BlockTree block = (BlockTree) statement; List<StatementTree> body = block.body(); statement = body.size() == expectedSize ? body.get(0) : null; } return statement; }

Target:
private static StatementTree getBody(StatementTree tree, int expectedSize) { if (tree.is(Kind.BLOCK)) { BlockTree block = (BlockTree) tree; List<StatementTree> body = block.body(); tree = body.size() == expectedSize ? body.get(0) : null; } return tree; }
Source:
default boolean isBrowser() { return ofNullable(getSessionDetail("browserName")) .map(browserName -> browserName.toString()) .orElse(null) != null; }

Target:
default boolean isBrowser() { return ofNullable(getSessionDetail("browserName")) .orElse(null) != null; }
Source:
private void onOpenEditor(VirtualFile file, EditorPartPresenter editor) { final List<Breakpoint> fileBreakpoints = breakpoints.get(file.getPath()); if (fileBreakpoints != null) { final BreakpointRenderer breakpointRenderer = getBreakpointRendererForEditor(editor); if (breakpointRenderer != null) { for (final Breakpoint breakpoint : fileBreakpoints) { int lineNumber = breakpoint.getLineNumber(); breakpointRenderer.addBreakpointMark(lineNumber, new LineChangeAction() { @Override public void onLineChange(VirtualFile file, int firstLine, int linesAdded, int linesRemoved) { BreakpointManagerImpl.this.onLineChange(file, firstLine, linesAdded, linesRemoved); } }); if (debuggerState == CONNECTED && breakpoint.isActive()) { breakpointRenderer.setBreakpointActive(lineNumber, true); } if (isCurrentBreakpoint(lineNumber)) { breakpointRenderer.setLineActive(lineNumber, true); } } } } }

Target:
private void onOpenEditor(VirtualFile file, EditorPartPresenter editor) { final List<Breakpoint> fileBreakpoints = breakpoints.get(file.getPath()); if (fileBreakpoints != null) { final BreakpointRenderer breakpointRenderer = getBreakpointRendererForEditor(editor); if (breakpointRenderer != null) { for (final Breakpoint breakpoint : fileBreakpoints) { readdBreakpointMark(breakpointRenderer, breakpoint); } } } }
Source:
public void onNext(T value) { R v = this.value; try { this.value = ObjectHelper.requireNonNull(reducer.apply(v, value), "The reducer returned a null value"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); d.dispose(); onError(ex); } }

Target:
public void onNext(T value) { R v = this.value; if (v != null) { try { this.value = ObjectHelper.requireNonNull(reducer.apply(v, value), "The reducer returned a null value"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); d.dispose(); onError(ex); } } }
Source:
public void testNestedNonTerminals1() throws Exception { Grammar.NonTerminalId ntistart = new Grammar.NonTerminalId("StartNT"); Grammar.StateId stistart = new Grammar.StateId("StartState"); Grammar.StateId stiend = new Grammar.StateId("EndState"); Grammar.NonTerminal nt1 = new Grammar.NonTerminal(ntistart, stistart, new Grammar.State.OrderingInfo(0), stiend, new Grammar.State.OrderingInfo(100)); Grammar.RegExState resx = new Grammar.RegExState(new Grammar.StateId("RegExStidx"), nt1, new Grammar.State.OrderingInfo(1), Pattern.compile("x")); Grammar.RegExState resy = new Grammar.RegExState(new Grammar.StateId("RegExStidy"), nt1, new Grammar.State.OrderingInfo(3), Pattern.compile("y")); Grammar.NonTerminalState nts = new Grammar.NonTerminalState(new Grammar.StateId("NT"), nt1, new Grammar.State.OrderingInfo(2), nt1, false); nt1.entryState.next.add(resx); nt1.entryState.next.add(nt1.exitState); resx.next.add(nts); nts.next.add(resy); resy.next.add(nt1.exitState); { Term result = new Parser(new ParseState("")).parse(nt1, 0); Term expected = amb(klist(amb(KList.EMPTY))); assertEquals("EmtpyString check: ", expected, result); } { Term result = new Parser(new ParseState("xxyy")).parse(nt1, 0); Term expected = amb(klist(amb(klist(Token.kAppOf("K", "x"), amb(klist(Token.kAppOf("K", "x"), amb(KList.EMPTY), Token.kAppOf("K", "y"))), Token.kAppOf("K", "y"))))); assertEquals("x^ny^n check: ", expected, result); } assertEquals("Expected Nullable NTs", 1, NullabilityCheck.getReachableNullableNT(nt1).size()); }

Target:
public void testNestedNonTerminals1() throws Exception { Grammar.NonTerminalId ntistart = new Grammar.NonTerminalId("StartNT"); Grammar.StateId stistart = new Grammar.StateId("StartState"); Grammar.StateId stiend = new Grammar.StateId("EndState"); Grammar.NonTerminal nt1 = new Grammar.NonTerminal(ntistart, stistart, new Grammar.State.OrderingInfo(0), stiend, new Grammar.State.OrderingInfo(100)); Grammar.RegExState resx = new Grammar.RegExState(new Grammar.StateId("RegExStidx"), nt1, new Grammar.State.OrderingInfo(1), Pattern.compile("x")); Grammar.RegExState resy = new Grammar.RegExState(new Grammar.StateId("RegExStidy"), nt1, new Grammar.State.OrderingInfo(3), Pattern.compile("y")); Grammar.NonTerminalState nts = new Grammar.NonTerminalState(new Grammar.StateId("NT"), nt1, new Grammar.State.OrderingInfo(2), nt1, false); nt1.entryState.next.add(resx); nt1.entryState.next.add(nt1.exitState); resx.next.add(nts); nts.next.add(resy); resy.next.add(nt1.exitState); { Term result = new Parser(new ParseState("")).parse(nt1, 0); Term expected = amb(klist(amb(KList.EMPTY))); Assert.assertEquals("EmtpyString check: ", expected, result); } { Term result = new Parser(new ParseState("xxyy")).parse(nt1, 0); Term expected = amb(klist(amb(klist(Token.kAppOf("K", "x"), amb(klist(Token.kAppOf("K", "x"), amb(KList.EMPTY), Token.kAppOf("K", "y"))), Token.kAppOf("K", "y"))))); Assert.assertEquals("x^ny^n check: ", expected, result); } Assert.assertEquals("Expected Nullable NTs", nt1, NullabilityCheck.getReachableNullableNT(nt1).iterator().next()); }
Source:
public void addPlayer(Player player) { if(player == null || this.players.contains(player)) { return; } this.players.add(player); calculateSkillLevel(); }

Target:
public int addPlayer(Player player) { if(player == null || this.players.contains(player)) { return -1; } if(this.players.size() == tournament.getMaxPlayers()) { return 0; } this.players.add(player); calculateSkillLevel(); return 1; }
Source:
public void testCancellationExceptionIsReturnedAsCause() throws InterruptedException, ExecutionException, TimeoutException { final Promise<Void> promise = new DefaultPromise<Void>(ImmediateEventExecutor.INSTANCE); promise.cancel(false); assertThat(promise.cause(), instanceOf(CancellationException.class)); }

Target:
public void testCancellationExceptionIsReturnedAsCause() throws InterruptedException, ExecutionException, TimeoutException { final Promise<Void> promise = new DefaultPromise<Void>(ImmediateEventExecutor.INSTANCE); assertTrue(promise.cancel(false)); assertThat(promise.cause(), instanceOf(CancellationException.class)); }
Source:
public ServletContainer getContainer() { if (container instanceof ServletContainer) return (ServletContainer) container; throw new RuntimeException("Not a ServletContainer. Use getServlet instead."); }

Target:
public Servlet getContainer() { return container; }
Source:
private void doAuthenticate(ExtMap input, ExtMap output) { if (!(input.get(Authn.InvokeKeys.USER).equals(adminUser) && input.get(Authn.InvokeKeys.CREDENTIALS) .equals(adminPassword))) { output.put(Authn.InvokeKeys.RESULT, Authn.AuthResult.CREDENTIALS_INVALID); } else { output.put(Authn.InvokeKeys.AUTH_RECORD, new ExtMap().mput( Authn.AuthRecord.PRINCIPAL, adminUser ).mput( Authn.AuthRecord.VALID_TO, new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ").format( DateUtils.addMinutes( new Date(System.currentTimeMillis()), Config.<Integer> getValue(ConfigValues.UserSessionTimeOutInterval) ) ) ) ); output.put(Authn.InvokeKeys.RESULT, Authn.AuthResult.SUCCESS); } }

Target:
private void doAuthenticate(ExtMap input, ExtMap output) { if (!(input.get(Authn.InvokeKeys.USER).equals(adminUser) && input.get(Authn.InvokeKeys.CREDENTIALS) .equals(adminPassword))) { output.put(Authn.InvokeKeys.RESULT, Authn.AuthResult.CREDENTIALS_INVALID); } else { output.put(Authn.InvokeKeys.AUTH_RECORD, new ExtMap().mput( Authn.AuthRecord.PRINCIPAL, adminUser ) ); output.put(Authn.InvokeKeys.RESULT, Authn.AuthResult.SUCCESS); } }
Source:
static void replaceOperationException(AtomicReference<Exception> operationExceptionRef, RouterException exception, ToIntFunction<RouterErrorCode> precedenceLevelFn) { RouterErrorCode routerErrorCode = exception.getErrorCode(); Exception currentException; Exception newException; do { currentException = operationExceptionRef.get(); if (currentException == null) { newException = exception; } else { int currentPrecedence = precedenceLevelFn.applyAsInt( currentException instanceof RouterException ? ((RouterException) currentException).getErrorCode() : RouterErrorCode.UnexpectedInternalError); newException = precedenceLevelFn.applyAsInt(routerErrorCode) < currentPrecedence ? exception : currentException; } } while (!operationExceptionRef.compareAndSet(currentException, newException)); }

Target:
static void replaceOperationException(AtomicReference<Exception> operationExceptionRef, RouterException exception, ToIntFunction<RouterErrorCode> precedenceLevelFn) { Exception currentException; Exception newException; do { currentException = operationExceptionRef.get(); if (currentException == null) { newException = exception; } else { int currentPrecedence = precedenceLevelFn.applyAsInt( currentException instanceof RouterException ? ((RouterException) currentException).getErrorCode() : RouterErrorCode.UnexpectedInternalError); newException = precedenceLevelFn.applyAsInt(exception.getErrorCode()) < currentPrecedence ? exception : currentException; } } while (!operationExceptionRef.compareAndSet(currentException, newException)); }