auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
RegistryResponseType registerDocumentSetBUnsecured(RespondingGatewayRegisterDocumentSetRequestType request) { RegistryResponseType response = null; try { setTargetCommunitiesVersion(request.getNhinTargetCommunities(), SPEC_1_0); response = outboundDocDataSubmission.registerDocumentSetB(request.getRegisterDocumentSetRequest(), request.getAssertion(), request.getNhinTargetCommunities(), request.getUrl()); } catch (Exception e) { LOG.error("Failed to send request to Nwhin: {}", e); START throw new ErrorEventException(e, "Unable to call Nhin Doc Data Submission"); END } return response; } Question: check to see if we log twice.

Target:
RegistryResponseType registerDocumentSetBUnsecured(RespondingGatewayRegisterDocumentSetRequestType request) { RegistryResponseType response = null; try { setTargetCommunitiesVersion(request.getNhinTargetCommunities(), SPEC_1_0); response = outboundDocDataSubmission.registerDocumentSetB(request.getRegisterDocumentSetRequest(), request.getAssertion(), request.getNhinTargetCommunities(), request.getUrl()); } catch (Exception e) { throw new ErrorEventException(e, "Unable to call Nhin Doc Data Submission"); } return response; }
Source:
public void testGetExecutorPoolSize() { START System.out.println("getExecutorPoolSize"); END // default Pool Size int expResult = 100; int result = instance.getExecutorPoolSize(); assertEquals(expResult, result); } Optional: replace these System out with LOG statements

Target:
public void testGetExecutorPoolSize() { // default Pool Size int expResult = 100; int result = instance.getExecutorPoolSize(); assertEquals(expResult, result); }
Source:
public static gov.hhs.fha.nhinc.patientdiscovery.persistence.HibernateUtil getPatientDiscoveryHibernateUtil() { ClassPathXmlApplicationContext context = ClassPathSingleton.CONTEXT; START LOG.debug("Memory address getPatientDiscoveryHibernateUtil {}", context.getId()); END if (patientDiscoveryHibernateUtil == null) { patientDiscoveryHibernateUtil = context.getBean(NhincConstants.PATIENT_DISCOVERY_HIBERNATE_BEAN, gov.hhs.fha.nhinc.patientdiscovery.persistence.HibernateUtil.class); } return patientDiscoveryHibernateUtil; } Do we need this?

Target:
public static gov.hhs.fha.nhinc.patientdiscovery.persistence.HibernateUtil getPatientDiscoveryHibernateUtil() { ClassPathXmlApplicationContext context = ClassPathSingleton.CONTEXT; if (patientDiscoveryHibernateUtil == null) { patientDiscoveryHibernateUtil = context.getBean(NhincConstants.PATIENT_DISCOVERY_HIBERNATE_BEAN, gov.hhs.fha.nhinc.patientdiscovery.persistence.HibernateUtil.class); } return patientDiscoveryHibernateUtil; }
Source:
public void addPatientCorrelationPLQ(PatientLocationQueryResponseType plqRecords, AssertionType assertion) { if (plqRecords == null) { LOG.warn("PLQRecords was null"); } try { PatientCorrelationPLQHelper.addPatientCorrelationPLQRecords(plqRecords); START } catch (final Exception ex) { END LOG.error("Error calling addPatientCorrelation: {}", ex.getMessage(), ex); } } Dont catch generic exceptions. Narrow it down to something specific.

Target:
public void addPatientCorrelationPLQ(PatientLocationQueryResponseType plqRecords, AssertionType assertion) { if (plqRecords == null) { LOG.warn("PLQRecords was null"); return; } PatientCorrelationPLQHelper.addPatientCorrelationPLQRecords(plqRecords); }
Source:
public AdapterPatientLocationQuerySecuredResponseType adapterPatientLocationQuerySecured( AdapterPatientLocationQuerySecuredRequestType request) { START context.toString(); END return PatientLocationQueryImpl.getPatientLocationQuery().getAdapterPLQSecuredResponse(request); } Do we need this?

Target:
public AdapterPatientLocationQuerySecuredResponseType adapterPatientLocationQuerySecured( AdapterPatientLocationQuerySecuredRequestType request) { return PatientLocationQueryImpl.getPatientLocationQuery().getAdapterPLQSecuredResponse(request); }
Source:
private static List<String> buildDescritpion(BusinessEntity entity) { List<String> descList = new ArrayList<>(); START if (null != entity && CollectionUtils.isNotEmpty(entity.getDescription())) { END for (Description obj : entity.getDescription()) { descList.add(obj.getValue()); } } return descList; } I feel the isNotEmpty() check is not needed here. The for loop will take care of this case.

Target:
private static List<String> buildDescritpion(BusinessEntity entity) { List<String> descList = new ArrayList<>(); if (null != entity && null != entity.getDescription()) { for (Description obj : entity.getDescription()) { descList.add(obj.getValue()); } } return descList; }
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(); } START } catch(IllegalArgumentException e) { END // ignoring, since the Sequoia UDDI often has multiple names for entries // and only one is known to CONNECT. } } return null; } ![CRITICAL](https://sonarsource.github.io/sonar-github/severity-critical.png 'Severity: CRITICAL') Either log or rethrow this exception. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](http://192.168.3.101:9000/coding_rules#rule_key=squid%3AS1166)

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:
private static boolean isOverrideExchange(ExchangeType exchange) { return null != exchange.getOrganizationList() && CollectionUtils.isNotEmpty(exchange.getOrganizationList().getOrganization()) START && StringUtils.isNotEmpty(exchange.getType()) && StringUtils.equalsIgnoreCase( END EXCHANGE_TYPE.OVERRIDES.toString(), exchange.getType()); } Optional: No need to do StringUtils.isNotEmpty(exchange.getType()) since StringUtils.equalsIgnoreCase can handle null if exchange.getType()=null

Target:
private static boolean isOverrideExchange(ExchangeType exchange) { return null != exchange.getOrganizationList() && CollectionUtils.isNotEmpty(exchange.getOrganizationList().getOrganization()) && StringUtils.equalsIgnoreCase(EXCHANGE_TYPE.OVERRIDES.toString(), exchange.getType()); }
Source:
public List<OrganizationType> getAllOrganizations(String exchangeName) throws ExchangeManagerException { refreshExchangeCacheIfRequired(); START return null != exchangeName ? new ArrayList<>(getCache().get(exchangeName).values()) END : new ArrayList<>(getCache().get(this.getDefaultExchange()).values()); } wonder if we can put (null !=exchange) to make reading more easier? If not, don't worry.

Target:
public List<OrganizationType> getAllOrganizations(String exchangeName) throws ExchangeManagerException { refreshExchangeCacheIfRequired(); return (null != exchangeName) ? new ArrayList<>(getCache().get(exchangeName).values()) : new ArrayList<>(getCache().get(this.getDefaultExchange()).values()); }
Source:
protected CONNECTCXFClient(ServicePortDescriptor<T> portDescriptor, String url, AssertionType assertion, ServicePortBuilder<T> portBuilder, String subscriptionId) { serviceEndpoint = super.configureBasePort(portBuilder.createPort(), subscriptionId, assertion != null ? assertion.getTransactionTimeout() : null); START configCNCheck(); END } remove this method

Target:
protected CONNECTCXFClient(ServicePortDescriptor<T> portDescriptor, String url, AssertionType assertion, ServicePortBuilder<T> portBuilder, String subscriptionId) { serviceEndpoint = super.configureBasePort(portBuilder.createPort(), subscriptionId, assertion != null ? assertion.getTransactionTimeout() : null); }
Source:
public String getDefaultExchange() { START return exInfo.getDefaultExchange(); END } need null-checked here

Target:
public String getDefaultExchange() { return null != exInfo ? exInfo.getDefaultExchange() : null; }
Source:
public List<ExchangeType> getExchanges() { exchanges = exchangeService.getAllExchanges(); START return exchanges; END } we should return exchangeService.getAllExchanges(); instead of assigned and return

Target:
public List<ExchangeType> getExchanges() { return exchangeService.getAllExchanges(); }
Source:
private List<CertificateDTO> listKeyStore(String portName) throws CertificateManagerException { ListKeyStoresRequestMessageType message = new ListKeyStoresRequestMessageType(); START ConfigAssertionType assertion = buildConfigAssertion(getKeyStorePassKey()); END message.setConfigAssertion(assertion); ListKeyStoresResponseMessageType response; try { response = (ListKeyStoresResponseMessageType) getClient().invokePort(EntityConfigAdminPortType.class, portName, message); } catch (Exception e) { throw new CertificateManagerException("Error while fetching certificates.", e); } return soapResponseToDTO(response.getCertList()); } No need for password/hash for listKeystore/listTrustStore

Target:
private List<CertificateDTO> listKeyStore(String portName) throws CertificateManagerException { ListKeyStoresRequestMessageType message = new ListKeyStoresRequestMessageType(); ConfigAssertionType assertion = buildConfigAssertion(); message.setConfigAssertion(assertion); ListKeyStoresResponseMessageType response; try { response = (ListKeyStoresResponseMessageType) getClient().invokePort(EntityConfigAdminPortType.class, portName, message); } catch (Exception e) { throw new CertificateManagerException("Error while fetching certificates.", e); } return soapResponseToDTO(response.getCertList()); }
Source:
private static boolean isHashTokenEmpty() { START return StringUtils.isBlank(getHashTokenFromSession()) ? true : false; END } remove "?true:false". It is unnecessary

Target:
private static boolean isHashTokenEmpty() { return StringUtils.isBlank(getHashTokenFromSession()); }
Source:
public static OrganizationType findOrganizationTypeBy(List<OrganizationType> organizations, String hcid) { if (CollectionUtils.isEmpty(organizations)) { return null; } START if (StringUtils.isBlank(hcid)) { END return organizations.get(0); } for (OrganizationType organization : organizations) { if (equalsIgnoreCaseForHCID(hcid, organization.getHcid())) { return organization; } } return null; } Please elaborate why we are returning an organization when hcid is blank

Target:
public static OrganizationType findOrganizationTypeBy(List<OrganizationType> organizations, String hcid) { if (CollectionUtils.isEmpty(organizations)) { return null; } if (StringUtils.isBlank(hcid)) { return null; } for (OrganizationType organization : organizations) { if (equalsIgnoreCaseForHCID(hcid, organization.getHcid())) { return organization; } } return null; }
Source:
public void setPatientId(String patientIdentifierIso) { getDocumentForm().setPatientId(patientIdentifierIso); START getDocumentForm().setSourcePatientId(patientIdentifierIso); END if (StringUtils.isNotBlank(patientIdentifierIso)) { String[] identifierValue = patientIdentifierIso.split("&"); HelperUtil.updateDocumentBy(withDocument, loadTestDataService.getPatientBy(identifierValue[0].replace("^^^", ""), identifierValue[1])); } else { HelperUtil.updateDocumentBy(withDocument, new Patient()); } } removed Line: 278 and 279 - this already being done in the HelperUtil.updateDocumentBy

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); START updateDocumentWith(patient.getPatientId()); END 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; } check-actionResult before updateDocumentWith

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<Patient> getCachePatients() { if (null == cachePatients) { START getAllPatients(); END } return cachePatients; } There is no assignment to cachePatients here.

Target:
public List<Patient> getCachePatients() { if (null == cachePatients) { cachePatients = getAllPatients(); } return cachePatients; }
Source:
public List<Phonenumber> getPhonenumbers() { if (isValidPatientId()) { return loadTestDataService.getAllPhonenumbersBy(getPatientId()); } else { return new ArrayList<>(); } START } END A method should have only one return statement instead of two. Use a local variable to get the result and return the local variable.

Target:
public List<Phonenumber> getPhonenumbers() { return loadTestDataService.getAllPhonenumbersBy(getPatientId()); }
Source:
START private int getKeySize(X509Certificate cert){ END PublicKey publicKey = cert.getPublicKey(); if (publicKey instanceof RSAPublicKey){ return ((RSAPublicKey)publicKey).getModulus().bitLength(); } return -1; } ![MINOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-minor.png) Make "getKeySize" a "static" method. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](http://GFE-ONC-LDEV15.connect.org:9000/coding_rules#rule_key=squid%3AS2325)

Target:
private static int getKeySize(X509Certificate cert){ PublicKey publicKey = cert.getPublicKey(); if (publicKey instanceof RSAPublicKey){ return ((RSAPublicKey)publicKey).getModulus().bitLength(); } return -1; }
Source:
public Address read(Long id) { START LOG.debug("AddressDAO.read() - Begin"); END if (id == null) { LOG.info("-- id Parameter is required for Address Query --"); LOG.debug("AddressDAO.read() - End"); return null; } Address foundRecord = super.read(id, Address.class); LOG.debug("AddressDAO.read() - End"); return foundRecord; } Inconsistent log level. Use only one. Stick to trace level for now in this method.

Target:
public Address read(Long id) { LOG.trace("AddressDAO.read() - Begin"); if (id == null) { LOG.trace("-- id Parameter is required for Address Query --"); LOG.trace("AddressDAO.read() - End"); return null; } Address foundRecord = super.read(id, Address.class); LOG.trace("AddressDAO.read() - End"); return foundRecord; }
Source:
protected boolean validateAttributes() { boolean validate = false; try { validate = PropertyAccessor.getInstance().getPropertyBoolean(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.VALIDATE_ATTRIBUTES_PROP); START } catch (PropertyAccessException ex) { END LOG.warn("Unable to access property for validating SAML attributes due to: {}", ex.getLocalizedMessage()); } return validate; } just need log.warn("msg {}", ex.getLocalizedMessage(),ex);

Target:
protected boolean validateAttributes() { boolean validate = false; try { validate = PropertyAccessor.getInstance().getPropertyBoolean(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.VALIDATE_ATTRIBUTES_PROP); } catch (PropertyAccessException ex) { LOG.warn("Unable to access property for validating SAML attributes due to: {}", ex.getLocalizedMessage(), ex); } return validate; }
Source:
public List<AttributeStatement> createEvidenceStatements(final List accessConstentValues, final List evidenceInstanceAccessConsentValues) { List<AttributeStatement> statements; START if (CollectionUtils.isEmpty(accessConstentValues)) { END 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; } These 2 if conditions and log statements are unnecessary. We can rew3ord and write these log statement in OpenSaml2Builder.createEvidenceStatements method.

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 START String decision = AUTHZ_DECISION_PERMIT; END final Evidence evidence = createEvidence(properties, subject); authDecisionStatements.add(OpenSAML2ComponentBuilder.getInstance().createAuthzDecisionStatement(resource, decision, AUTHZ_DECISION_ACTION_EXECUTE, evidence)); } return authDecisionStatements; } Unneeded local variable, just put the constant value into the method a couple lines below.

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:
public static String checkPrefixBeforeAppend(final String checkValue, final String checkPrefix) { final String tempValue = checkValue.toLowerCase(); final String tempPrefix = checkPrefix.toLowerCase(); START if(tempValue.indexOf(tempPrefix) == -1){ END return MessageFormat.format("{0}{1}", checkPrefix, checkValue); } else { return checkValue; } } use startsWith instead of indexOf. indexOf will return position even if the communityId is defined as 67i8urn:oid

Target:
public static String checkPrefixBeforeAppend(final String checkValue, final String checkPrefix) { final String tempValue = checkValue.trim().toLowerCase(); final String tempPrefix = checkPrefix.toLowerCase(); if(!tempValue.startsWith(tempPrefix)){ return MessageFormat.format("{0}{1}", checkPrefix, checkValue); } else { return checkValue; } }
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(); } START beginValidTime = setBeginValidTime(beginValidTime, issueInstant); END 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); // } } This is where the if statement should be for checking the property for allowing for corrected times.

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:
public void configure() { super.configure(); START HTTPConduit conduit = getHttpConduit(); END TLSClientParameters tlsCP = tlsClientFactory.getTLSClientParameters(); conduit.setTlsClientParameters(tlsCP); } Use inline method call over here.

Target:
public void configure() { super.configure(); getHttpConduit().setTlsClientParameters(tlsClientFactory.getTLSClientParameters()); }
Source:
private static String getPropertiesUpdateMessage(String msg, String key, String oldValue, String newValue) { StringBuilder buffer = new StringBuilder(); START buffer.append(msg); END buffer.append(key); buffer.append(" from "); buffer.append(oldValue); buffer.append(" to "); buffer.append(newValue); buffer.append("."); return buffer.toString(); } optional: use buffer.append(msg).append(key).append("...")

Target:
private static String getPropertiesUpdateMessage(String msg, String key, String oldValue, String newValue) { StringBuilder buffer = new StringBuilder(); buffer.append(msg).append(key).append(" from ").append(oldValue).append(" to ").append(newValue).append("."); return buffer.toString(); }
Source:
public void onDirectTabChange(TabChangeEvent tEvent) { Tab selectedTab = tEvent.getTab(); START if (selectedTab.getId().equalsIgnoreCase(DIRECTDOMAINTAB)) { END directTabIndex = 0; } else if (selectedTab.getId().equalsIgnoreCase(DIRECTAGENTTAB)) { directTabIndex = 1; } else if (selectedTab.getId().equalsIgnoreCase(DIRECTCERTTAB)) { directTabIndex = 2; } else { directTabIndex = 3; } } Optional: use DIRECTDOMAINTAB.equalsIgnoreCase(selectedTab.getId()) to prevent NPE if second operator is null

Target:
public void onDirectTabChange(TabChangeEvent tEvent) { Tab selectedTab = tEvent.getTab(); if (DIRECTDOMAINTAB.equalsIgnoreCase(selectedTab.getId())) { directTabIndex = 0; } else if (DIRECTAGENTTAB.equalsIgnoreCase(selectedTab.getId())) { directTabIndex = 1; } else if (DIRECTCERTTAB.equalsIgnoreCase(selectedTab.getId())) { directTabIndex = 2; } else { directTabIndex = 3; } }
Source:
public CXFSAMLCallbackHandler(final HOKSAMLAssertionBuilder builder) { this.builder = builder; START accessor = PropertyAccessor.getInstance(); END } To prevent code duplication, would it be possible to change the body of this constructor to the following? this(); this.builder = builder;

Target:
public CXFSAMLCallbackHandler(final HOKSAMLAssertionBuilder builder) { this(); this.builder = builder; }
Source:
private static String getCustomErrorMsg(final String errorType) { StringBuilder errorBuilder = new StringBuilder(); errorBuilder.append(SamlConstants.SECURITY_ASSERTION_ISSUER_FORMAT); errorBuilder.append(" "); errorBuilder.append(SamlConstants.URN_OASIS_NAMES); errorBuilder.append(" and "); errorBuilder.append(errorType); errorBuilder.append(" "); errorBuilder.append(IS_PRESENT); START return errorBuilder.toString(); END } Suggestion for readability -- chaining calls to append: ```java StringBuilder errorBuilder = new StringBuilder(SamlConstants.SECURITY_ASSERTION_ISSUER_FORMAT) .append(" ") ...SNIPPED... ``` If you're feeling really crazy, you can even skip the StringBuilder declaration and just make the function a single statement: ```java return new StringBuilder(SamlConstants.SECURITY_ASSERTION_ISSUER_FORMAT) .append(" ") ...SNIPPED... .toString(); ```

Target:
private static String getCustomErrorMsg(final String errorType) { return new StringBuilder(SamlConstants.SECURITY_ASSERTION_ISSUER_FORMAT).append("").append(" ") .append(SamlConstants.URN_OASIS_NAMES).append(" and ").append(errorType).append(" ").append(IS_PRESENT) .toString(); }
Source:
private boolean hasKeepAliveForConnection() { String keepAlive = assertion.getKeepAlive(); if (NullChecker.isNullish(keepAlive)) { keepAlive = getKeepAliveProperty(); } return NullChecker.isNotNullish(keepAlive) START && (keepAlive.equalsIgnoreCase("TRUE") || keepAlive.equalsIgnoreCase("T")); END } ![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Move the "TRUE" string literal on the left side of this string comparison. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](http://GFE-ONC-LDEV15.connect.org:9000/coding_rules#rule_key=squid%3AS1132) ![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Move the "T" string literal on the left side of this string comparison. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](http://GFE-ONC-LDEV15.connect.org:9000/coding_rules#rule_key=squid%3AS1132)

Target:
private boolean hasKeepAliveForConnection() { String keepAlive = assertion.getKeepAlive(); if (NullChecker.isNullish(keepAlive)) { keepAlive = getKeepAliveProperty(); } return ("TRUE".equalsIgnoreCase(keepAlive) || "T".equalsIgnoreCase(keepAlive)); }
Source:
START private String trimPropertyName(String propName) { END if ((propName.length()) > (NhincConstants.CUSTOM_HTTP_HEADERS.length() + 1)) { return propName.substring(NhincConstants.CUSTOM_HTTP_HEADERS.length() + 1).trim(); } else { return null; } } ![MINOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-minor.png) Make "trimPropertyName" a "static" method. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](http://GFE-ONC-LDEV15.connect.org:9000/coding_rules#rule_key=squid%3AS2325)

Target:
private static String trimPropertyName(String propName) { if ((propName.length()) > (NhincConstants.CUSTOM_HTTP_HEADERS.length() + 1)) { return propName.substring(NhincConstants.CUSTOM_HTTP_HEADERS.length() + 1).trim(); } else { return null; } }
Source:
private void handleHttpHeaders(AssertionType assertion, WebServiceContext context) { try { if (getPropertyAccessor().getPropertyBoolean(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.READ_HTTP_HEADERS)) { MessageContext messageContext = getMessageContext(context); START if (messageContext != null && (messageContext instanceof WrappedMessageContext)) { END readHttpHeaders(messageContext, assertion); } } } catch (PropertyAccessException ex) { LOG.warn("Unable to access property for reading HTTP headers.", ex); } } remove !=null since null instanceof WrappedMessageContext will return false

Target:
private void handleHttpHeaders(AssertionType assertion, WebServiceContext context) { try { if (getPropertyAccessor().getPropertyBoolean(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.READ_HTTP_HEADERS)) { MessageContext messageContext = getMessageContext(context); if (messageContext instanceof WrappedMessageContext) { readHttpHeaders(messageContext, assertion); } } } catch (PropertyAccessException ex) { LOG.warn("Unable to access property for reading HTTP headers.", ex); } }
Source:
protected long getTimeStampFutureTTL() { try { return PropertyAccessor.getInstance().getPropertyLong(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.TIMESTAMP_FUTURE_TIME_TO_LIVE); } catch (PropertyAccessException pae) { START LOG.warn("Failed to determine timestamp future TTL in gateway.properties, will use default value: {}", END pae.getLocalizedMessage()); LOG.trace("Get Timestamp future TTL exception: {}", pae.getLocalizedMessage(), pae); } return INVALID_LONG_VALUE; } consider to use warn or trace. It doesn't make sense to log twice with different message

Target:
protected long getTimeStampFutureTTL() { try { return PropertyAccessor.getInstance().getPropertyLong(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.TIMESTAMP_FUTURE_TIME_TO_LIVE); } catch (PropertyAccessException pae) { LOG.error("Failed to determine timestamp future TTL in gateway.properties, will use default value: {}", pae.getLocalizedMessage(), pae); } return INVALID_LONG_VALUE; }
Source:
START private static boolean checkDistinguishedName(final String userName) { END Name name = null; try { name = new LdapName(userName); } catch (final Exception e) { LOG.warn("Not a Valid Distinguished Name, setting the value from Certificate: {}", e.getLocalizedMessage()); LOG.trace("Exception checking DN: {}", e.getLocalizedMessage(), e); } return name == null ? false : true; } do we need to use static on this private method? Please update javac doc

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 KeyInfo getKeyInfo(final PublicKey publicKey) throws SAMLComponentBuilderException { final KeyInfoBean keyInfoBean = new KeyInfoBean(); KeyInfo keyInfo = null; keyInfoBean.setPublicKey(publicKey); try { keyInfo = SAML1ComponentBuilder.createKeyInfo(keyInfoBean); START } catch (org.opensaml.security.SecurityException | org.apache.wss4j.common.ext.WSSecurityException e) { END LOG.error(e.getLocalizedMessage(), e); throw new SAMLComponentBuilderException(e.getLocalizedMessage(), e); } return keyInfo; } Why are we not importing these classes at the top of the file?

Target:
public KeyInfo getKeyInfo(final PublicKey publicKey) throws SAMLComponentBuilderException { final KeyInfoBean keyInfoBean = new KeyInfoBean(); KeyInfo keyInfo = null; keyInfoBean.setPublicKey(publicKey); try { keyInfo = SAML1ComponentBuilder.createKeyInfo(keyInfoBean); } catch (SecurityException | WSSecurityException e) { LOG.error(e.getLocalizedMessage(), e); throw new SAMLComponentBuilderException(e.getLocalizedMessage(), e); } return keyInfo; }
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); } START return name == null ? false : true; END } This could just be: return name != null;

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:
START public static DateTime setEndValidTime(DateTime endValidTimeArg, DateTime issueInstant) { END 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; } Same here, why public?

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:
private void sanitizeInput(final String value) throws SanitizationException { try { CleanResults result = antiSamy.scan(value); List<String>errorMsgList = result.getErrorMessages(); START if (CollectionUtils.isNotEmpty(errorMsgList)) { END throw new SanitizationException("Malicious code has been detected on the HTTP header"); } } catch (ScanException | PolicyException | SanitizationException ex) { throw new SanitizationException(ex); } } No need to define errorMsgList. you can use inline here.

Target:
private void sanitizeInput(final String value) throws SanitizationException { try { CleanResults result = antiSamy.scan(value); if (CollectionUtils.isNotEmpty(result.getErrorMessages())) { throw new SanitizationException("Malicious code has been detected on the HTTP header"); } } catch (ScanException | PolicyException | SanitizationException ex) { throw new SanitizationException(ex); } }
Source:
public static void closeSession(Session session) { if (session != null) { try { session.close(); } catch (Exception e) { LOG.error("Failed to close session: ", e); } } else { START LOG.warn("Session is null, cannot close"); END } } Do we need this else block?

Target:
public static void closeSession(Session session) { if (session != null) { try { session.close(); } catch (Exception e) { LOG.error("Failed to close session: ", e); } } }
Source:
public List<QualifiedPatientIdentifier> retrievePatientCorrelation( QualifiedPatientIdentifier qualifiedPatientIdentifier, List<String> includeOnlyAssigningAuthorities) { Retriever retriever = new Retriever(); START return retriever.retrievePatientCorrelation(qualifiedPatientIdentifier, includeOnlyAssigningAuthorities); END } we can just make this call inline. new Retriever().retrievePatientCorrelation(qualifiedPatientIdentifier, includeOnlyAssigningAuthorities);

Target:
public List<QualifiedPatientIdentifier> retrievePatientCorrelation( QualifiedPatientIdentifier qualifiedPatientIdentifier, List<String> includeOnlyAssigningAuthorities) { return Retriever.retrievePatientCorrelation(qualifiedPatientIdentifier, includeOnlyAssigningAuthorities); }
Source:
protected Session getSession() { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); START return sessionFactory.openSession(); END } Can this be reduced to a single line?

Target:
protected Session getSession() { return HibernateUtil.getSessionFactory().openSession(); }
Source:
public String clearAuditTabMessageId() { this.relatesTo = null; this.messageId = null; START if (this.auditRecordList != null && !auditRecordList.isEmpty()) { END this.auditRecordList.clear(); } this.auditMessage = ""; this.auditFound = false; return NavigationConstant.AUDIT_SEARCH_PAGE; } Checking for Not null is sufficient here. We don't need to check !auditRecordList.isEmpty() as we are clearing the list.

Target:
public String clearAuditTabMessageId() { this.relatesTo = null; this.messageId = null; if (auditRecordList != null) { this.auditRecordList.clear(); } this.auditMessage = ""; this.auditFound = false; return NavigationConstant.AUDIT_SEARCH_PAGE; }
Source:
public void testLogFindAuditEvents() { START System.out.println("testLogFindAuditEvents"); END AuditRepositoryLogger instance = new AuditRepositoryLogger(); FindAuditEventsMessageType message = new FindAuditEventsMessageType(); FindAuditEventsType auditEvent = new FindAuditEventsType(); auditEvent.setPatientId("D12345"); message.setFindAuditEvents(auditEvent); LogEventRequestType result = instance.logFindAuditEvents(message, NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION, NhincConstants.AUDIT_LOG_NHIN_INTERFACE); assertNotNull(result); assertEquals(NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION, result.getDirection()); assertNotNull(result.getAuditMessage()); } This log statement isn't really adding any value (plus it's a system out call....) -- can you remove this?

Target:
public void testLogFindAuditEvents() { AuditRepositoryLogger instance = new AuditRepositoryLogger(); FindAuditEventsMessageType message = new FindAuditEventsMessageType(); FindAuditEventsType auditEvent = new FindAuditEventsType(); auditEvent.setPatientId("D12345"); message.setFindAuditEvents(auditEvent); LogEventRequestType result = instance.logFindAuditEvents(message, NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION, NhincConstants.AUDIT_LOG_NHIN_INTERFACE); assertNotNull(result); assertEquals(NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION, result.getDirection()); assertNotNull(result.getAuditMessage()); }
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 ... START SessionFactory session = HibernateUtil.getSessionFactory(); END // register event loggers as observers... EventLoggerFactory.getInstance().registerLoggers(); } Do we need the local variable session anywhere? Otherwise, just call getSessionFactory without assigning it to anything.

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); START return auditMsg; END } Instead of assign and return, just return the last statement.

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:
public void execute(OutboundDocSubmissionDeferredRequestOrchestratable message) { START LOG.debug("Begin OutboundDocSubmissionOrchestratableImpl_g0.process"); END NhinDocSubmissionDeferredRequestProxy nhincDocSubmission = getNhinDocSubmissionDeferredRequestProxy(); XDRAcknowledgementType response = nhincDocSubmission.provideAndRegisterDocumentSetBRequest11( message.getRequest(), message.getAssertion(), message.getTarget()); message.setResponse(response); LOG.debug("End OutboundDocSubmissionDeferredRequestStrategyImpl_g0.process"); } As you are touching this code base, can you remove this logging statement at the beginning and exiting the method

Target:
public void execute(OutboundDocSubmissionDeferredRequestOrchestratable message) { NhinDocSubmissionDeferredRequestProxy nhincDocSubmission = getNhinDocSubmissionDeferredRequestProxy(); XDRAcknowledgementType response = nhincDocSubmission.provideAndRegisterDocumentSetBRequest11( message.getRequest(), message.getAssertion(), message.getTarget()); message.setResponse(response); }
Source:
public static String getHomeCommunityIdFromAssertion(AssertionType assertion) { String homeCommunity = null; try { if (NullChecker.isNotNullish(assertion.getHomeCommunity().getHomeCommunityId())) { homeCommunity = assertion.getHomeCommunity().getHomeCommunityId(); } START } catch (NullPointerException ex) { END LOG.warn("Could not obtain HCID from HomeCommunity in assertion.", ex); } return homeCommunity; } Remove the NullPointerException catch statement and rewrite with a Null check.

Target:
public static String getHomeCommunityIdFromAssertion(AssertionType assertion) { String homeCommunity = null; if (assertion != null && assertion.getHomeCommunity() != null && NullChecker.isNotNullish(assertion.getHomeCommunity().getHomeCommunityId())) { homeCommunity = assertion.getHomeCommunity().getHomeCommunityId(); } return homeCommunity; }
Source:
public MCCIIN000002UV01 processPatientDiscoveryAsyncReq(RespondingGatewayPRPAIN201305UV02SecuredRequestType request) { AssertionType assertion = getAssertion(context, null); return outboundPatientDiscoveryRequest.processPatientDiscoveryAsyncReq(request.getPRPAIN201305UV02(), assertion, request.getNhinTargetCommunities(), getWebContextProperties(context)); START } END Can you explain why does Entity Outbound requires WebContextProperties for PatientDiscoveryDeferredRequest service?

Target:
public MCCIIN000002UV01 processPatientDiscoveryAsyncReq(RespondingGatewayPRPAIN201305UV02SecuredRequestType request) { AssertionType assertion = getAssertion(context, null); return outboundPatientDiscoveryRequest.processPatientDiscoveryAsyncReq(request.getPRPAIN201305UV02(), assertion, request.getNhinTargetCommunities()); }
Source:
public static boolean isNotNullishIgnoreSpace(String value) { START return (value != null && !value.trim().isEmpty()); END } Unnecessary parens around return value.

Target:
public static boolean isNotNullishIgnoreSpace(String value) { return value != null && !value.trim().isEmpty(); }
Source:
private static II getLivingSubjectId(PRPAMT201306UV02LivingSubjectId id) { II oII = null; START if (id != null && id.getValue() != null) { END oII = id.getValue().get(0); } return oII; } Should getValue() be tested for emptiness as well, due to subsequent .get(0)?

Target:
private static II getLivingSubjectId(PRPAMT201306UV02LivingSubjectId id) { II oII = null; if (id != null && id.getValue() != null && !id.getValue().isEmpty()) { oII = id.getValue().get(0); } return oII; }
Source:
private static PRPAMT201306UV02LivingSubjectId createSubjectId(II subjectId) { START PRPAMT201306UV02LivingSubjectId id = new PRPAMT201306UV02LivingSubjectId(); END if (subjectId != null) { id.getValue().add(subjectId); } return id; } If subjectId is null, should we return a blank PRPAMT201306UV02LivingSubjectId, or null?

Target:
private static PRPAMT201306UV02LivingSubjectId createSubjectId(II subjectId) { PRPAMT201306UV02LivingSubjectId id = new PRPAMT201306UV02LivingSubjectId(); id.getValue().add(subjectId); return id; }
Source:
private String getInboundReplyToHeader(WebServiceContext context) { MessageContext messageContext = context.getMessageContext(); if (messageContext == null || !(messageContext instanceof WrappedMessageContext)) { return null; } Message message = ((WrappedMessageContext) messageContext).getWrappedMessage(); AddressingProperties maps = (AddressingProperties) message.get(NhincConstants.INBOUND_REPLY_TO_HEADER); START return (maps.getReplyTo().getAddress().getValue()); END } Unnecessary parens around the return value.

Target:
private String getInboundReplyToHeader(WebServiceContext context) { MessageContext messageContext = context.getMessageContext(); if (messageContext == null || !(messageContext instanceof WrappedMessageContext)) { return null; } Message message = ((WrappedMessageContext) messageContext).getWrappedMessage(); AddressingProperties maps = (AddressingProperties) message.get(NhincConstants.INBOUND_REPLY_TO_HEADER); return maps.getReplyTo().getAddress().getValue(); }
Source:
protected Marshaller getMarshaller() { Marshaller marshaller = null; try { JAXBContextHandler oHandler = new JAXBContextHandler(); JAXBContext jc = oHandler.getJAXBContext(CORE_X12AuditDataTransformConstants.CORE_X12_JAXB_CONTEXT); marshaller = jc.createMarshaller(); START return marshaller; END } catch (JAXBException ex) { LOG.error("JAXB Marshall error : " + ex.getMessage(), ex); } return marshaller; } This return is redundant and should be removed

Target:
protected Marshaller getMarshaller() { Marshaller marshaller = null; try { JAXBContextHandler oHandler = new JAXBContextHandler(); JAXBContext jc = oHandler.getJAXBContext(CORE_X12AuditDataTransformConstants.CORE_X12_JAXB_CONTEXT); marshaller = jc.createMarshaller(); } catch (JAXBException ex) { LOG.error("JAXB Marshall error : " + ex.getMessage(), ex); } return marshaller; }
Source:
protected QName getQname(String nameSpaceURI, String localPart) { QName xmlQname = null; START xmlQname = new QName(nameSpaceURI, localPart); END return xmlQname; } This function should be a single line (inline return).

Target:
protected QName getQname(String nameSpaceURI, String localPart) { return (new QName(nameSpaceURI, localPart)); }
Source:
private JAXBElement<RegistryObjectType> createIdentifiable(RegistryObjectType registryObjectType) { START JAXBElement<RegistryObjectType> i = new JAXBElement<>(new QName( END "urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0", "Identifiable"), RegistryObjectType.class, registryObjectType); return i; } Don't create and immediately return, do the return in-line.

Target:
private JAXBElement<RegistryObjectType> createIdentifiable(RegistryObjectType registryObjectType) { return new JAXBElement<>(new QName( "urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0", "Identifiable"), RegistryObjectType.class, registryObjectType); }
Source:
public void auditRequestMessage(T request, AssertionType assertion, NhinTargetSystemType target, String direction, String _interface, Boolean isRequesting, Properties webContextProperties, String serviceName) { LOG.trace("--- Before auditing of request message ---"); if (getAuditLogger() != null) { getAuditLogger().auditRequestMessage(request, assertion, target, direction, _interface, isRequesting, webContextProperties, serviceName, getAuditTransforms()); START } else { END LOG.error("Error looking into EJB JNDI Object"); } LOG.trace("--- After auditing of request message ---"); } You already log an error if JNDI lookup fails, as part of getAuditLogger() -- do we need this else statement?

Target:
public void auditRequestMessage(T request, AssertionType assertion, NhinTargetSystemType target, String direction, String _interface, Boolean isRequesting, Properties webContextProperties, String serviceName) { LOG.trace("--- Before auditing of request message ---"); if (getAuditLogger() != null) { getAuditLogger().auditRequestMessage(request, assertion, target, direction, _interface, isRequesting, webContextProperties, serviceName, getAuditTransforms()); } LOG.trace("--- After auditing of request message ---"); }
Source:
protected String createUUID() { START return (UUID.randomUUID().toString()); END } Unnecessary parentheses (and an extra line break).

Target:
protected String createUUID() { return UUID.randomUUID().toString(); }
Source:
private PRPAIN201306UV02 sendToAdapter(PRPAIN201305UV02 request, AssertionType assertion) throws PatientDiscoveryException { AdapterPatientDiscoveryProxy proxy = adapterFactory.create(); START return proxy.respondingGatewayPRPAIN201305UV02(request, assertion); END } Simplify this to one line.

Target:
private PRPAIN201306UV02 sendToAdapter(PRPAIN201305UV02 request, AssertionType assertion) throws PatientDiscoveryException { return adapterFactory.create().respondingGatewayPRPAIN201305UV02(request, assertion); }