auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private FilterType buildPropertyIsFilterTypeForProperty( String propertyName, Object literal, PROPERTY_IS_OPS propertyIsType, boolean isCaseSensitive) { final String featurePropertyName = Optional.ofNullable(metacardMapper.getFeatureProperty(propertyName)).orElse(propertyName); if (isWfsFeatureProperty(featurePropertyName)) { final FeatureAttributeDescriptor featureAttributeDescriptor = (FeatureAttributeDescriptor) featureMetacardType.getAttributeDescriptor(featurePropertyName); if (featureAttributeDescriptor.isIndexed()) { final FilterType filter = new FilterType(); filter.setComparisonOps( createPropertyIsFilter( featureAttributeDescriptor.getPropertyName(), literal, propertyIsType, isCaseSensitive)); return filter; } else { throw new IllegalArgumentException( String.format(PROPERTY_NOT_QUERYABLE, featurePropertyName)); } } else { LOGGER.debug( "The property '{}' could not be mapped to a feature property of feature type '{}'.", propertyName, featureMetacardType.getFeatureType()); return null; } }

Target:
private FilterType buildPropertyIsFilterTypeForProperty( String propertyName, Object literal, PROPERTY_IS_OPS propertyIsType, boolean isCaseSensitive) { final String featurePropertyName = mapQueryPropertyToFeatureProperty(propertyName, this::isWfsFeatureProperty); if (featurePropertyName != null) { final FilterType filter = new FilterType(); filter.setComparisonOps( createPropertyIsFilter(featurePropertyName, literal, propertyIsType, isCaseSensitive)); return filter; } return null; }
Source:
private HashMap<String, String> getRequestHeaders() { HashMap<String, String> headers = new HashMap<>(); headers.put("Accept", "application/json"); return headers; }

Target:
private Map<String, String> getRequestHeaders() { final Map<String, String> headers = new HashMap<>(); headers.put("Accept", "application/json"); return headers; }
Source:
private void verifyPartitionedBucketedTable(HiveStorageFormat storageFormat, String tableName) { TableMetadata tableMetadata = getTableMetadata(catalog, TPCH_SCHEMA, tableName); assertEquals(tableMetadata.getMetadata().getProperties().get(STORAGE_FORMAT_PROPERTY), storageFormat); assertEquals(tableMetadata.getMetadata().getProperties().get(PARTITIONED_BY_PROPERTY), ImmutableList.of("orderstatus")); assertEquals(tableMetadata.getMetadata().getProperties().get(BUCKETED_BY_PROPERTY), ImmutableList.of("custkey", "custkey2")); assertEquals(tableMetadata.getMetadata().getProperties().get(BUCKET_COUNT_PROPERTY), 11); List<?> partitions = getPartitions(tableName); assertEquals(partitions.size(), 3); assertQuery("SELECT * from " + tableName, "SELECT custkey, custkey, comment, orderstatus FROM orders"); for (int i = 1; i <= 30; i++) { assertQuery( format("SELECT * from " + tableName + " where custkey = %d and custkey2 = %d", i, i), format("SELECT custkey, custkey, comment, orderstatus FROM orders where custkey = %d", i)); } assertThatThrownBy(() -> assertUpdate("INSERT INTO " + tableName + " VALUES (1, 1, 'comment', 'O')", 1)) .hasMessage(getExpectedErrorMessageForInsertExistingBucketedTable( HiveSessionProperties.getInsertExistingPartitionsBehavior(getSession().toConnectorSession(tableMetadata.getConnectorId())), "orderstatus=O")); }

Target:
private void verifyPartitionedBucketedTable(HiveStorageFormat storageFormat, String tableName) { TableMetadata tableMetadata = getTableMetadata(catalog, TPCH_SCHEMA, tableName); assertEquals(tableMetadata.getMetadata().getProperties().get(STORAGE_FORMAT_PROPERTY), storageFormat); assertEquals(tableMetadata.getMetadata().getProperties().get(PARTITIONED_BY_PROPERTY), ImmutableList.of("orderstatus")); assertEquals(tableMetadata.getMetadata().getProperties().get(BUCKETED_BY_PROPERTY), ImmutableList.of("custkey", "custkey2")); assertEquals(tableMetadata.getMetadata().getProperties().get(BUCKET_COUNT_PROPERTY), 11); List<?> partitions = getPartitions(tableName); assertEquals(partitions.size(), 3); assertQuery("SELECT * from " + tableName, "SELECT custkey, custkey, comment, orderstatus FROM orders"); for (int i = 1; i <= 30; i++) { assertQuery( format("SELECT * from " + tableName + " where custkey = %d and custkey2 = %d", i, i), format("SELECT custkey, custkey, comment, orderstatus FROM orders where custkey = %d", i)); } assertThatThrownBy(() -> assertUpdate("INSERT INTO " + tableName + " VALUES (1, 1, 'comment', 'O')", 1)) .hasMessage(getExpectedErrorMessageForInsertExistingBucketedTable( getInsertExistingPartitionsBehavior(getConnectorSession(getSession())), "orderstatus=O")); }
Source:
public void testThrowError() throws Exception { Error error = new Error("Transaction throws!"); Mockito.when(c.getAutoCommit()).thenReturn(true); Mockito.when(h.getConnection()).thenReturn(c); try { new LocalTransactionHandler().inTransaction(h, x -> { throw error; }); } catch (Throwable throwable) { assertThat(throwable).isSameAs(error); } }

Target:
public void testThrowError() throws Exception { Error error = new Error("Transaction throws!"); Mockito.when(c.getAutoCommit()).thenReturn(true); Mockito.when(h.getConnection()).thenReturn(c); assertThatThrownBy(() -> new LocalTransactionHandler().inTransaction(h, x -> { throw error; })) .isSameAs(error); }
Source:
public Object getCaptionValue() { if (captionValue != null) { return captionValue; } return getKey(); }

Target:
public Object getCaptionValue() { if (captionValue != null) { return captionValue; } Object name = getPropertyValue(Property.NAME.name); return name != null ? name : key; }
Source:
public static void start(final int port) { new Thread(new Runnable() { @Override public void run() { ServerSocket serverSocket = null; Socket client = null; try { serverSocket = new ServerSocket(port); while (true) { client = serverSocket.accept(); PrintWriter out = new PrintWriter(client.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); KnockKnockProtocol kkp = new KnockKnockProtocol(); String inputLine, outputLine; while ((inputLine = in.readLine()) != null) { outputLine = kkp.processInput(inputLine); out.print(outputLine); out.flush(); if (outputLine.equals("Bye.")) break; } } } catch (IOException e) { e.printStackTrace(); } finally { if (serverSocket != null) try { serverSocket.close(); } catch (IOException e) } } }).start(); }

Target:
public static void start(final int port) { new Thread(new Runnable() { @Override public void run() { ServerSocket serverSocket = null; Socket client = null; try { serverSocket = new ServerSocket(port); KnockKnockProtocol kkp = new KnockKnockProtocol(); while (true) { client = serverSocket.accept(); PrintWriter out = new PrintWriter(client.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); String inputLine, outputLine; while ((inputLine = in.readLine()) != null) { outputLine = kkp.processInput(inputLine); out.print(outputLine); out.flush(); if (outputLine.equals("Bye.")) break; } } } catch (IOException e) { e.printStackTrace(); } finally { if (serverSocket != null) try { serverSocket.close(); } catch (IOException e) } } }).start(); }
Source:
private IResource[] getSelectedResources(IStructuredSelection selection) { Set<IResource> result = new HashSet<IResource>(); for (Object o : selection.toList()) { IResource resource = (IResource) getAdapter(o, IResource.class); if (resource != null) { result.add(resource); } else { extractResourcesFromMapping(result, o); } } return result.toArray(new IResource[result.size()]); }

Target:
private IResource[] getSelectedResources(IStructuredSelection selection) { Set<IResource> result = new HashSet<IResource>(); for (Object o : selection.toList()) { IResource resource = (IResource) getAdapter(o, IResource.class); if (resource != null) result.add(resource); else extractResourcesFromMapping(result, o); } return result.toArray(new IResource[result.size()]); }
Source:
public List<EmailWrapper> generateFeedbackSessionReminderEmails( FeedbackSessionAttributes session, List<StudentAttributes> students, List<InstructorAttributes> instructorsToRemind, InstructorAttributes instructorToNotify) { CourseAttributes course = coursesLogic.getCourse(session.getCourseId()); String template = EmailTemplates.USER_FEEDBACK_SESSION.replace("${status}", FEEDBACK_STATUS_SESSION_OPEN); String additionalContactInformation = HTML_NO_ACTION_REQUIRED + getAdditionalContactInformationFragment(course); List<InstructorAttributes> instructorToNotifyAsList = new ArrayList<InstructorAttributes>(); instructorToNotifyAsList.add(instructorToNotify); List<EmailWrapper> emails = generateFeedbackSessionEmailBasesForInstructorReminders(course, session, instructorsToRemind, template, EmailType.FEEDBACK_SESSION_REMINDER.getSubject()); emails.addAll(generateFeedbackSessionEmailBases(course, session, students, instructorToNotifyAsList, template, EmailType.FEEDBACK_SESSION_REMINDER.getSubject(), FEEDBACK_ACTION_SUBMIT, additionalContactInformation)); return emails; }

Target:
public List<EmailWrapper> generateFeedbackSessionReminderEmails( FeedbackSessionAttributes session, List<StudentAttributes> students, List<InstructorAttributes> instructorsToRemind, InstructorAttributes instructorToNotify) { CourseAttributes course = coursesLogic.getCourse(session.getCourseId()); String template = EmailTemplates.USER_FEEDBACK_SESSION.replace("${status}", FEEDBACK_STATUS_SESSION_OPEN); String additionalContactInformation = HTML_NO_ACTION_REQUIRED + getAdditionalContactInformationFragment(course); List<InstructorAttributes> instructorToNotifyAsList = new ArrayList<>(); instructorToNotifyAsList.add(instructorToNotify); List<EmailWrapper> emails = generateFeedbackSessionEmailBasesForInstructorReminders(course, session, instructorsToRemind, template, EmailType.FEEDBACK_SESSION_REMINDER.getSubject()); emails.addAll(generateFeedbackSessionEmailBases(course, session, students, instructorToNotifyAsList, template, EmailType.FEEDBACK_SESSION_REMINDER.getSubject(), FEEDBACK_ACTION_SUBMIT, additionalContactInformation)); return emails; }
Source:
private static String deleteLineBreak(String postdata) { String repl = ""; if (postdata != null) { Matcher m = deleteLinePattern.matcher(postdata); repl = m.replaceAll(""); } return repl; }

Target:
private static String deleteLineBreak(String postdata) { Matcher m = deleteLinePattern.matcher(postdata); return m.replaceAll(""); }
Source:
protected void migrateComments(CoreSession session, RelationManager relationManager, CommentServiceConfig config, Statement statement) { Map<String, Object> ctxMap = Collections.singletonMap(ResourceAdapter.CORE_SESSION_CONTEXT_KEY, session); QNameResourceImpl object = (QNameResourceImpl) statement.getObject(); DocumentModel parent = (DocumentModel) relationManager.getResourceRepresentation(config.documentNamespace, object, ctxMap); QNameResourceImpl subject = (QNameResourceImpl) statement.getSubject(); DocumentModel comment = (DocumentModel) relationManager.getResourceRepresentation(config.commentNamespace, subject, ctxMap); comment.setPropertyValue(COMMENT_PARENT_ID, parent.getId()); comment.setPropertyValue(COMMENT_ANCESTOR_IDS, new ArrayList<>(Collections.singletonList(parent.getId()))); session.saveDocument(comment); Graph graph = relationManager.getGraph(config.graphName, session); graph.remove(statement); }

Target:
protected void migrateComments(CoreSession session, RelationManager relationManager, CommentServiceConfig config, Statement statement) { Map<String, Object> ctxMap = Collections.singletonMap(ResourceAdapter.CORE_SESSION_CONTEXT_KEY, session); QNameResourceImpl object = (QNameResourceImpl) statement.getObject(); DocumentModel parent = (DocumentModel) relationManager.getResourceRepresentation(config.documentNamespace, object, ctxMap); QNameResourceImpl subject = (QNameResourceImpl) statement.getSubject(); DocumentModel comment = (DocumentModel) relationManager.getResourceRepresentation(config.commentNamespace, subject, ctxMap); comment.setPropertyValue(COMMENT_PARENT_ID, parent.getId()); session.saveDocument(comment); Graph graph = relationManager.getGraph(config.graphName, session); graph.remove(statement); }
Source:
public boolean onPrepareOptionsMenu(final Menu menu) { mSyncbutton = menu.findItem(R.id.syncbutton); mAddPatientMenuItem = menu.findItem(R.id.actionAddPatients); MenuItem logoutMenuItem = menu.findItem(R.id.actionLogout); if (logoutMenuItem != null) { logoutMenuItem.setTitle(getString(R.string.action_logout) + " " + mOpenMRS.getUsername()); } if(mSyncbutton !=null) { final Boolean syncState = NetworkUtils.isOnline(); if (mAddPatientMenuItem != null){ enableAddPatient(syncState); } setSyncButtonState(syncState); } return true; }

Target:
public boolean onPrepareOptionsMenu(final Menu menu) { mSyncbutton = menu.findItem(R.id.syncbutton); MenuItem logoutMenuItem = menu.findItem(R.id.actionLogout); if (logoutMenuItem != null) { logoutMenuItem.setTitle(getString(R.string.action_logout) + " " + mOpenMRS.getUsername()); } if(mSyncbutton !=null) { final Boolean syncState = NetworkUtils.isOnline(); setSyncButtonState(syncState); } return true; }
Source:
public Ds3Request toDs3Request() { Ds3Request ds3request = new Ds3Request( name, request.getHttpVerb(), classification, request.getBucketRequirement(), request.getObjectRequirement(), toDs3ResponseCodes(), toDs3Params(request.getOptionalQueryParams()), toDs3Params(request.getRequiredQueryParams())); return ds3request; }

Target:
public Ds3Request toDs3Request() { final Ds3Request ds3request = new Ds3Request( name, request.getHttpVerb(), classification, request.getBucketRequirement(), request.getObjectRequirement(), toDs3ResponseCodes(), toDs3Params(request.getOptionalQueryParams()), toDs3Params(request.getRequiredQueryParams())); return ds3request; }
Source:
public static void pushExportBuffer( int partitionId, String signature, long uso, long bufferPtr, ByteBuffer buffer, boolean sync) { if (bufferPtr != 0) DBBPool.registerUnsafeMemory(bufferPtr); ExportManager instance = instance(); try { ExportGeneration generation = instance.m_generation.get(); if (generation == null) { if (buffer != null) { DBBPool.wrapBB(buffer).discard(); } return; } generation.pushExportBuffer(partitionId, signature, uso, buffer, sync); } catch (Exception e) { exportLog.error("Error pushing export buffer", e); } finally { } }

Target:
public static void pushExportBuffer( int partitionId, String signature, long uso, long bufferPtr, ByteBuffer buffer, boolean sync) { if (bufferPtr != 0) DBBPool.registerUnsafeMemory(bufferPtr); ExportManager instance = instance(); try { ExportGeneration generation = instance.m_generation.get(); if (generation == null) { if (buffer != null) { DBBPool.wrapBB(buffer).discard(); } return; } generation.pushExportBuffer(partitionId, signature, uso, buffer, sync); } catch (Exception e) { exportLog.error("Error pushing export buffer", e); } }
Source:
protected RedirectAction retrieveRedirectAction(final WebContext context) { return redirector.redirect(context); }

Target:
protected RedirectAction retrieveRedirectAction(final WebContext context) throws RequiresHttpAction { return redirectActionBuilder.redirect(context); }
Source:
public ImageTemplate buildImageTemplateFromNode(String name, String id) { name = name.toLowerCase(); return new ImageTemplateBuilder.CloneImageTemplateBuilder().nodeId(id).name(name).build(); }

Target:
public ImageTemplate buildImageTemplateFromNode(String name, String id) { String imageName = name.toLowerCase(); return new ImageTemplateBuilder.CloneImageTemplateBuilder().nodeId(id).name(imageName).build(); }
Source:
public void testGetFromChangeId() throws Exception { ITask task = createAndSynchronizeQuery(true); AbstractRepositoryConnector connector = TasksUi.getRepositoryConnector(repository.getConnectorKind()); GerritClient client = ((GerritConnector) connector).getClient(repository); Project.NameKey project = client.getChange(task.getTaskId(), null).getChangeDetail().getChange().getProject(); if (GerritVersion.isVersion28OrLater(client.getVersion())) { ((GerritClient28) client).clearCachedBranches(project); assertNull(client.getCachedBranches(project)); } TaskData taskData = connector.getTaskData(repository, task.getTaskId(), new NullProgressMonitor()); assertEquals(task.getTaskId(), taskData.getTaskId()); if (GerritVersion.isVersion28OrLater(client.getVersion())) { assertNotNull(client.getCachedBranches(project)); } TaskAttribute changeIdAttribute = taskData.getRoot().getAttribute( GerritTaskSchema.getDefault().CHANGE_ID.getKey()); assertNotNull(changeIdAttribute); assertThat(task.getTaskId(), not(equalTo(changeIdAttribute.getValue()))); TaskData taskDataFromChangeId = connector.getTaskData(repository, changeIdAttribute.getValue(), new NullProgressMonitor()); assertEquals(task.getTaskId(), taskDataFromChangeId.getTaskId()); assertEquals(taskData.getRoot().toString(), taskDataFromChangeId.getRoot().toString()); }

Target:
public void testGetFromChangeId() throws Exception { ITask task = createAndSynchronizeQuery(true); AbstractRepositoryConnector connector = TasksUi.getRepositoryConnector(repository.getConnectorKind()); GerritClient client = ((GerritConnector) connector).getClient(repository); Project.NameKey project = new Project.NameKey(taskDataManager.getTaskData(task) .getRoot() .getMappedAttribute(TaskAttribute.PRODUCT) .getValue()); if (GerritVersion.isVersion28OrLater(client.getVersion())) { ((GerritClient28) client).clearCachedBranches(project); assertNull(client.getCachedBranches(project)); } TaskData taskData = connector.getTaskData(repository, task.getTaskId(), new NullProgressMonitor()); assertEquals(task.getTaskId(), taskData.getTaskId()); if (GerritVersion.isVersion28OrLater(client.getVersion())) { assertNotNull(client.getCachedBranches(project)); } TaskAttribute changeIdAttribute = taskData.getRoot().getAttribute( GerritTaskSchema.getDefault().CHANGE_ID.getKey()); assertNotNull(changeIdAttribute); assertThat(task.getTaskId(), not(equalTo(changeIdAttribute.getValue()))); TaskData taskDataFromChangeId = connector.getTaskData(repository, changeIdAttribute.getValue(), new NullProgressMonitor()); assertEquals(task.getTaskId(), taskDataFromChangeId.getTaskId()); assertEquals(taskData.getRoot().toString(), taskDataFromChangeId.getRoot().toString()); }
Source:
public void testPinning() { assertThat(OperationCode.PUT.shouldBePinned(), is(false)); for (OperationCode operationCode : OperationCode.values()) { if (OperationCode.PUT != operationCode) { assertThat(operationCode.shouldBePinned(), is(true)); } } }

Target:
public void testPinning() { assertThat(OperationCode.PUT.shouldBePinned(), is(false)); Arrays.stream(OperationCode.values()) .filter(operationCode -> operationCode != OperationCode.PUT) .forEach((operationCode -> assertThat(operationCode + " must be pinned", operationCode.shouldBePinned(), is(true)))); }
Source:
private void loadAllCertificates() { Path certPath = securityConfig.getCertificateLocation(); if (Files.exists(certPath) && Files.isDirectory(certPath) && certPath.toFile().listFiles() != null) { getLogger().info("Loading certificate from location:{}.", certPath); for (File file : certPath.toFile().listFiles()) { if (file.isFile()) { CertificateCodec certificateCodec = new CertificateCodec(securityConfig); try { X509CertificateHolder x509CertificateHolder = certificateCodec .readCertificate(certPath, file.getName()); X509Certificate cert = CertificateCodec.getX509Certificate(x509CertificateHolder); certificateMap.putIfAbsent(cert.getSerialNumber().toString(), cert); getLogger().info("Added certificate from file:{}.", file.getAbsolutePath()); } catch (java.security.cert.CertificateException | IOException e) { getLogger().error("Error reading certificate.", e); } } } } }

Target:
private void loadAllCertificates() { Path certPath = securityConfig.getCertificateLocation(); if (Files.exists(certPath) && Files.isDirectory(certPath)) { getLogger().info("Loading certificate from location:{}.", certPath); File[] certFiles = certPath.toFile().listFiles(); if (certFiles != null) { CertificateCodec certificateCodec = new CertificateCodec(securityConfig); for (File file : certFiles) { if (file.isFile()) { try { X509CertificateHolder x509CertificateHolder = certificateCodec .readCertificate(certPath, file.getName()); X509Certificate cert = CertificateCodec.getX509Certificate(x509CertificateHolder); certificateMap.putIfAbsent(cert.getSerialNumber().toString(), cert); getLogger().info("Added certificate from file:{}.", file.getAbsolutePath()); } catch (java.security.cert.CertificateException | IOException e) { getLogger().error("Error reading certificate from file:{}.", file.getAbsolutePath(), e); } } } } } }
Source:
public void transactionCancelledTest() { String label = "testwork"; Model model = job.getWritableModel(); Bag depBag = model.createBag(depositPid.getRepositoryPath()); PID workPid = repository.mintContentPid(); Bag workBag = model.createBag(workPid.getRepositoryPath()); workBag.addProperty(RDF.type, Cdr.FileObject); workBag.addProperty(CdrDeposit.label, label); PID mainPid = addFileObject(workBag, FILE1_LOC, FILE1_MIMETYPE, FILE1_SHA1); depBag.add(workBag); workBag.asResource().addProperty(Cdr.primaryObject, model.getResource(mainPid.getRepositoryPath())); job.closeModel(); job.run(); }

Target:
public void transactionCancelledTest() { String label = "testwork"; Model model = job.getWritableModel(); Bag depBag = model.createBag(depositPid.getRepositoryPath()); PID workPid = repository.mintContentPid(); Bag workBag = model.createBag(workPid.getRepositoryPath()); workBag.addProperty(RDF.type, Cdr.FileObject); workBag.addProperty(CdrDeposit.label, label); PID mainPid = addFileObject(workBag, FILE1_LOC, FILE1_MIMETYPE, FILE1_SHA1); depBag.add(workBag); workBag.asResource().addProperty(Cdr.primaryObject, model.getResource(mainPid.getRepositoryPath())); job.closeModel(); try { job.run(); } finally { assertFalse(FedoraTransaction.hasTxId()); assertFalse(FedoraTransaction.isStillAlive()); assertFalse(repository.objectExists(workPid)); } }
Source:
private static AbbreviatedObjectId id(DiffEntry de) { return (de.changeType == ChangeType.DELETE ? de.oldId : de.newId); }

Target:
private static AbbreviatedObjectId id(DiffEntry de) { return de.changeType == ChangeType.DELETE ? de.oldId : de.newId; }
Source:
private void exceptionHandler(Exception exception) { if (exception.getClass().getName().equals("org.jabref.logic.importer.FetcherException")) { if (exception.getMessage().equals("A network error occurred")) { dialogService.showWarningDialogAndWait(Localization.lang("An error occurred"), Localization.lang(exception.getMessage() + ". You have no rights to access resources")); } } else { dialogService.showWarningDialogAndWait(Localization.lang("An error occurred"), Localization.lang(exception.getMessage())); } }

Target:
private void exceptionHandler(Exception exception) { if (exception instanceof FetcherException) { if (exception.getMessage().equals("A network error occurred")) { dialogService.showWarningDialogAndWait(Localization.lang("An error occurred"), Localization.lang(exception.getMessage() + ". You have no rights to access resources.")); } } else { dialogService.showWarningDialogAndWait(Localization.lang("An error occurred"), Localization.lang(exception.getMessage())); } }
Source:
private Optional<Long> getStartForFailuresInBuckets( long now, List<Long> recentFailures, long bucketSizeMillis, int numBuckets, double percentThreshold, int minBucketIndexPercent ) { long thresholdFailTimeMillis = now - (bucketSizeMillis * numBuckets); long[] bucketThresholds = new long[numBuckets]; for (int i = 0; i < numBuckets; i++) { bucketThresholds[i] = thresholdFailTimeMillis + i * bucketSizeMillis; } int bucketsWithFailure = 0; int maxBucketIndex = -1; for (int i = 0; i < bucketThresholds.length; i++) { for (long t : recentFailures) { if ( t > bucketThresholds[i] && (i == bucketThresholds.length - 1 || t <= bucketThresholds[i + 1]) ) { bucketsWithFailure++; maxBucketIndex = i; break; } } } if ((double) bucketsWithFailure / numBuckets > percentThreshold) { boolean failuresAreRecentEnough = maxBucketIndex >= 0 && maxBucketIndex * 100 / numBuckets > minBucketIndexPercent; if (failuresAreRecentEnough) { return recentFailures.stream().min(Comparator.comparingLong(Long::longValue)); } } return Optional.empty(); }

Target:
private Optional<Long> getStartForFailuresInBuckets( long now, List<Long> recentFailures, long bucketSizeMillis, int numBuckets, double percentThreshold, int minBucketIndexPercent ) { long thresholdFailTimeMillis = now - (bucketSizeMillis * numBuckets); List<Long> bucketThresholds = IntStream .range(0, numBuckets - 1) .mapToLong(i -> thresholdFailTimeMillis + i * bucketSizeMillis) .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); int bucketsWithFailure = 0; int maxBucketIndex = -1; for (int i = 0; i < bucketThresholds.size(); i++) { for (long t : recentFailures) { if ( t > bucketThresholds.get(i) && (i == bucketThresholds.size() - 1 || t <= bucketThresholds.get(i + 1)) ) { bucketsWithFailure++; maxBucketIndex = i; break; } } } if ((double) bucketsWithFailure / numBuckets > percentThreshold) { boolean failuresAreRecentEnough = maxBucketIndex >= 0 && maxBucketIndex * 100 / numBuckets > minBucketIndexPercent; if (failuresAreRecentEnough) { return recentFailures.stream().min(Comparator.comparingLong(Long::longValue)); } } return Optional.empty(); }
Source:
public BoldStylerProvider getBoldStylerProvider() { return fBoldStylerProvider; }

Target:
BoldStylerProvider getBoldStylerProvider() { return fBoldStylerProvider; }
Source:
public PhysicalDevice getPhysicalDevice() { return physicalDevice; }

Target:
public PhysicalDevice getPhysicalDevice() { return this.physicalDevice; }
Source:
private boolean maybeOverridePartitionDiscovery(String key, String value, boolean override) { boolean overridden = false; String userValue = props.getProperty(key); if (override) { LOG.warn( String.format( "Property %s is provided but will be overridden from %s to %s", key, userValue, value)); props.setProperty(key, value); overridden = true; } else { if (userValue != null) { } else { props.setProperty(key, KafkaSourceOptions.PARTITION_DISCOVERY_INTERVAL_MS .defaultValue() .toString()); } } return overridden; }

Target:
private boolean maybeOverridePartitionDiscovery(String key, String value, boolean override) { boolean overridden = false; String userValue = props.getProperty(key); if (override) { props.setProperty(key, value); overridden = true; } else { if (userValue == null) { props.setProperty(key, KafkaSourceOptions.PARTITION_DISCOVERY_INTERVAL_MS .defaultValue() .toString()); } } return overridden; }
Source:
private void printAllReferredServices(StringBuilder buf, boolean detail) { boolean printHeader = true; for (ConsumerModel consumer : ApplicationModel.allConsumerModels()) { if (printHeader) { buf.append("CONSUMER:\r\n"); printHeader = false; } buf.append(consumer.getServiceName()); if (detail) { buf.append(" -> "); buf.append(" addresses: "); buf.append(getConsumerAddressNum(consumer.getServiceName())); } } }

Target:
private void printAllReferredServices(StringBuilder buf, boolean detail) { if (!ApplicationModel.allConsumerModels().isEmpty()) { buf.append("CONSUMER:\r\n"); } for (ConsumerModel consumer : ApplicationModel.allConsumerModels()) { buf.append(consumer.getServiceName()); if (detail) { buf.append(" -> "); buf.append(" addresses: "); buf.append(getConsumerAddressNum(consumer.getServiceName())); } } }
Source:
public void updateParticipant(Study study, Set<Roles> callerRoles, StudyParticipant participant) { checkNotNull(study); checkNotNull(callerRoles); checkNotNull(participant); Validate.entityThrowingException(new StudyParticipantValidator(externalIdService, study, false), participant); Account account = getAccountThrowingException(study, participant.getId()); account = accountDao.getAccount(AccountId.forId(study.getIdentifier(), account.getId())); if (account.getExternalId() == null) { account.setExternalId(participant.getExternalId()); } updateAccountAndRoles(study, callerRoles, account, participant); if (participant.getStatus() != null) { if (callerRoles.contains(Roles.ADMIN) || callerRoles.contains(Roles.WORKER)) { account.setStatus(participant.getStatus()); } } accountDao.updateAccount(account, false); externalIdService.assignExternalId(study, account.getExternalId(), account.getHealthCode()); }

Target:
public void updateParticipant(Study study, Set<Roles> callerRoles, StudyParticipant participant) { checkNotNull(study); checkNotNull(callerRoles); checkNotNull(participant); Validate.entityThrowingException(new StudyParticipantValidator(externalIdService, study, false), participant); Account account = getAccountThrowingException(study, participant.getId()); account = accountDao.getAccount(AccountId.forId(study.getIdentifier(), account.getId())); boolean assigningExternalId = (account.getExternalId() == null && participant.getExternalId() != null); if (assigningExternalId) { account.setExternalId(participant.getExternalId()); } updateAccountAndRoles(study, callerRoles, account, participant); if (participant.getStatus() != null) { if (callerRoles.contains(Roles.ADMIN) || callerRoles.contains(Roles.WORKER)) { account.setStatus(participant.getStatus()); } } accountDao.updateAccount(account, false); if (assigningExternalId) { externalIdService.assignExternalId(study, account.getExternalId(), account.getHealthCode()); } }
Source:
public static List<CompressedDecklistInfo> decToDecklist(File decFile) { try { BufferedReader reader = new BufferedReader(new FileReader(decFile)); List<CompressedDecklistInfo> deckList = new ArrayList<>(); String line; while ((line = reader.readLine()) != null) { if (Character.isDigit(line.charAt(0)) || line.startsWith("SB:")) { boolean isSideboard = false; int numberOf; String cardName = null; String setName = null; if (line.startsWith("SB:")) { isSideboard = true; line = line.substring(3).trim(); } int firstSpace = line.indexOf(' '); numberOf = Integer.valueOf(line.substring(0, firstSpace).trim()); line = line.substring(firstSpace).trim(); int bracketIndex = line.indexOf('['); if (bracketIndex >= 0) { int endBracket = line.indexOf(']'); setName = line.substring(bracketIndex + 1, line.indexOf(']')); if (bracketIndex > 0) { cardName = line.substring(0, bracketIndex).trim(); } else { cardName = line.substring(endBracket + 1).trim(); } } } } return deckList; } catch (FileNotFoundException fnf) { return null; } catch (IOException ioe) { return null; } }

Target:
public static List<CompressedDecklistInfo> decToDecklist(File decFile) { List<CompressedDecklistInfo> deckList = new ArrayList<>(); try { BufferedReader reader = new BufferedReader(new FileReader(decFile)); String line; while ((line = reader.readLine()) != null) { if (Character.isDigit(line.charAt(0)) || line.startsWith("SB:")) { boolean isSideboard = false; int numberOf; String cardName = null; String setName = null; if (line.startsWith("SB:")) { isSideboard = true; line = line.substring(3).trim(); } int firstSpace = line.indexOf(' '); numberOf = Integer.valueOf(line.substring(0, firstSpace).trim()); line = line.substring(firstSpace).trim(); int bracketIndex = line.indexOf('['); if (bracketIndex >= 0) { int endBracket = line.indexOf(']'); setName = line.substring(bracketIndex + 1, line.indexOf(']')); if (bracketIndex > 0) { cardName = line.substring(0, bracketIndex).trim(); } else { cardName = line.substring(endBracket + 1).trim(); } } try { deckList.add( new CompressedDecklistInfo( cardName, setName, false, numberOf, isSideboard ) ); } catch (InstantiationException ie) { } } } } catch (FileNotFoundException fnf) { return null; } catch (IOException ioe) { return null; } return deckList; }
Source:
public UfsJournal(URI location, Master master, long quietPeriodMs, Supplier<Set<JournalSink>> journalSinks) { this(location, master, master.getMasterContext().getUfsManager().getRoot().acquireUfsResource() .get(), quietPeriodMs, journalSinks); }

Target:
public UfsJournal(URI location, Master master, long quietPeriodMs, Supplier<Set<JournalSink>> journalSinks) { this(location, master, master.getMasterContext().getUfsManager().getJournal() .acquireUfsResource() .get(), quietPeriodMs, journalSinks); }
Source:
public void testCardResourceFields() throws HTTPError { Card card = createCreditableCard(); assertNotNull(card.address); assertNull(card.avs_postal_match); assertNull(card.avs_result); assertNull(card.avs_street_match); assertNotNull(card.bank_name); assertNotNull(card.can_credit); assertNotNull(card.can_debit); assertNotNull(card.category); assertNotNull(card.created_at); assertNull(card.cvv_match); assertNull(card.cvv_result); assertNotNull(card.expiration_month); assertNotNull(card.expiration_year); assertNotNull(card.fingerprint); assertNotNull(card.href); assertNotNull(card.id); assertNotNull(card.is_verified); assertNotNull(card.meta); assertNotNull(card.name); assertNotNull(card.number); assertNotNull(card.type); assertNotNull(card.updated_at); assertNotNull(card.card_holds); assertNull(card.customer); assertNotNull(card.debits); assertNotNull(card.disputes); assertNotNull(card.credits); }

Target:
public void testCardResourceFields() throws HTTPError { Card card = createCreditableCard(); Map<String, String> meta = new HashMap<String, String>(); meta.put("facebook", "0192837465"); card.meta = meta; card.save(); Map<String, Object> payload = personCustomerPayload(); Customer customer = new Customer(payload); customer.save(); card.associateToCustomer(customer); assertEquals(card.address.toString(), "{city=null, line2=null, " + "line1=null, state=null, postal_code=null, country_code=null}"); assertNull(card.avs_postal_match); assertNull(card.avs_result); assertNull(card.avs_street_match); assertEquals(card.bank_name, "WELLS FARGO BANK, N.A."); assertTrue(card.can_credit); assertTrue(card.can_debit); assertEquals(card.category, "other"); assertNotNull(card.created_at); assertNull(card.cvv_match); assertNull(card.cvv_result); assertEquals(card.expiration_month.intValue(), 5); assertEquals(card.expiration_year.intValue(), 2016); assertNotNull(card.fingerprint); assertTrue(card.href.contains("/cards/CC")); assertTrue(card.id.contains("CC")); assertTrue(card.is_verified); assertEquals(card.meta.get("facebook"), "0192837465"); assertEquals(card.name, "Johannes Bach"); assertEquals(card.number, "xxxxxxxxxxxx1118"); assertEquals(card.type, "debit"); assertNotNull(card.updated_at); assertEquals(card.customer.href, customer.href); assertTrue(card.disputes instanceof Dispute.Collection); assertTrue(card.card_holds instanceof CardHold.Collection); assertTrue(card.debits instanceof Debit.Collection); assertTrue(card.credits instanceof Credit.Collection); }
Source:
private void applyRasterFunction(Raster raster) { RasterFunction rasterFunction = RasterFunction.fromJson(getString(R.string.hillshade_simplified)); RasterFunctionArguments rasterFunctionArguments = rasterFunction.getArguments(); List<String> rasterName = rasterFunctionArguments.getRasterNames(); rasterFunctionArguments.setRaster(rasterName.get(0), raster); raster = new Raster(rasterFunction); RasterLayer hillshadeLayer = new RasterLayer(raster); map.getOperationalLayers().add(hillshadeLayer); }

Target:
private void applyRasterFunction(Raster raster) { RasterFunction rasterFuntionFromJson = RasterFunction.fromJson(getString(R.string.hillshade_simplified)); RasterFunctionArguments rasterFunctionArguments = rasterFuntionFromJson.getArguments(); List<String> rasterNames = rasterFunctionArguments.getRasterNames(); rasterFunctionArguments.setRaster(rasterNames.get(0), raster); raster = new Raster(rasterFuntionFromJson); RasterLayer hillshadeLayer = new RasterLayer(raster); mMapView.getMap().getOperationalLayers().add(hillshadeLayer); }
Source:
public ApiResponse handleApiView(String name, JSONObject params) throws ApiException { ApiResponse result; String contextId = null; switch (name) { case VIEW_GET_SCAN_PROGRESS: LOGGER.debug("Access control get scan progress called"); contextId = params.getString(PARAM_CONTEXT_ID); result = new ApiResponseElement( name, String.valueOf( extension.getScanProgress(Integer.parseInt(contextId)))); break; case VIEW_GET_SCAN_STATUS: LOGGER.debug("Access control get scan status called"); contextId = params.getString(PARAM_CONTEXT_ID); result = new ApiResponseElement( name, extension.getScanStatus(Integer.parseInt(contextId))); break; default: throw new ApiException(ApiException.Type.BAD_ACTION); } return result; }

Target:
public ApiResponse handleApiView(String name, JSONObject params) throws ApiException { ApiResponse result; int contextId; switch (name) { case VIEW_GET_SCAN_PROGRESS: LOGGER.debug("Access control get scan progress called"); contextId = ApiUtils.getContextByParamId(params, PARAM_CONTEXT_ID).getIndex(); String scanStatus; try { scanStatus = String.valueOf(extension.getScanProgress(contextId)); } catch (IllegalStateException ise) { throw new ApiException( ApiException.Type.DOES_NOT_EXIST, "Failed to obtain scan progress for contextId: " + contextId); } result = new ApiResponseElement(name, scanStatus); break; case VIEW_GET_SCAN_STATUS: LOGGER.debug("Access control get scan status called"); contextId = ApiUtils.getContextByParamId(params, PARAM_CONTEXT_ID).getIndex(); result = new ApiResponseElement(name, extension.getScanStatus(contextId)); break; default: throw new ApiException(ApiException.Type.BAD_VIEW); } return result; }
Source:
public GrpcBackedQueryMessage(QueryRequest queryRequest, Serializer messageSerializer, Serializer serializer) { this.query = queryRequest; this.serializedPayload = new LazyDeserializingObject<>(new GrpcSerializedObject(queryRequest.getPayload()), messageSerializer); this.serializedResponseType = new LazyDeserializingObject<>(new GrpcSerializedObject(queryRequest.getResponseType()), serializer); this.metaDataSupplier = new GrpcMetaData(queryRequest.getMetaDataMap(), messageSerializer); }

Target:
public GrpcBackedQueryMessage(QueryRequest queryRequest, Serializer messageSerializer, Serializer serializer) { this( queryRequest, new LazyDeserializingObject<>(new GrpcSerializedObject(queryRequest.getPayload()), messageSerializer), new LazyDeserializingObject<>(new GrpcSerializedObject(queryRequest.getResponseType()), serializer), new GrpcMetaData(queryRequest.getMetaDataMap(), messageSerializer) ); }
Source:
protected void write(ByteBuffer bb, InetSocketAddress remoteAddress) throws IOException { writeQueue.add(new WriteDataPair(remoteAddress, bb)); getSocketExecuter().startListening(this); }

Target:
protected void write(ByteBuffer bb, InetSocketAddress remoteAddress) throws IOException { writeQueue.add(new Pair<InetSocketAddress, ByteBuffer>(remoteAddress, bb)); getSocketExecuter().setUDPServerOperations(this, true); }
Source:
public void startTimer() { isTimerOn = true; Scheduler.get().scheduleFixedPeriod(new Scheduler.RepeatingCommand() { public boolean execute() { moveProductsUpward(); return isTimerOn; } }, 6000); }

Target:
public void startTimer() { isTimerOn = true; Scheduler.get().scheduleFixedPeriod(new Scheduler.RepeatingCommand() { public boolean execute() { moveProductsUpward(); return isTimerOn; } }, timerTopDownPeriod); }
Source:
public List<ComponentDto> selectComponentKeysHavingIssuesToMerge(DbSession dbSession, String mergeBranchUuid) { return mapper(dbSession).selectComponentKeysHavingIssuesToMerge(mergeBranchUuid); }

Target:
public List<KeyWithUuidDto> selectComponentKeysHavingIssuesToMerge(DbSession dbSession, String mergeBranchUuid) { return mapper(dbSession).selectComponentKeysHavingIssuesToMerge(mergeBranchUuid); }
Source:
@Test public void noTypeAdapterForQualifiedPlatformType() { Moshi moshi = new Moshi.Builder().build(); Field uppercaseStringField; try { uppercaseStringField = MoshiTest.class.getDeclaredField("uppercaseString"); } catch (NoSuchFieldException e) { throw new AssertionError(e); } try { moshi.adapter(uppercaseStringField.getGenericType(), Util.jsonAnnotations(uppercaseStringField)); fail(); } catch (IllegalArgumentException expected) { assertThat(expected).hasMessage("No JsonAdapter for class java.lang.String " + "annotated [@com.squareup.moshi.MoshiTest$Uppercase()]"); } }

Target:
@Test public void noTypeAdapterForQualifiedPlatformType() throws Exception { Moshi moshi = new Moshi.Builder().build(); Field uppercaseStringField = MoshiTest.class.getDeclaredField("uppercaseString"); try { moshi.adapter(uppercaseStringField.getGenericType(), Util.jsonAnnotations(uppercaseStringField)); fail(); } catch (IllegalArgumentException expected) { assertThat(expected).hasMessage("No JsonAdapter for class java.lang.String " + "annotated [@com.squareup.moshi.MoshiTest$Uppercase()]"); } }
Source:
public boolean isReferenceTo(PsiElement element) { if (!(element instanceof HaxeFile)) { final HaxeReference[] references = PsiTreeUtil.getChildrenOfType(this, HaxeReference.class); final boolean chain = references != null && references.length == 2; if (chain) return false; } final PsiElement resolve = element instanceof HaxeComponentName ? resolveToComponentName() : resolve(); boolean b = resolve instanceof HaxeNamedComponent; boolean b1 = (resolve instanceof HaxeComponentName || b) && resolve.getParent() instanceof HaxeClass; if (element instanceof HaxeFile && (b1 || resolve instanceof AbstractHaxePsiClass) ) { return element == resolve.getContainingFile(); } return resolve == element; }

Target:
public boolean isReferenceTo(PsiElement element) { if (!(element instanceof HaxeFile)) { final HaxeReference[] references = PsiTreeUtil.getChildrenOfType(this, HaxeReference.class); final boolean chain = references != null && references.length == 2; if (chain) return false; } final PsiElement resolve = element instanceof HaxeComponentName ? resolveToComponentName() : resolve(); if (element instanceof HaxeFile && resolve instanceof HaxeClass) { return element == resolve.getContainingFile(); } return resolve == element; }
Source:
public CapabilityResource parse(ConfigResource parent, IdString id) throws ResourceNotFoundException, Exception { return null; }

Target:
public CapabilityResource parse(ConfigResource parent, IdString id) throws ResourceNotFoundException { throw new ResourceNotFoundException(id); }
Source:
private static void processGenericSuperType(Map<Class<?>, Map<TypeVariable<?>, TypeVariable<?>>> allBindings, Map<TypeVariable<?>, TypeVariable<?>> bindings, Type genericSuperType) { if ( genericSuperType == null ) { return; } else if ( genericSuperType instanceof ParameterizedType ) { Map<TypeVariable<?>, TypeVariable<?>> newBindings = new HashMap<>(); Type[] typeArguments = ( (ParameterizedType) genericSuperType ).getActualTypeArguments(); TypeVariable<?>[] typeParameters = ( (Class<?>) ( (ParameterizedType) genericSuperType ).getRawType() ).getTypeParameters(); for ( int i = 0; i < typeArguments.length; i++ ) { Type typeArgument = typeArguments[i]; TypeVariable<?> typeParameter = typeParameters[i]; boolean typeParameterFoundInSubType = false; for ( Entry<TypeVariable<?>, TypeVariable<?>> subTypeParameter : bindings.entrySet() ) { if ( typeArgument == subTypeParameter.getValue() ) { newBindings.put( subTypeParameter.getKey(), typeParameter ); typeParameterFoundInSubType = true; } } if ( !typeParameterFoundInSubType ) { newBindings.put( typeParameter, typeParameter ); } } allBindings.put( ( (Class<?>) ( (ParameterizedType) genericSuperType ).getRawType() ), newBindings ); collectTypeBindings( ( (Class<?>) ( (ParameterizedType) genericSuperType ).getRawType() ), allBindings, newBindings ); } else if ( genericSuperType instanceof Class ) { allBindings.put( (Class<?>) genericSuperType, Collections.emptyMap() ); } else { throw new IllegalArgumentException( "Unexpected type: " + genericSuperType ); } }

Target:
private static void processGenericSuperType(Map<Class<?>, Map<TypeVariable<?>, TypeVariable<?>>> allBindings, Map<TypeVariable<?>, TypeVariable<?>> bindings, Type genericSuperType) { if ( genericSuperType == null ) { return; } else if ( genericSuperType instanceof ParameterizedType ) { Map<TypeVariable<?>, TypeVariable<?>> newBindings = new HashMap<>(); Type[] typeArguments = ( (ParameterizedType) genericSuperType ).getActualTypeArguments(); TypeVariable<?>[] typeParameters = ( (Class<?>) ( (ParameterizedType) genericSuperType ).getRawType() ).getTypeParameters(); for ( int i = 0; i < typeArguments.length; i++ ) { Type typeArgument = typeArguments[i]; TypeVariable<?> typeParameter = typeParameters[i]; boolean typeParameterFoundInSubType = false; for ( Entry<TypeVariable<?>, TypeVariable<?>> subTypeParameter : bindings.entrySet() ) { if ( typeArgument.equals( subTypeParameter.getValue() ) ) { newBindings.put( subTypeParameter.getKey(), typeParameter ); typeParameterFoundInSubType = true; } } if ( !typeParameterFoundInSubType ) { newBindings.put( typeParameter, typeParameter ); } } allBindings.put( ( (Class<?>) ( (ParameterizedType) genericSuperType ).getRawType() ), newBindings ); collectTypeBindings( ( (Class<?>) ( (ParameterizedType) genericSuperType ).getRawType() ), allBindings, newBindings ); } else if ( genericSuperType instanceof Class ) { allBindings.put( (Class<?>) genericSuperType, Collections.emptyMap() ); } else { throw new IllegalArgumentException( "Unexpected type: " + genericSuperType ); } }
Source:
public final <T> PojoModelElementAccessor<T> createAccessor(Class<T> requestedType) { if ( !isAssignableTo( requestedType ) ) { log.incompatibleRequestedType( createAccessor(), requestedType ); } return (PojoModelElementAccessor<T>) createAccessor(); }

Target:
public final <T> PojoModelElementAccessor<T> createAccessor(Class<T> requestedType) { if ( !isAssignableTo( requestedType ) ) { log.incompatibleRequestedType( getModelPathTypeNode().toUnboundPath(), requestedType ); } return (PojoModelElementAccessor<T>) createAccessor(); }
Source:
public static Set<@ClassGetName String> getClassnamesFromArgs(VisibilityPredicate visibility) { Set<@ClassGetName String> classnames = getClassNamesFromFile(classlist); for (Path jarFile : testjar) { classnames.addAll(getClassnamesFromJarFile(jarFile, visibility)); } for (String classname : testclass) { if (!Signatures.isClassGetName(classname)) { throw new RandoopUsageError( "Illegal argument --testclass=" + classname + ", should be a class name"); } classnames.add(classname); } for (Iterator<String> itor = classnames.iterator(); itor.hasNext(); ) { String classname = itor.next(); if (shouldOmitClass(classname)) { itor.remove(); break; } } return classnames; }

Target:
public static Set<@ClassGetName String> getClassnamesFromArgs(VisibilityPredicate visibility) { Set<@ClassGetName String> classnames = getClassNamesFromFile(classlist); for (Path jarFile : testjar) { classnames.addAll(getClassnamesFromJarFile(jarFile, visibility)); } for (String classname : testclass) { if (!Signatures.isClassGetName(classname)) { throw new RandoopUsageError( "Illegal argument --testclass=" + classname + ", should be a class name"); } classnames.add(classname); } for (Iterator<String> itor = classnames.iterator(); itor.hasNext(); ) { String classname = itor.next(); if (shouldOmitClass(classname)) { itor.remove(); } } return classnames; }
Source:
public void validate() { super.validate(); assertTrue(courseId != null, "Time zone should not be null"); }

Target:
public void validate() { super.validate(); assertTrue(courseId != null, "Course ID should not be null"); }
Source:
public Maintainable toMaintenance() { return null; }

Target:
public Maintainable toMaintenance() { throw new UnsupportedOperationException("not yet implemented"); }
Source:
public void validate(final UsernamePasswordCredentials credentials, final WebContext context) throws HttpAction { init(context); if (credentials == null || credentials.getPassword() == null || credentials.getUsername() == null) { throw new TechnicalException("Credentials are required"); } final String ticketGrantingTicketId = requestTicketGrantingTicket(credentials.getUsername(), credentials.getPassword(), context); if (Strings.isNullOrEmpty(ticketGrantingTicketId)) { credentials.setUserProfile(null); } else { final CasRestProfile profile = new CasRestProfile(ticketGrantingTicketId, credentials.getUsername()); credentials.setUserProfile(profile); } }

Target:
public void validate(final UsernamePasswordCredentials credentials, final WebContext context) throws HttpAction { init(context); if (credentials == null || credentials.getPassword() == null || credentials.getUsername() == null) { throw new TechnicalException("Credentials are required"); } final String ticketGrantingTicketId = requestTicketGrantingTicket(credentials.getUsername(), credentials.getPassword(), context); if (CommonHelper.isNotBlank(ticketGrantingTicketId)) { credentials.setUserProfile(new CasRestProfile(ticketGrantingTicketId, credentials.getUsername())); } }