auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void completeOperation(FutureResult futureResult, Callback callback, Object operationResult, Exception exception) { try { futureResult.done(operationResult, exception); if (callback != null) { callback.onCompletion(operationResult, exception); } } catch (Exception e) { //@todo add metric. logger.error("Exception caught during future and callback completion", e); } finally { //@todo add metric. } }

Target:
private void completeOperation(FutureResult futureResult, Callback callback, Object operationResult, Exception exception) { try { futureResult.done(operationResult, exception); if (callback != null) { callback.onCompletion(operationResult, exception); } } catch (Exception e) { //@todo add metric. logger.error("Exception caught during future and callback completion", e); } finally { //@todo add metric. } }
Source:
public int read() throws IOException { ByteBuffer buffer = singleByteBufferChannel.getBuffer(); buffer.clear(); int data = -1; if (read(singleByteBufferChannel) != -1) { buffer.flip(); data = buffer.get() & 0xFF; totalBytesRead.incrementAndGet(); } return data; }

Target:
public int read() throws IOException { ByteBuffer buffer = singleByteBufferChannel.getBuffer(); buffer.clear(); int data = -1; if (read(singleByteBufferChannel) != -1) { buffer.flip(); data = buffer.get() & 0xFF; totalBytesRead++; } return data; }
Source:
protected OperationRequest makeOperationRequest(ReplicaId replicaId) { DeleteRequest deleteRequest = new DeleteRequest(context.getCorrelationId(), context.getClientId(), blobId); if (sslEnabledColos.contains(replicaId.getDataNodeId().getDatacenterName())) { return new DeleteOperationRequest(connectionPool, responseQueue, context, blobId, replicaId, deleteRequest, true); } else { return new DeleteOperationRequest(connectionPool, responseQueue, context, blobId, replicaId, deleteRequest, false); } }

Target:
protected OperationRequest makeOperationRequest(ReplicaId replicaId) { DeleteRequest deleteRequest = new DeleteRequest(context.getCorrelationId(), context.getClientId(), blobId); return new DeleteOperationRequest(connectionPool, responseQueue, context, blobId, replicaId, deleteRequest); }
Source:
public AdminMetrics(MetricRegistry metricRegistry) { //errors unknownActionErrorCount = metricRegistry.counter(MetricRegistry.name(AdminBlobStorageService.class, "unknownActionErrorCount")); }

Target:
public AdminMetrics(MetricRegistry metricRegistry) { }
Source:
public void channelInactive(ChannelHandlerContext ctx) { // TODO: once we support keepalive, we need to do this at the end of a request too. try { if (requestHandler != null) { requestHandler.onRequestComplete(request); } if (responseHandler != null) { responseHandler.onRequestComplete(request); } } catch (Exception e) { logger.error("Unable to perform cleanup tasks. Swallowing exception..", e); nettyMetrics.channelInactiveTasksFailureCount.inc(); } }

Target:
public void channelInactive(ChannelHandlerContext ctx) { onRequestComplete(null, true); }
Source:
public long sizeInBytes() { // header + blobId return super.sizeInBytes() + Blob_Id_Size_In_Bytes + blobId.sizeInBytes(); }

Target:
public long sizeInBytes() { // header + blobId return super.sizeInBytes() + blobId.sizeInBytes(); }
Source:
public StoreMetrics(String storeName, ReadableMetricsRegistry registry) { super(registry); writes = newCounter(storeName + "-Writes"); reads = newCounter(storeName + "-Reads"); deletes = newCounter(storeName + "-Deletes"); overflowWriteError = new Counter(storeName + "-OverflowWriteError"); }

Target:
public StoreMetrics(String storeName, ReadableMetricsRegistry registry) { super(registry); writes = newCounter(storeName + "-Writes"); reads = newCounter(storeName + "-Reads"); deletes = newCounter(storeName + "-Deletes"); overflowWriteError = newCounter(storeName + "-OverflowWriteError"); }
Source:
public static <T> T readBy(Session session, Class<T> clazz, String id) { LOG.trace("GenericDBUtil.readBy"); T entity = null; try { entity = session.get(clazz, id); LOG.trace("GenericDBUtil.readBy - entity = session.get()"); } catch (HibernateException | NullPointerException e) { LOG.error("Exception during read caused by : {}", e.getMessage(), e); throw e; } finally { closeSession(session); } return entity; }

Target:
public static <T> T readBy(Session session, Class<T> clazz, String id) { LOG.trace("GenericDBUtil.readBy"); T entity = null; try { entity = session.get(clazz, id); LOG.trace("GenericDBUtil.readBy - entity = session.get()"); } catch (HibernateException | NullPointerException e) { throw e; } finally { closeSession(session); } return entity; }
Source:
public void testGetExecutorPoolSize() { System.out.println("getExecutorPoolSize"); // default Pool Size int expResult = 100; int result = instance.getExecutorPoolSize(); assertEquals(expResult, result); }

Target:
public void testGetExecutorPoolSize() { // default Pool Size int expResult = 100; int result = instance.getExecutorPoolSize(); assertEquals(expResult, result); }
Source:
public static String getNhinServiceName(List<String> serviceNames) { for (String name : serviceNames) { try { if (StringUtils.isNotBlank(NhincConstants.NHIN_SERVICE_NAMES.fromValueString(name).toString())) { return NhincConstants.NHIN_SERVICE_NAMES.fromValueString(name).getUDDIServiceName(); } } catch(IllegalArgumentException e) { // ignoring, since the Sequoia UDDI often has multiple names for entries // and only one is known to CONNECT. } } return null; }

Target:
public static String getNhinServiceName(List<String> serviceNames) { for (String name : serviceNames) { try { if (StringUtils.isNotBlank(NhincConstants.NHIN_SERVICE_NAMES.fromValueString(name).toString())) { return NhincConstants.NHIN_SERVICE_NAMES.fromValueString(name).getUDDIServiceName(); } } catch(IllegalArgumentException e) { // ignoring, since the Sequoia UDDI often has multiple names for entries // and only one is known to CONNECT. //Adding logging of error so CAGitBot stops complaining LOG.debug(e.getMessage()); } } return null; }
Source:
public String getDefaultExchange() { return exInfo.getDefaultExchange(); }

Target:
public String getDefaultExchange() { return null != exInfo ? exInfo.getDefaultExchange() : null; }
Source:
public void setPatientId(String patientIdentifierIso) { getDocumentForm().setPatientId(patientIdentifierIso); getDocumentForm().setSourcePatientId(patientIdentifierIso); if (StringUtils.isNotBlank(patientIdentifierIso)) { String[] identifierValue = patientIdentifierIso.split("&"); HelperUtil.updateDocumentBy(withDocument, loadTestDataService.getPatientBy(identifierValue[0].replace("^^^", ""), identifierValue[1])); } else { HelperUtil.updateDocumentBy(withDocument, new Patient()); } }

Target:
public void setPatientId(String patientIdentifierIso) { if (StringUtils.isNotBlank(patientIdentifierIso)) { String[] identifierValue = patientIdentifierIso.split("&"); HelperUtil.updateDocumentBy(withDocument, loadTestDataService.getPatientBy(identifierValue[0].replace("^^^", ""), identifierValue[1])); } else { HelperUtil.updateDocumentBy(withDocument, new Patient()); } }
Source:
public boolean savePatient(Patient patient) throws LoadTestDataException { boolean actionResult; if (CollectionUtils.isNotEmpty(patient.getPersonnames())) { actionResult = patientDAO.saveTransaction(patient); updateDocumentWith(patient.getPatientId()); if (!actionResult) { logDaoError("Patient basic-info"); } } else { LOG.info("Patient basic-info is required"); throw new LoadTestDataException("Patient basic-info is required when trying to save-patient."); } return actionResult; }

Target:
public boolean savePatient(Patient patient) throws LoadTestDataException { boolean actionResult; if (CollectionUtils.isNotEmpty(patient.getPersonnames())) { actionResult = patientDAO.saveTransaction(patient); if (actionResult) { updateDocumentWith(patient.getPatientId()); } if (!actionResult) { logDaoError("Patient basic-info"); } } else { LOG.info("Patient basic-info is required"); throw new LoadTestDataException("Patient basic-info is required when trying to save-patient."); } return actionResult; }
Source:
public List<AttributeStatement> createEvidenceStatements(final List accessConstentValues, final List evidenceInstanceAccessConsentValues) { List<AttributeStatement> statements; if (CollectionUtils.isEmpty(accessConstentValues)) { LOG.debug("No Access Consent found for Evidence"); } // Set the Instance Access Consent if (CollectionUtils.isEmpty(evidenceInstanceAccessConsentValues)) { LOG.debug("No Instance Access Consent found for Evidence"); } statements = OpenSAML2ComponentBuilder.getInstance().createEvidenceStatements(accessConstentValues, evidenceInstanceAccessConsentValues, NHIN_NS); LOG.trace("SamlCallbackHandler.createEvidenceStatements() -- End"); return statements; }

Target:
public List<AttributeStatement> createEvidenceStatements(final List accessConstentValues, final List evidenceInstanceAccessConsentValues) { List<AttributeStatement> statements; statements = OpenSAML2ComponentBuilder.getInstance().createEvidenceStatements(accessConstentValues, evidenceInstanceAccessConsentValues, NHIN_NS); LOG.trace("SamlCallbackHandler.createEvidenceStatements() -- End"); return statements; }
Source:
public List<AuthzDecisionStatement> createAuthorizationDecisionStatements(final CallbackProperties properties, final Subject subject) { final List<AuthzDecisionStatement> authDecisionStatements = new ArrayList<>(); final Boolean hasAuthzStmt = properties.getAuthorizationStatementExists(); // The authorization Decision Statement is optional if (hasAuthzStmt) { // Create resource for Authentication Decision Statement final String resource = properties.getAuthorizationResource(); //"Decision. The Decision attribute of the Authorization Decision Statement must be Permit" &CONN-1758 String decision = AUTHZ_DECISION_PERMIT; final Evidence evidence = createEvidence(properties, subject); authDecisionStatements.add(OpenSAML2ComponentBuilder.getInstance().createAuthzDecisionStatement(resource, decision, AUTHZ_DECISION_ACTION_EXECUTE, evidence)); } return authDecisionStatements; }

Target:
public List<AuthzDecisionStatement> createAuthorizationDecisionStatements(final CallbackProperties properties, final Subject subject) { final List<AuthzDecisionStatement> authDecisionStatements = new ArrayList<>(); final Boolean hasAuthzStmt = properties.getAuthorizationStatementExists(); // The authorization Decision Statement is optional if (hasAuthzStmt) { // Create resource for Authentication Decision Statement final String resource = properties.getAuthorizationResource(); final Evidence evidence = createEvidence(properties, subject); authDecisionStatements.add(OpenSAML2ComponentBuilder.getInstance().createAuthzDecisionStatement(resource, AUTHZ_DECISION_PERMIT, AUTHZ_DECISION_ACTION_EXECUTE, evidence)); } return authDecisionStatements; }
Source:
protected Conditions createConditions(final CallbackProperties properties) { DateTime issueInstant = properties.getIssueInstant(); DateTime beginValidTime = properties.getSamlConditionsNotBefore(); DateTime endValidTime = properties.getSamlConditionsNotAfter(); if (issueInstant == null) { issueInstant = new DateTime(); } beginValidTime = setBeginValidTime(beginValidTime, issueInstant); endValidTime = setEndValidTime(endValidTime, issueInstant); // Only create the Conditions if NotBefore and/or NotOnOrAfter is present // if (beginValidTime != null || endValidTime != null) { return OpenSAML2ComponentBuilder.getInstance().createConditions(beginValidTime, endValidTime); // } }

Target:
protected Conditions createConditions(final CallbackProperties properties) { DateTime issueInstant = new DateTime(); DateTime beginValidTime = properties.getSamlConditionsNotBefore(); DateTime endValidTime = properties.getSamlConditionsNotAfter(); // Only create the Conditions if NotBefore and/or NotOnOrAfter is present if (beginValidTime != null || endValidTime != null) { beginValidTime = setBeginValidTime(beginValidTime, issueInstant); endValidTime = setEndValidTime(endValidTime, issueInstant); return OpenSAML2ComponentBuilder.getInstance().createConditions(beginValidTime, endValidTime); } return null; }
Source:
private static boolean checkDistinguishedName(final String userName) { Name name = null; try { name = new LdapName(userName); } catch (final Exception e) { LOG.trace("Exception checking DN: {}", e.getLocalizedMessage(), e); } return name == null ? false : true; }

Target:
private static boolean checkDistinguishedName(final String userName) { Name name = null; try { name = new LdapName(userName); } catch (final Exception e) { LOG.trace("Exception checking DN: {}", e.getLocalizedMessage(), e); } return name != null; }
Source:
public static DateTime setEndValidTime(DateTime endValidTimeArg, DateTime issueInstant) { DateTime endValidTime = endValidTimeArg; final DateTime now = new DateTime(); // Make end datetime at a minimum 5 minutes from now if (endValidTime == null || endValidTime.isBefore(now.plusMinutes(5))) { endValidTime = now.plusMinutes(5); } // Ensure issueInstant is contained within valid times if (endValidTime.isBefore(issueInstant)) { endValidTime = issueInstant.plusMinutes(5); } return endValidTime; }

Target:
private static DateTime setEndValidTime(DateTime endValidTimeArg, DateTime issueInstant) { DateTime endValidTime = endValidTimeArg; final DateTime now = new DateTime(); // Make end datetime at a minimum 5 minutes from now if (endValidTime == null || endValidTime.isBefore(now.plusMinutes(5))) { endValidTime = now.plusMinutes(5); } // Ensure issueInstant is contained within valid times if (endValidTime.isBefore(issueInstant)) { endValidTime = issueInstant.plusMinutes(5); } return endValidTime; }
Source:
public void init(ServletConfig config) throws ServletException { super.init(config); LOG.debug("InitServlet start..."); executor = Executors.newFixedThreadPool(ExecutorServiceHelper.getInstance().getExecutorPoolSize()); largeJobExecutor = Executors.newFixedThreadPool(ExecutorServiceHelper.getInstance() .getLargeJobExecutorPoolSize()); //Initialize HibernateUtil when CONNECTGatewayWeb is initialized required for AuditRepo JavaImpl EJB calls. //Do not Remove this ... SessionFactory session = HibernateUtil.getSessionFactory(); // register event loggers as observers... EventLoggerFactory.getInstance().registerLoggers(); }

Target:
public void init(ServletConfig config) throws ServletException { super.init(config); executor = Executors.newFixedThreadPool(ExecutorServiceHelper.getInstance().getExecutorPoolSize()); largeJobExecutor = Executors.newFixedThreadPool(ExecutorServiceHelper.getInstance() .getLargeJobExecutorPoolSize()); //Initialize HibernateUtil when CONNECTGatewayWeb is initialized required for AuditRepo JavaImpl EJB calls. //Do not Remove this ... HibernateUtil.getSessionFactory(); // register event loggers as observers... EventLoggerFactory.getInstance().registerLoggers(); }
Source:
protected AuditMessageType getParticipantObjectIdentificationForRequest( ProvideAndRegisterDocumentSetRequestType request, AssertionType assertion, AuditMessageType auditMsg) { // PatientParticipantObjetIdentification and SubmissionSetParticipantObjetIdentification is same for both //Request and Response in case of DS auditMsg = getPatientParticipantObjectIdentification(request, auditMsg); auditMsg = getSubmissionSetParticipantObjectIdentification(request, auditMsg); return auditMsg; }

Target:
protected AuditMessageType getParticipantObjectIdentificationForRequest( ProvideAndRegisterDocumentSetRequestType request, AssertionType assertion, AuditMessageType auditMsg) { // PatientParticipantObjectIdentification and SubmissionSetParticipantObjectIdentification is same for both //Request and Response in case of DS getPatientParticipantObjectIdentification(request, auditMsg); getSubmissionSetParticipantObjectIdentification(request, auditMsg); return auditMsg; }
Source:
protected AuditMessageType.ActiveParticipant getActiveParticipant(UserType oUserInfo) { // Create Active Participant Section // create a method to call the AuditDataTransformHelper - one expectation AuditMessageType.ActiveParticipant participant = createActiveParticipantFromUser( oUserInfo, Boolean.TRUE); if (oUserInfo.getRoleCoded() != null) { participant.getRoleIDCode().add(AuditDataTransformHelper.createCodeValueType(oUserInfo.getRoleCoded().getCode(), "", oUserInfo.getRoleCoded().getCodeSystemName(), oUserInfo.getRoleCoded().getDisplayName())); } return participant; }

Target:
protected AuditMessageType.ActiveParticipant getActiveParticipant(UserType oUserInfo) { // Create Active Participant Section // create a method to call the AuditDataTransformHelper - one expectation AuditMessageType.ActiveParticipant participant = createActiveParticipantFromUser(oUserInfo); if (oUserInfo.getRoleCoded() != null) { participant.getRoleIDCode().add(AuditDataTransformHelper.createCodeValueType(oUserInfo.getRoleCoded(). getCode(), "", oUserInfo.getRoleCoded().getCodeSystemName(), oUserInfo.getRoleCoded().getDisplayName())); } return participant; }
Source:
public String getToken() { createToken(); if (token != null) { return token; } return null; }

Target:
public String getToken() { createToken(); return token; }
Source:
public String getDocumentId() { return (documentId == null) ? URI : documentId; }

Target:
public String getDocumentId() { //workaround for now, once the CONNECT FHIR adapter supports //documentId, we will remove this logic return (documentId == null) ? uri : documentId; }
Source:
public void auditNhinCoreX12RealtimeRequest(COREEnvelopeRealTimeRequest message, AssertionType assertion, NhinTargetSystemType target, String direction) { LOG.debug("---Begin COREX12AuditLogger.auditCoreX12RealtimeRequest()---"); // Set up the audit logging request message AuditRepositoryLogger auditLogger = new AuditRepositoryLogger(); LogEventRequestType auditLogMsg = auditLogger.logNhinCoreX12RealtimeRequest(message, assertion, target, direction); if (auditLogMsg != null && auditLogMsg.getAuditMessage() != null) { audit(auditLogMsg, assertion); } else { LOG.error("Core X12 Realtime Request auditLogMsg is null"); } LOG.debug("---End COREX12AuditLogger.auditCoreX12RealtimeRequest()---"); }

Target:
public void auditNhinCoreX12RealtimeRequest(COREEnvelopeRealTimeRequest message, AssertionType assertion, NhinTargetSystemType target, String direction) { LOG.trace("---Begin COREX12AuditLogger.auditCoreX12RealtimeRequest()---"); // Set up the audit logging request message LogEventRequestType auditLogMsg = auditLogger.logNhinCoreX12RealtimeRequest(message, assertion, target, direction); if (auditLogMsg != null && auditLogMsg.getAuditMessage() != null) { audit(auditLogMsg, assertion); } else { LOG.error("Core X12 Realtime Request auditLogMsg is null"); } LOG.trace("---End COREX12AuditLogger.auditCoreX12RealtimeRequest()---"); }
Source:
public void registerHandlers() { //initialize the HibernateUtil when the Direct Servlet is initialized.. DO NOT Remove this. SessionFactory session = gov.hhs.fha.nhinc.event.persistence.HibernateUtil.getSessionFactory(); session = gov.hhs.fha.nhinc.direct.messagemonitoring.persistence.HibernateUtil.getSessionFactory(); LOG.debug("Registering event Loggers"); EventLoggerFactory.getInstance().registerLoggers(); LOG.debug("Registering handlers..."); getDirectReceiver(); }

Target:
public void registerHandlers() { //initialize the HibernateUtil when the Direct Servlet is initialized.. DO NOT Remove this. SessionFactory session = gov.hhs.fha.nhinc.event.persistence.HibernateUtil.getSessionFactory(); session = gov.hhs.fha.nhinc.direct.messagemonitoring.persistence.HibernateUtil.getSessionFactory(); LOG.trace("Registering event Loggers"); EventLoggerFactory.getInstance().registerLoggers(); LOG.trace("Registering handlers..."); getDirectReceiver(); }
Source:
public COREEnvelopeRealTimeResponse realTimeRequest(COREEnvelopeRealTimeRequest coreEnvelopeRealTimeRequest, AssertionType assertion) { COREEnvelopeRealTimeResponse oResponse = null; if (coreEnvelopeRealTimeRequest != null) { LOG.trace("Begin AdapterCORE_X12DSRealTimeOrchImpl.realTimeRequest()"); //Call to a method which builds response metadata and returns response oResponse = buildAdapterCORE_X12DSRealTimeResponseMetadata(); //Call for logging inbound logAdapterCORE_X12DSRealTimeRequest(coreEnvelopeRealTimeRequest); LOG.trace("End AdapterCORE_X12DSRealTimeOrchImpl.realTimeRequest()"); } else { oResponse = new COREEnvelopeRealTimeResponse(); return oResponse; //TODO: Need to add error handling } return oResponse; }

Target:
public COREEnvelopeRealTimeResponse realTimeRequest(COREEnvelopeRealTimeRequest coreEnvelopeRealTimeRequest, AssertionType assertion) { COREEnvelopeRealTimeResponse oResponse = null; if (coreEnvelopeRealTimeRequest != null) { LOG.trace("Begin AdapterCORE_X12DSRealTimeOrchImpl.realTimeRequest()"); //Call to a method which builds response metadata and returns response oResponse = buildAdapterCORE_X12DSRealTimeResponseMetadata(); //Call for logging inbound logAdapterCORE_X12DSRealTimeRequest(coreEnvelopeRealTimeRequest); LOG.trace("End AdapterCORE_X12DSRealTimeOrchImpl.realTimeRequest()"); } else { oResponse = new COREEnvelopeRealTimeResponse(); //TODO: Need to add error handling } return oResponse; }
Source:
public SimpleDateFormatThreadSafe(final String pattern, final DateFormatSymbols formatSymbols) { super(pattern, formatSymbols); localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() { protected SimpleDateFormat initialValue() { return new SimpleDateFormat(pattern, formatSymbols); } }; }

Target:
public SimpleDateFormatThreadSafe(final String pattern, final DateFormatSymbols formatSymbols) { super(pattern, formatSymbols); localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat(pattern, formatSymbols); } }; }
Source:
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException { String name = rs.getString(names[0]); return rs.wasNull() ? null : new CEP(name); }

Target:
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException { String value = rs.getString(names[0]); return rs.wasNull() ? null : new CEP(value); }
Source:
public void boletoNaoDeveAceitarDescricaoNula() { Boleto b = Boleto.novoBoleto(); b.comDescricao(""); }

Target:
public void boletoNaoDeveAceitarDescricaoNula() { Boleto b = Boleto.novoBoleto(); b.comDescricao(null); }
Source:
public String decapitalize(String word) { // do nothing if null or empty if ((word == null) || (word.length() < 1)) { return word; } // or if already decapitalized char first = word.charAt(0); if (Character.isLowerCase(first)) { return word; } // otherwise turn the first character to lower case and attach the rest return String.valueOf(Character.toLowerCase(first)) + word.substring(1); }

Target:
public String decapitalize(String word) { // do nothing if null or empty if ((word == null) || (word.length() < 1)) { return word; } // or if already decapitalized char first = word.charAt(0); if (Character.isLowerCase(first)) { return word; } // otherwise turn the first character to lower case and attach the rest StringBuilder sb = new StringBuilder(word.length()); sb.append(Character.toLowerCase(first)); sb.append(word.substring(1)); return sb.toString(); }
Source:
public void visitCtYieldStatement(CtYieldStatement statement) { String foo = ""; }

Target:
public void visitCtYieldStatement(CtYieldStatement statement) { }
Source:
public static void setup() { testMethods = testMethods.stream() .filter(v -> v.hasAnnotation(Test.class) && v.hasAnnotation(Ignore.class) && v.getAnnotation(Ignore.class).value().equals("UnresolvedBug")) .collect(Collectors.toList()); }

Target:
public static void setup() { testMethods = testMethods.stream() .filter(v -> v.hasAnnotation(Test.class) && v.hasAnnotation(Ignore.class) && v.getAnnotation(Ignore.class).value().equalsIgnoreCase("UnresolvedBug")) .collect(Collectors.toList()); }
Source:
private void defineCommentContent(String tagContent, CtJavaDocTag.TagType tagType) { if (tagType != null) { CtJavaDocTag docTag = this.getFactory().Code().createJavaDocTag(tagContent, tagType); this.addTag(docTag); } else if (!tagContent.isEmpty()) { this.setContent(tagContent.trim()); } }

Target:
private void defineCommentContent(String tagContent, CtJavaDocTag.TagType tagType) { if (tagType != null) { CtJavaDocTag docTag = this.getFactory().Code().createJavaDocTag(tagContent, tagType); this.addTag(docTag); } }
Source:
private static ContainerKind containerKindOf(Class<?> valueClass) { if (List.class.isAssignableFrom(valueClass)) { return ContainerKind.LIST; } if (Map.class.isAssignableFrom(valueClass)) { return ContainerKind.MAP; } if (Set.class.isAssignableFrom(valueClass) || Collection.class.isAssignableFrom(valueClass)) { return ContainerKind.SET; } return ContainerKind.SINGLE; }

Target:
private static ContainerKind containerKindOf(Class<?> valueClass) { if (List.class.isAssignableFrom(valueClass)) { return ContainerKind.LIST; } if (Map.class.isAssignableFrom(valueClass)) { return ContainerKind.MAP; } if (Collection.class.isAssignableFrom(valueClass)) { return ContainerKind.SET; } return ContainerKind.SINGLE; }
Source:
public ScanningMode enter(CtElement element) { if (ignoredParent != null && element != null) { if (element.hasParent(ignoredParent)) { return ScanningMode.SKIP_ALL; } } if (element instanceof CtType) { nrOfNestedLocalClasses++; } return ScanningMode.NORMAL; }

Target:
public ScanningMode enter(CtElement element) { if (ignoredParent != null && element != null && element.hasParent(ignoredParent)) { return ScanningMode.SKIP_ALL; } if (element instanceof CtType) { nrOfNestedLocalClasses++; } return ScanningMode.NORMAL; }
Source:
public <E extends CtElement> E setAllMetadata(Map<String, Object> metadata) { if (metadata != null) { if (this.metadata == null) { this.metadata = new HashMap<>(); } else { this.metadata.clear(); } this.metadata.putAll(metadata); } else { this.metadata = null; } return (E) this; }

Target:
public <E extends CtElement> E setAllMetadata(Map<String, Object> metadata) { if (metadata == null || metadata.isEmpty()) { this.metadata = null; return (E) this; } if (this.metadata == null) { this.metadata = new HashMap<>(); } else { this.metadata.clear(); } this.metadata.putAll(metadata); return (E) this; }
Source:
private String getCommentContent(int start, int end) { try { return IOUtils.toString(new CharArrayReader(contents, start, end - start)); } catch (IOException e) { throw new SpoonException(e); } }

Target:
private String getCommentContent(int start, int end) { return new String(contents, start, end - start); }
Source:
public boolean getNoClasspath() { if (this.noclasspath == null) { logger.warn("Spoon is currently use with the default noClasspath option set as true. Read the documentation for more information: http://spoon.gforge.inria.fr/launcher.html#about-the-classpath"); return true; } return noclasspath; }

Target:
public boolean getNoClasspath() { if (this.noclasspath == null) { logger.warn("Spoon is currently use with the default noClasspath option set as true. Read the documentation for more information: http://spoon.gforge.inria.fr/launcher.html#about-the-classpath"); this.noclasspath = true; } return noclasspath; }
Source:
public <T extends CtStatementList> T setStatements(List<CtStatement> statements) { if (statements == null || statements.isEmpty()) { this.statements.clear(); return (T) this; } this.statements.clear(); this.statements.addAll(statements); return (T) this; }

Target:
public <T extends CtStatementList> T setStatements(List<CtStatement> statements) { this.statements.set(statements); return (T) this; }
Source:
static void linkToParent(CtElement owner, CtElement element) { if (owner.getFactory().getEnvironment().checksAreSkipped() == false && element.isParentInitialized() && element.getParent() != owner) { //the `e` already has an different parent. Check if it is still linked to that parent if (element.getRoleInParent() != null) { throw new SpoonException("The element " + element + " is already used by another part of SpoonModel. Remove it from previous model or clone it before."); } } element.setParent(owner); }

Target:
static void linkToParent(CtElement owner, CtElement element) { element.setParent(owner); }
Source:
protected boolean biScan(CtRole role, Collection<? extends CtElement> elements, Collection<? extends CtElement> others) { for (Iterator<? extends CtElement> firstIt = elements.iterator(), secondIt = others.iterator(); (firstIt.hasNext()) && (secondIt.hasNext());) { biScan(role, firstIt.next(), secondIt.next()); } return true; }

Target:
protected void biScan(CtRole role, Collection<? extends CtElement> elements, Collection<? extends CtElement> others) { for (Iterator<? extends CtElement> firstIt = elements.iterator(), secondIt = others.iterator(); (firstIt.hasNext()) && (secondIt.hasNext());) { biScan(role, firstIt.next(), secondIt.next()); } }
Source:
public boolean addModule(CtModule module) { if (allModules.containsKey(module.getSimpleName())) { return false; } allModules.put(module.getSimpleName(), module); return true; }

Target:
public boolean addModule(CtModule module) { return this.allModules.add(module); }
Source:
public <T extends CtElement> T setParent(T parent) { if (!this.getSimpleName().equals(CtModule.TOP_LEVEL_MODULE_NAME) && parent != getFactory().Module().getUnnamedModule()) { throw new SpoonException("The parent of a module should necessarily be the unnamed module."); } return (T) super.setParent(parent); }

Target:
public <T extends CtElement> T setParent(T parent) { return (T) this; }
Source:
public boolean isOverriding(CtMethod<?> thisMethod, CtMethod<?> thatMethod) { if (thisMethod == thatMethod) { //method overrides itself in spoon model return true; } CtType<?> thatDeclType = thatMethod.getDeclaringType(); CtType<?> thisDeclType = getAdaptationScope(); if (thatDeclType != thisDeclType) { if (isSubtypeOf(thatDeclType.getReference()) == false) { //the declaringType of that method must be superType of this scope type return false; } } //TODO check method visibility following https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.8.1 return isSubSignature(thisMethod, thatMethod) || isSubSignature(thatMethod, thisMethod); }

Target:
public boolean isOverriding(CtMethod<?> thisMethod, CtMethod<?> thatMethod) { if (thisMethod == thatMethod) { //method overrides itself in spoon model return true; } CtType<?> thatDeclType = thatMethod.getDeclaringType(); CtType<?> thisDeclType = getAdaptationScope(); if (thatDeclType != thisDeclType) { if (isSubtypeOf(thatDeclType.getReference()) == false) { //the declaringType of that method must be superType of this scope type return false; } } //TODO check method visibility following https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.8.1 return isSubSignature(thisMethod, thatMethod); }
Source:
public CtStatement apply(CtType<?> targetType) { CtClass<?> c = Substitution.getTemplateCtClass(targetType, this); // we substitute the first statement of method statement CtStatement result = c.getMethod("statement").getBody().getStatements().get(0).clone(); return (CtStatement) new SubstitutionVisitor(c.getFactory(), targetType, this).substitute(result); }

Target:
public CtStatement apply(CtType<?> targetType) { CtClass<?> c = Substitution.getTemplateCtClass(targetType, this); // we substitute the first statement of method statement CtStatement result = c.getMethod("statement").getBody().getStatements().get(0).clone(); return new SubstitutionVisitor(c.getFactory(), targetType, this).substitute(result); }
Source:
public <C extends CtTypedElement> C setType(CtTypeReference<T> type) { if (getExecutable() != null && type != null) { getExecutable().setType(type); type.setParent(this); } return (C) this; }

Target:
public <C extends CtTypedElement> C setType(CtTypeReference<T> type) { if (type != null) { type.setParent(this); } if (getExecutable() != null) { getExecutable().setType(type); } return (C) this; }
Source:
public List<SpoonFile> getAllFiles() { List<SpoonFile> result = new ArrayList<>(); Set<SpoonFile> distinctSet = new HashSet<>(); for (SpoonFile f : getFiles()) { // we take care not to add a file that was already found in a folder if (distinctSet.add(f)) { result.add(f); } } return result; }

Target:
public List<SpoonFile> getAllFiles() { List<SpoonFile> result = new ArrayList<>(); for (SpoonFile f : getFiles()) { // we take care not to add a file that was already found in a folder if (!result.contains(f)) { result.add(f); } } return result; }
Source:
public void setBinaryOutputDirectory(File outputDirectory) { modelBuilder.setBinaryOutputDirectory(outputDirectory); getFactory().getEnvironment().setBinaryOutputDirectory(outputDirectory.getAbsolutePath()); }

Target:
public void setBinaryOutputDirectory(File outputDirectory) { setBinaryOutputDirectory(outputDirectory.getPath()); }
Source:
public void testWildcard() throws Exception { assertEquals(3, buildClass(Paella.class).getElements(new TypeFilter<CtWildcardReference>(CtWildcardReference.class) { @Override public boolean matches(CtWildcardReference element) { return element.getParent(CtTypeParameter.class) != null; } }).size()); }

Target:
public void testWildcard() throws Exception { assertEquals(3, buildClass(Paella.class).getElements(new TypeFilter<CtWildcardReference>(CtWildcardReference.class)).size()); }
Source:
public void reflectionAPI() throws Exception { // Spoon can be used as reflection API CtType s = new TypeFactory().get(String.class); assertEquals("String", s.getSimpleName()); assertEquals("java.lang.String", s.getQualifiedName()); assertEquals(3, s.getSuperInterfaces().size()); assertEquals(2,s.getMethodsByName("toLowerCase").size()); System.out.println(s); }

Target:
public void reflectionAPI() throws Exception { // Spoon can be used as reflection API CtType s = new TypeFactory().get(String.class); assertEquals("String", s.getSimpleName()); assertEquals("java.lang.String", s.getQualifiedName()); assertEquals(3, s.getSuperInterfaces().size()); assertEquals(2,s.getMethodsByName("toLowerCase").size()); }
Source:
public void testSourceClasspath() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { final SpoonModelBuilder.ClasspathOptions options = new SpoonModelBuilder.ClasspathOptions().classpath(systemClasspath); Assert.assertEquals("-cp " + TEST_CLASSPATH, String.join(" ", options.build())); }

Target:
public void testSourceClasspath() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { final ClasspathOptions options = new ClasspathOptions().classpath(systemClasspath); Assert.assertEquals("-cp " + TEST_CLASSPATH, String.join(" ", options.build())); }
Source:
public Object[] getFiniteSupport() { checkHasParams(); return null; }

Target:
public Object[] getFiniteSupport() { return null; }
Source:
public boolean showSearchBox() { // Only show it if Library is loaded. if (node.pluginManager != null && node.pluginManager.isPluginLoaded("plugins.Library.Main")) { return true; } else { return false; } }

Target:
public boolean showSearchBox() { // Only show it if Library is loaded. return (node.pluginManager != null && node.pluginManager.isPluginLoaded("plugins.Library.Main")); }
Source:
public int hashCode() { // see #equals return element.hashCode(); }

Target:
public int hashCode() { if (element == null) { // shouldn't ever happen return super.hashCode(); } // see #equals for explanation return element.hashCode(); }
Source:
protected int getPriorityFromTaintFrame(TaintFrame fact, int offset) throws DataflowAnalysisException { Taint mvcResultTaint = fact.getStackValue(offset); // The MVC Result object was tainted - This could still be safe if the content-type is a safe one if (!mvcResultTaint.isSafe()) { // Get the value of the content-type parameter Taint parameterTaint = fact.getStackValue(0); if ( !parameterTaint.isSafe() || (parameterTaint.getConstantValue() != null && parameterTaint.getConstantValue().toLowerCase().equals(VULNERABLE_CONTENT_TYPE)) ) { return getPriority(mvcResultTaint); } } return Priorities.IGNORE_PRIORITY; }

Target:
protected int getPriorityFromTaintFrame(TaintFrame fact, int offset) throws DataflowAnalysisException { Taint mvcResultTaint = fact.getStackValue(offset); // The MVC Result object was tainted - This could still be safe if the content-type is a safe one if (!mvcResultTaint.isSafe()) { // Get the value of the content-type parameter Taint parameterTaint = fact.getStackValue(0); if ( !parameterTaint.isSafe() || VULNERABLE_CONTENT_TYPE.equalsIgnoreCase(parameterTaint.getConstantValue())) { return getPriority(mvcResultTaint); } } return Priorities.IGNORE_PRIORITY; }
Source:
void maybeDeleteRecordedAutoDeleteExchange(String exchange) { synchronized (this.consumers) { synchronized (this.recordedExchanges) { if(!hasMoreDestinationsBoundToExchange(Utility.copy(this.recordedBindings), exchange)) { RecordedExchange x = this.recordedExchanges.get(exchange); // last binding where this exchange is the source is gone, remove recorded exchange // if it is auto-deleted. See bug 26364. if((x != null) && x.isAutoDelete()) { deleteRecordedExchange(exchange); } } } } }

Target:
void maybeDeleteRecordedAutoDeleteExchange(String exchange) { synchronized (this.consumers) { synchronized (this.recordedExchanges) { if(!hasMoreDestinationsBoundToExchange(Utility.copy(this.recordedBindings), exchange)) { RecordedExchange x = this.recordedExchanges.get(exchange); // last binding where this exchange is the source is gone, remove recorded exchange // if it is auto-deleted. See bug 26364. if((x != null) && x.isAutoDelete()) { this.recordedExchanges.remove(exchange); } } } } }
Source:
public boolean onKeyUp(int keyCode, KeyEvent event) { //If the key entered is 'Enter'('next' or 'done'), then move the focus // to the next view. if (keyCode == KeyEvent.KEYCODE_ENTER) { if (brandText.hasFocus()) { yearText.requestFocus(); return true; } else if (playerNameText.hasFocus()) { teamText.requestFocus(); return true; } else if (teamText.hasFocus() == true) { playerPositionSpinner.requestFocus(); return true; } } return super.onKeyUp(keyCode, event); }

Target:
public boolean onKeyUp(int keyCode, KeyEvent event) { //If the key entered is 'Enter'('next' or 'done'), then move the focus // to the next view. if (keyCode == KeyEvent.KEYCODE_ENTER) { if (brandText.hasFocus()) { yearText.requestFocus(); return true; } else if (playerNameText.hasFocus()) { teamText.requestFocus(); return true; } else if (teamText.hasFocus()) { playerPositionSpinner.requestFocus(); return true; } } return super.onKeyUp(keyCode, event); }
Source:
public ButtonRs() { this(ButtonRs.DEFAULT_BUILD); final GraphicsEnvironment env = GraphicsEnvironment .getLocalGraphicsEnvironment(); font(env, "http://img.rultor.com/rultor.ttf"); // @checkstyle LineLength (1 line) font(env, "http://img.rultor.com/helveticaneue.ttf"); }

Target:
public ButtonRs() { this(ButtonRs.DEFAULT_BUILD); final GraphicsEnvironment env = GraphicsEnvironment .getLocalGraphicsEnvironment(); this.font(env, "http://img.rultor.com/rultor.ttf"); this.font(env, "http://img.rultor.com/helveticaneue.ttf"); }
Source:
public void testFindWorkingTemplateNoNPE() throws DotDataException, DotSecurityException { try { final Template template = templateAPI.findWorkingTemplate("NO_TEMPLATE", APILocator.getUserAPI().getSystemUser(), false); assertNull(template); } catch(NullPointerException e) { Logger.error(this, "getting non-existant template should not throw an NPE", e); } }

Target:
public void testFindWorkingTemplateNoNPE() throws DotDataException, DotSecurityException { try { final Template template = templateAPI.findWorkingTemplate("NO_TEMPLATE", APILocator.getUserAPI().getSystemUser(), false); assertNull(template); } catch(NullPointerException e) { Logger.error(this, "getting non-existant template should not throw an NPE", e); assertTrue("getting non-existant template should not throw an NPE", false); } }
Source:
public void execute(JobDelegateDataBean data) { try { executeDelegate(data); } catch (Exception e) { Logger.error(this, "An error occurred when running the Job Delegate: " + this.getClass(), e); } finally { // The main reason for this abstraction is to ensure that the // database connection is released and closed after executing this try { HibernateUtil.closeSession(); } catch (DotHibernateException e) { Logger.warn(this, e.getMessage(), e); } } }

Target:
public void execute(JobDelegateDataBean data) { try { executeDelegate(data); } catch (Exception e) { Logger.error(this, "An error occurred when running the Job Delegate: " + this.getClass(), e); } }
Source:
abstract void serve() throws Exception; abstract void serve(Writer out) throws DotDataException, IOException, DotSecurityException; public final String eval() { StringWriter out = new StringWriter(4096); try { serve(out); } catch (Exception e) { throw new DotRuntimeException(e); } return out.toString(); }

Target:
abstract void serve() throws DotDataException, IOException, DotSecurityException; abstract void serve(Writer out) throws DotDataException, IOException, DotSecurityException; public final String eval() { StringWriter out = new StringWriter(4096); try { serve(out); } catch (DotDataException | IOException | DotSecurityException e) { throw new DotRuntimeException(e); } return out.toString(); }
Source:
protected List<String> getTablesToDropConstraints() { // TODO Auto-generated method stub return null; }

Target:
protected List<String> getTablesToDropConstraints() { return new ArrayList<>(); }
Source:
public void testGetFolderContentWithInvalidIdentifier() throws Exception { // https://github.com/dotCMS/core/issues/11829 final String NOT_EXISTING_ID = "01234567-1234-1234-1234-123456789012"; try { browserAPI.getFolderContent( APILocator.systemUser(), NOT_EXISTING_ID, 0, -1, "", null, null, true, false, false, false, "", false, false, 1 ); } catch ( Exception e ){ Assert.assertTrue( e instanceof NotFoundInDbException ); } }

Target:
public void testGetFolderContentWithInvalidIdentifier() { // https://github.com/dotCMS/core/issues/11829 final String NOT_EXISTING_ID = "01234567-1234-1234-1234-123456789012"; try { browserAPI.getFolderContent( APILocator.systemUser(), NOT_EXISTING_ID, 0, -1, "", null, null, true, false, false, false, "", false, false, 1 ); } catch ( Exception e ){ Assert.assertTrue( e instanceof NotFoundInDbException ); } }
Source:
public void registerBundleService () { if(System.getProperty(WebKeys.OSGI_ENABLED)!=null){ // Register main service BundleContext context = HostActivator.instance().getBundleContext(); if (null != context) { Hashtable<String, String> props = new Hashtable<String, String>(); context.registerService(WorkflowAPIOsgiService.class.getName(), this, props); } else { Logger.debug(this, "Bundle Context is null, WorkflowAPIOsgiService has been not registered"); } } }

Target:
public void registerBundleService () { if(System.getProperty(WebKeys.OSGI_ENABLED)!=null){ // Register main service BundleContext context = HostActivator.instance().getBundleContext(); if (null != context) { Hashtable<String, String> props = new Hashtable<String, String>(); context.registerService(WorkflowAPIOsgiService.class.getName(), this, props); } else { Logger.error(this, "Bundle Context is null, WorkflowAPIOsgiService has been not registered"); } } }
Source:
private boolean validPayload(final SessionWrapper session, final Payload payload) { //Get the verifier associated to this Payload final PayloadVerifier verifier = this.payloadVerifierFactory.getVerifier(payload); if ( null != verifier ) { //Check if we have the "visibility" rights to use this payload return verifier.verified(payload, session); } return true; }

Target:
private boolean validPayload(final SessionWrapper session, final Payload payload) { //Get the verifier associated to this Payload final PayloadVerifier verifier = this.payloadVerifierFactory.getVerifier(payload); //Check if we have the "visibility" rights to use this payload return (null != verifier) ? verifier.verified(payload, session) : true; }
Source:
private int readStreamToStrBuffer(int length) throws IOException { if (length > strBuffer.length - strBufferIndex) { expandStrBuffer(length); } int bytesRead = inputStream.read(strBuffer, strBufferIndex, Math.min(length, strBuffer.length - strBufferIndex)); if (bytesRead < 0) { throw new IOException("Reached end of stream."); } strBufferIndex += bytesRead; System.out.println(bytesRead); return bytesRead; }

Target:
private int readStreamToStrBuffer(int length) throws IOException { if (length > strBuffer.length - strBufferIndex) { expandStrBuffer(length); } int bytesRead = inputStream.read(strBuffer, strBufferIndex, Math.min(length, strBuffer.length - strBufferIndex)); if (bytesRead < 0) { throw new IOException("Reached end of stream."); } strBufferIndex += bytesRead; return bytesRead; }
Source:
private void readAmount(int numChars) throws IOException { int bytesRead = is.read(buffer, end, Math.min(numChars, buffer.length - end)); if (bytesRead < 0) { // EOF throw new IOException(String.format("Reached end of stream.")); } end = end + bytesRead; }

Target:
private void readAmount(int numChars) throws IOException { int bytesRead = reader.read(buffer, end, Math.min(numChars, buffer.length - end)); if (bytesRead < 0) { // EOF throw new IOException("Reached end of stream."); } end = end + bytesRead; }
Source:
public Response saveRule(RuleDTO ruleDTO) { final Rule rule = convert(ruleDTO); rule.setId(null); rule.setPosition(0); // new rules get the lowest position (lowest priority) final int ruleId = classificationService.saveRule(rule); final UriBuilder builder = UriBuilder.fromResource(ClassificationRestService.class); final URI uri = builder.path(ClassificationRestService.class, "getRule").build(ruleId); return Response.created(uri).build(); }

Target:
public Response saveRule(RuleDTO ruleDTO) { final Rule rule = convert(ruleDTO); rule.setId(null); final int ruleId = classificationService.saveRule(rule); final UriBuilder builder = UriBuilder.fromResource(ClassificationRestService.class); final URI uri = builder.path(ClassificationRestService.class, "getRule").build(ruleId); return Response.created(uri).build(); }
Source:
public String getUnmodifiedInstance() { return null; //For node type resources, use the default instance }

Target:
public String getUnmodifiedInstance() { return getInstance(); }
Source:
public void testNodesWithFlows() { this.m_driver.get(this.getBaseUrl() + "opennms/element/nodeList.htm?flows=true"); assertThat(Iterables.transform(m_driver.findElements(By.xpath("//div[@class='NLnode']//a")), WebElement::getText), containsInAnyOrder("TestMachine loc1node2", "TestMachine loc2node2")); }

Target:
public void testNodesWithFlows() { m_driver.get(this.getBaseUrl() + "opennms/element/nodeList.htm?flows=true"); assertThat(Iterables.transform(m_driver.findElements(By.xpath("//div[@class='NLnode']//a")), WebElement::getText), containsInAnyOrder("TestMachine loc1node2", "TestMachine loc2node2")); }
Source:
public NodeInfo getNodeInfo() { return this.getProperty(GenericProperties.NODE_INFO); // final Optional<Object> first = graphProperties.getProperties().values().stream().filter(v -> v instanceof NodeInfo).findFirst(); // if (first.isPresent()) { // return (NodeInfo) first.get(); // } // return (NodeInfo) graphProperties.getComputedProperties().values().stream().filter(v -> v instanceof NodeInfo).findFirst().orElse(null); }

Target:
public NodeInfo getNodeInfo() { return null; // final Optional<Object> first = graphProperties.getProperties().values().stream().filter(v -> v instanceof NodeInfo).findFirst(); // if (first.isPresent()) { // return (NodeInfo) first.get(); // } // return (NodeInfo) graphProperties.getComputedProperties().values().stream().filter(v -> v instanceof NodeInfo).findFirst().orElse(null); }
Source:
public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof IpServiceEdgeRequestDTO)) { return false; } if (!super.equals(obj)) { return false; } // compare subclass fields return java.util.Objects.equals(applicationId, ((ApplicationEdgeRequestDTO) obj).applicationId); }

Target:
public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof ApplicationEdgeRequestDTO)) { return false; } if (!super.equals(obj)) { return false; } // compare subclass fields return java.util.Objects.equals(applicationId, ((ApplicationEdgeRequestDTO) obj).applicationId); }