auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void deleteFromMessageMonitoringDB(final MonitoredMessage trackMessage) { try { MessageMonitoringDAOImpl.getInstance().deleteCompletedMessages(trackMessage); } catch (final MessageMonitoringDAOException ex) { LOG.debug("Error While deleting Message from MessageMonitoring Table: {}", ex); return; } LOG.debug("Completed message deleted."); }

Target:
can we remove return?
Source:
public void viewEvent() { LOG.debug("view-event: begin"); if (null == selectedEvent) { LOG.info("no event selected for view."); HelperUtil.addMessageError(null, "You need to selected an event."); return; } selectedEvent = service.getLogEvent(selectedEvent.getId()); if (StringUtils.isNotBlank(selectedEvent.getDescription())) { selectedEventJson = new JSONObject(selectedEvent.getDescription()); } HelperUtil.execPFShowDialog("wgvDlgViewEventErrorlog"); }

Target:
Fix the error message something like, Select an event to view. Also what is labeled as event on screen, Service or exception? Replace event with appropriate label
Source:
public ErrorLogBean() { try { dropdowns = service.getDropdowns(); } catch (Exception ex) { LOG.error("Error calling service.dropdowns: {}", ex.getMessage(), ex); HelperUtil.addMessageError(null, SERVICE_ERROR); } }

Target:
Don't like catching exception in the constructor. use an init method with @PostConstruct annotation.
Source:
private AdhocQueryResponse respondingGatewayCrossGatewayQuery(AdhocQueryRequest request, AssertionType assertion, NhinTargetCommunitiesType targets) { AdhocQueryResponse response = null; if (targets == null) { targets = new ObjectFactory().createNhinTargetCommunitiesType(); } if (StringUtils.isBlank(targets.getUseSpecVersion())) { targets.setUseSpecVersion("3.0"); } response = outboundDocQuery.respondingGatewayCrossGatewayQuery(request, assertion, targets); return response; }

Target:
can we remove: declare-response, useless-assign and just return the object from the method-call?
Source:
public void errorResponseHasRegistryObjectList() throws Exception { AdapterDocQueryOrchImpl impl = new AdapterDocQueryOrchImpl(); try { impl.respondingGatewayCrossGatewayQuery(null, null); Assert.fail(); } catch (ErrorEventException e) { AdhocQueryResponse response = (AdhocQueryResponse) e.getReturnOverride(); assertNotNull(response.getRegistryObjectList()); assertEquals(0, response.getRegistryObjectList().getIdentifiable().size()); } }

Target:
Optional: no need to throws Exception since you already catch the runtime Exception here
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); throw new ErrorEventException(e, "Unable to call Nhin Doc Data Submission"); } return response; }

Target:
Question: check to see if we log twice.
Source:
public void testGetExecutorPoolSize() { System.out.println("getExecutorPoolSize"); // default Pool Size int expResult = 100; int result = instance.getExecutorPoolSize(); assertEquals(expResult, result); }

Target:
Optional: replace these System out with LOG statements
Source:
public static gov.hhs.fha.nhinc.patientdiscovery.persistence.HibernateUtil getPatientDiscoveryHibernateUtil() { ClassPathXmlApplicationContext context = ClassPathSingleton.CONTEXT; LOG.debug("Memory address getPatientDiscoveryHibernateUtil {}", context.getId()); if (patientDiscoveryHibernateUtil == null) { patientDiscoveryHibernateUtil = context.getBean(NhincConstants.PATIENT_DISCOVERY_HIBERNATE_BEAN, gov.hhs.fha.nhinc.patientdiscovery.persistence.HibernateUtil.class); } return patientDiscoveryHibernateUtil; }

Target:
Do we need this?
Source:
public void addPatientCorrelationPLQ(PatientLocationQueryResponseType plqRecords, AssertionType assertion) { if (plqRecords == null) { LOG.warn("PLQRecords was null"); } try { PatientCorrelationPLQHelper.addPatientCorrelationPLQRecords(plqRecords); } catch (final Exception ex) { LOG.error("Error calling addPatientCorrelation: {}", ex.getMessage(), ex); } }

Target:
Dont catch generic exceptions. Narrow it down to something specific.
Source:
public AdapterPatientLocationQuerySecuredResponseType adapterPatientLocationQuerySecured( AdapterPatientLocationQuerySecuredRequestType request) { context.toString(); return PatientLocationQueryImpl.getPatientLocationQuery().getAdapterPLQSecuredResponse(request); }

Target:
Do we need this?
Source:
private static List<String> buildDescritpion(BusinessEntity entity) { List<String> descList = new ArrayList<>(); if (null != entity && CollectionUtils.isNotEmpty(entity.getDescription())) { for (Description obj : entity.getDescription()) { descList.add(obj.getValue()); } } return descList; }

Target:
I feel the isNotEmpty() check is not needed here. The for loop will take care of this case.
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:
![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)
Source:
private static boolean isOverrideExchange(ExchangeType exchange) { return null != exchange.getOrganizationList() && CollectionUtils.isNotEmpty(exchange.getOrganizationList().getOrganization()) && StringUtils.isNotEmpty(exchange.getType()) && StringUtils.equalsIgnoreCase( EXCHANGE_TYPE.OVERRIDES.toString(), exchange.getType()); }

Target:
Optional: No need to do StringUtils.isNotEmpty(exchange.getType()) since StringUtils.equalsIgnoreCase can handle null if exchange.getType()=null
Source:
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()); }

Target:
wonder if we can put (null !=exchange) to make reading more easier? If not, don't worry.
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); configCNCheck(); }

Target:
remove this method
Source:
public String getDefaultExchange() { return exInfo.getDefaultExchange(); }

Target:
need null-checked here
Source:
public List<ExchangeType> getExchanges() { exchanges = exchangeService.getAllExchanges(); return exchanges; }

Target:
we should return exchangeService.getAllExchanges(); instead of assigned and return
Source:
private List<CertificateDTO> listKeyStore(String portName) throws CertificateManagerException { ListKeyStoresRequestMessageType message = new ListKeyStoresRequestMessageType(); ConfigAssertionType assertion = buildConfigAssertion(getKeyStorePassKey()); 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()); }

Target:
No need for password/hash for listKeystore/listTrustStore
Source:
private static boolean isHashTokenEmpty() { return StringUtils.isBlank(getHashTokenFromSession()) ? true : false; }

Target:
remove "?true:false". It is unnecessary
Source:
public static OrganizationType findOrganizationTypeBy(List<OrganizationType> organizations, String hcid) { if (CollectionUtils.isEmpty(organizations)) { return null; } if (StringUtils.isBlank(hcid)) { return organizations.get(0); } for (OrganizationType organization : organizations) { if (equalsIgnoreCaseForHCID(hcid, organization.getHcid())) { return organization; } } return null; }

Target:
Please elaborate why we are returning an organization when hcid is blank
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:
removed Line: 278 and 279 - this already being done in the HelperUtil.updateDocumentBy
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:
check-actionResult before updateDocumentWith
Source:
public List<Patient> getCachePatients() { if (null == cachePatients) { getAllPatients(); } return cachePatients; }

Target:
There is no assignment to cachePatients here.
Source:
public List<Phonenumber> getPhonenumbers() { if (isValidPatientId()) { return loadTestDataService.getAllPhonenumbersBy(getPatientId()); } else { return new ArrayList<>(); } }

Target:
A method should have only one return statement instead of two. Use a local variable to get the result and return the local variable.
Source:
private int getKeySize(X509Certificate cert){ PublicKey publicKey = cert.getPublicKey(); if (publicKey instanceof RSAPublicKey){ return ((RSAPublicKey)publicKey).getModulus().bitLength(); } return -1; }

Target:
![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)
Source:
public Address read(Long id) { LOG.debug("AddressDAO.read() - Begin"); 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; }

Target:
Inconsistent log level. Use only one. Stick to trace level for now in this method.
Source:
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()); } return validate; }

Target:
just need log.warn("msg {}", ex.getLocalizedMessage(),ex);
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:
These 2 if conditions and log statements are unnecessary. We can rew3ord and write these log statement in OpenSaml2Builder.createEvidenceStatements method.
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:
Unneeded local variable, just put the constant value into the method a couple lines below.
Source:
public static String checkPrefixBeforeAppend(final String checkValue, final String checkPrefix) { final String tempValue = checkValue.toLowerCase(); final String tempPrefix = checkPrefix.toLowerCase(); if(tempValue.indexOf(tempPrefix) == -1){ return MessageFormat.format("{0}{1}", checkPrefix, checkValue); } else { return checkValue; } }

Target:
use startsWith instead of indexOf. indexOf will return position even if the communityId is defined as 67i8urn:oid
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:
This is where the if statement should be for checking the property for allowing for corrected times.
Source:
public void configure() { super.configure(); HTTPConduit conduit = getHttpConduit(); TLSClientParameters tlsCP = tlsClientFactory.getTLSClientParameters(); conduit.setTlsClientParameters(tlsCP); }

Target:
Use inline method call over here.
Source:
private static String getPropertiesUpdateMessage(String msg, String key, String oldValue, String newValue) { StringBuilder buffer = new StringBuilder(); buffer.append(msg); buffer.append(key); buffer.append(" from "); buffer.append(oldValue); buffer.append(" to "); buffer.append(newValue); buffer.append("."); return buffer.toString(); }

Target:
optional: use buffer.append(msg).append(key).append("...")
Source:
public void onDirectTabChange(TabChangeEvent tEvent) { Tab selectedTab = tEvent.getTab(); if (selectedTab.getId().equalsIgnoreCase(DIRECTDOMAINTAB)) { directTabIndex = 0; } else if (selectedTab.getId().equalsIgnoreCase(DIRECTAGENTTAB)) { directTabIndex = 1; } else if (selectedTab.getId().equalsIgnoreCase(DIRECTCERTTAB)) { directTabIndex = 2; } else { directTabIndex = 3; } }

Target:
Optional: use DIRECTDOMAINTAB.equalsIgnoreCase(selectedTab.getId()) to prevent NPE if second operator is null
Source:
public CXFSAMLCallbackHandler(final HOKSAMLAssertionBuilder builder) { this.builder = builder; accessor = PropertyAccessor.getInstance(); }

Target:
To prevent code duplication, would it be possible to change the body of this constructor to the following? 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); return errorBuilder.toString(); }

Target:
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(); ```
Source:
private boolean hasKeepAliveForConnection() { String keepAlive = assertion.getKeepAlive(); if (NullChecker.isNullish(keepAlive)) { keepAlive = getKeepAliveProperty(); } return NullChecker.isNotNullish(keepAlive) && (keepAlive.equalsIgnoreCase("TRUE") || keepAlive.equalsIgnoreCase("T")); }

Target:
![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)
Source:
private 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; } }

Target:
![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)
Source:
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 != null && (messageContext instanceof WrappedMessageContext)) { readHttpHeaders(messageContext, assertion); } } } catch (PropertyAccessException ex) { LOG.warn("Unable to access property for reading HTTP headers.", ex); } }

Target:
remove !=null since null instanceof WrappedMessageContext will return false
Source:
protected long getTimeStampFutureTTL() { try { return PropertyAccessor.getInstance().getPropertyLong(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.TIMESTAMP_FUTURE_TIME_TO_LIVE); } catch (PropertyAccessException pae) { LOG.warn("Failed to determine timestamp future TTL in gateway.properties, will use default value: {}", pae.getLocalizedMessage()); LOG.trace("Get Timestamp future TTL exception: {}", pae.getLocalizedMessage(), pae); } return INVALID_LONG_VALUE; }

Target:
consider to use warn or trace. It doesn't make sense to log twice with different message
Source:
private static boolean checkDistinguishedName(final String userName) { 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; }

Target:
do we need to use static on this private method? Please update javac doc
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); } catch (org.opensaml.security.SecurityException | org.apache.wss4j.common.ext.WSSecurityException e) { LOG.error(e.getLocalizedMessage(), e); throw new SAMLComponentBuilderException(e.getLocalizedMessage(), e); } return keyInfo; }

Target:
Why are we not importing these classes at the top of the file?
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:
This could just be: 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:
Same here, why public?
Source:
private void sanitizeInput(final String value) throws SanitizationException { try { CleanResults result = antiSamy.scan(value); List<String>errorMsgList = result.getErrorMessages(); if (CollectionUtils.isNotEmpty(errorMsgList)) { throw new SanitizationException("Malicious code has been detected on the HTTP header"); } } catch (ScanException | PolicyException | SanitizationException ex) { throw new SanitizationException(ex); } }

Target:
No need to define errorMsgList. you can use inline here.
Source:
public static void closeSession(Session session) { if (session != null) { try { session.close(); } catch (Exception e) { LOG.error("Failed to close session: ", e); } } else { LOG.warn("Session is null, cannot close"); } }

Target:
Do we need this else block?
Source:
public List<QualifiedPatientIdentifier> retrievePatientCorrelation( QualifiedPatientIdentifier qualifiedPatientIdentifier, List<String> includeOnlyAssigningAuthorities) { Retriever retriever = new Retriever(); return retriever.retrievePatientCorrelation(qualifiedPatientIdentifier, includeOnlyAssigningAuthorities); }

Target:
we can just make this call inline. new Retriever().retrievePatientCorrelation(qualifiedPatientIdentifier, includeOnlyAssigningAuthorities);
Source:
protected Session getSession() { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); return sessionFactory.openSession(); }

Target:
Can this be reduced to a single line?
Source:
public String clearAuditTabMessageId() { this.relatesTo = null; this.messageId = null; if (this.auditRecordList != null && !auditRecordList.isEmpty()) { this.auditRecordList.clear(); } this.auditMessage = ""; this.auditFound = false; return NavigationConstant.AUDIT_SEARCH_PAGE; }

Target:
Checking for Not null is sufficient here. We don't need to check !auditRecordList.isEmpty() as we are clearing the list.
Source:
public void testLogFindAuditEvents() { System.out.println("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()); }

Target:
This log statement isn't really adding any value (plus it's a system out call....) -- can you remove this?
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:
Do we need the local variable session anywhere? Otherwise, just call getSessionFactory without assigning it to anything.
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:
Instead of assign and return, just return the last statement.
Source:
public void execute(OutboundDocSubmissionDeferredRequestOrchestratable message) { LOG.debug("Begin OutboundDocSubmissionOrchestratableImpl_g0.process"); NhinDocSubmissionDeferredRequestProxy nhincDocSubmission = getNhinDocSubmissionDeferredRequestProxy(); XDRAcknowledgementType response = nhincDocSubmission.provideAndRegisterDocumentSetBRequest11( message.getRequest(), message.getAssertion(), message.getTarget()); message.setResponse(response); LOG.debug("End OutboundDocSubmissionDeferredRequestStrategyImpl_g0.process"); }

Target:
As you are touching this code base, can you remove this logging statement at the beginning and exiting the method
Source:
public static String getHomeCommunityIdFromAssertion(AssertionType assertion) { String homeCommunity = null; try { if (NullChecker.isNotNullish(assertion.getHomeCommunity().getHomeCommunityId())) { homeCommunity = assertion.getHomeCommunity().getHomeCommunityId(); } } catch (NullPointerException ex) { LOG.warn("Could not obtain HCID from HomeCommunity in assertion.", ex); } return homeCommunity; }

Target:
Remove the NullPointerException catch statement and rewrite with a Null check.
Source:
public MCCIIN000002UV01 processPatientDiscoveryAsyncReq(RespondingGatewayPRPAIN201305UV02SecuredRequestType request) { AssertionType assertion = getAssertion(context, null); return outboundPatientDiscoveryRequest.processPatientDiscoveryAsyncReq(request.getPRPAIN201305UV02(), assertion, request.getNhinTargetCommunities(), getWebContextProperties(context)); }

Target:
Can you explain why does Entity Outbound requires WebContextProperties for PatientDiscoveryDeferredRequest service?
Source:
public static boolean isNotNullishIgnoreSpace(String value) { return (value != null && !value.trim().isEmpty()); }

Target:
Unnecessary parens around return value.
Source:
private static II getLivingSubjectId(PRPAMT201306UV02LivingSubjectId id) { II oII = null; if (id != null && id.getValue() != null) { oII = id.getValue().get(0); } return oII; }

Target:
Should getValue() be tested for emptiness as well, due to subsequent .get(0)?
Source:
private static PRPAMT201306UV02LivingSubjectId createSubjectId(II subjectId) { PRPAMT201306UV02LivingSubjectId id = new PRPAMT201306UV02LivingSubjectId(); if (subjectId != null) { id.getValue().add(subjectId); } return id; }

Target:
If subjectId is null, should we return a blank PRPAMT201306UV02LivingSubjectId, or null?
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); return (maps.getReplyTo().getAddress().getValue()); }

Target:
Unnecessary parens around the return value.
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(); return marshaller; } catch (JAXBException ex) { LOG.error("JAXB Marshall error : " + ex.getMessage(), ex); } return marshaller; }

Target:
This return is redundant and should be removed
Source:
protected QName getQname(String nameSpaceURI, String localPart) { QName xmlQname = null; xmlQname = new QName(nameSpaceURI, localPart); return xmlQname; }

Target:
This function should be a single line (inline return).
Source:
private JAXBElement<RegistryObjectType> createIdentifiable(RegistryObjectType registryObjectType) { JAXBElement<RegistryObjectType> i = new JAXBElement<>(new QName( "urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0", "Identifiable"), RegistryObjectType.class, registryObjectType); return i; }

Target:
Don't create and immediately return, do the return in-line.
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()); } else { LOG.error("Error looking into EJB JNDI Object"); } LOG.trace("--- After auditing of request message ---"); }

Target:
You already log an error if JNDI lookup fails, as part of getAuditLogger() -- do we need this else statement?
Source:
protected String createUUID() { return (UUID.randomUUID().toString()); }

Target:
Unnecessary parentheses (and an extra line break).
Source:
private PRPAIN201306UV02 sendToAdapter(PRPAIN201305UV02 request, AssertionType assertion) throws PatientDiscoveryException { AdapterPatientDiscoveryProxy proxy = adapterFactory.create(); return proxy.respondingGatewayPRPAIN201305UV02(request, assertion); }

Target:
Simplify this to one line.
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:
You line wrap MUCH later a couple lines down; should this wrap later on this line, or wrapped earlier down below?
Source:
public String getToken() throws NoSuchAlgorithmException { createToken(); return token; }

Target:
hmm. Don't think this should just throw the exception but don't know a better way of handling this. since this should be a fatal error.
Source:
public String getToken() { createToken(); if (token != null) { return token; } return null; }

Target:
This function should be simplified to: createToken(); return token;
Source:
private String getSenderEmailId(MimeMessage message) throws MessagingException { InternetAddress sender = (InternetAddress) message.getSender(); if (sender == null) { InternetAddress[] fromAddresses = (InternetAddress[]) message.getFrom(); sender = fromAddresses[0]; } return (sender.getAddress()); }

Target:
Has "message" been null checked before this point? Also, is there a guarantee that the fromAddresses length will be greater than 0?
Source:
private boolean getDirectTestFlag(String fileName, String property) { boolean directTestFlag = false; String directTestingFlag = getDirectTestingParam(fileName, property); if (directTestingFlag.equals("true")) { directTestFlag = true; } return directTestFlag; }

Target:
Need to check if the directTestingFlag is null.
Source:
public String getDocumentId() { return (documentId == null) ? URI : documentId; }

Target:
"URI" should be lowercase
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:
Any logging that is just "begin" and "end" statements should really just be trace. Apply to all subsequent uses in pr.
Source:
protected List<PRPAIN201306UV02MFMIMT700711UV01Subject1> getSubjects(PRPAIN201306UV02 response) { List<PRPAIN201306UV02MFMIMT700711UV01Subject1> subjects = null; if (response != null && response.getControlActProcess() != null) { subjects = response.getControlActProcess().getSubject(); } return subjects; }

Target:
Only a suggestion, but anytime you have a function that will return a Collection, consider initializing as empty instead of null unless there's a compelling reason otherwise -- this allows callers to run the result through an enhanced for loop (or similar) without requiring a null check.
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:
These debug statements should either be changed to trace or removed.
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:
remove this return statement, it's redundant.
Source:
public void deleteAddress() { List<Address> addresses = selectedDomain.getAddress(); for (int i = 0; i < addresses.size(); i++) { if (addresses.get(i).getEmailAddress().equals(getEmailAddress())) { addresses.remove(i); } } UpdateDomain updateDomain = new UpdateDomain(); updateDomain.setDomain(selectedDomain); directService.updateDomain(updateDomain); }

Target:
You should break out of the for loop once the address is found.
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:
where's your @override?
Source:
private void display(String message, int lengthMillis) { if (contextIsStillAlive()) { Toast toast = Toast.makeText(context, message, lengthMillis); toast.show(); toasts.add(toast); } else { Log.e("Couldn't toast, context has become null. Attempted message: " + message); } }

Target:
I would add then show, means later you could add , then something else could show
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:
`name` não é um bom nome de variável. Acho que oc erto aqui seria value ou cep mesmo, que acha?
Source:
public void boletoNaoDeveAceitarDescricaoNula() { Boleto b = Boleto.novoBoleto(); b.comDescricao(""); }

Target:
Não deveria ser null aqui?
Source:
public void getParts() { Iterator<DoubleSegment> edges = RECTANGLE.getParts().iterator(); assertEquals(TOP_EDGE, edges.next()); assertEquals(LEFT_EDGE, edges.next()); assertEquals(RIGHT_EDGE, edges.next()); assertEquals(BOTTOM_EDGE, edges.next()); assertFalse(edges.hasNext()); }

Target:
I would use something like assertEquals(Arrays.asList(...), edges)
Source:
public void internalMapFailure() { Async<Integer> failure = Asyncs.failure(new Throwable()); Async<Integer> mapped = Asyncs.map(failure, new Function<Integer, Integer>() { @Override public Integer apply(Integer input) { return input + 1; } }, new SimpleAsync<Integer>()); assertThat(mapped, AsyncMatchers.<Integer>failed()); }

Target:
As far as I understand, we can get rid of explicit type parameters is such calls
Source:
List<CompositeT> allBetween(CompositeT from, CompositeT to) { List<CompositeT> res = new ArrayList<>(); res.add(from); if (to != from) { includeClosed(from, to, res); } return res; }

Target:
I think it is better to exclude "from" and "to" objects from resulting list
Source:
boolean includeClosed(CompositeT left, CompositeT to, List<CompositeT> res) { for (CompositeT next = left.nextSibling(); next != null; next = next.nextSibling()) { if (includeOpen(next, to, res)) { return true; } } if (left.getParent() == null) { throw new IllegalArgumentException("Right bound not found in left's bound hierarchy. to=" + to); } return includeClosed(left.getParent(), to, res); }

Target:
First, it is better to assert something in the beginning on the method. Second, left may be root in the first call of this method , I think.
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:
I agree with the other changes, but not sure in this case. Is this really more optimal than the previous version?
Source:
public void visitCtYieldStatement(CtYieldStatement statement) { String foo = ""; }

Target:
to be removed
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:
how about https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equalsIgnoreCase(java.lang.String) instead of `equals`?
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:
Is it recursive call to setContent which calls defineCommentContent, which calls setContent ... ? I have not checked it deeper I just do not understand it on first sight.
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:
Set is a subtype of Collection so only the second part is necessary ```suggestion if (Collection.class.isAssignableFrom(valueClass)) { ```
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:
Thank you, it is really better now. Would not it be even easier, if there would be only one `if` and longer condition?
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:
`if (metadata != null && metadata.size() > 0) ...` WDYT?
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:
`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:
Do we want to print this warning A) only once B) for each call ... to fill the log by these warnings? I vote for A) ... then add `this.noclasspath = true`
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:
We already call `clear` below in the method: this could now be simlified by just adding a if not null around the final `addAll`
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:
This change: - is good for explicit behavior - is bad for concise API (must always delete in parent before intercession) - will break a lot of client code (it already breaks the test code, see the changes in `src/test`) I would prefer to revert it, so that it remains fully backward compatible, and that while keeping the other awesome advantages of the rest of this PR. WDYT?
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:
I guess this code does not work for `Set` since beginning, because you cannot assure that elements in 2 Sets are iterated in consistent pairs. I wonder why it works ... WDYT?
Source:
public boolean addModule(CtModule module) { if (allModules.containsKey(module.getSimpleName())) { return false; } allModules.put(module.getSimpleName(), module); return true; }

Target:
I see one more problem. Later call of CtModule.setSimpleName(...) will cause inconsistency in modules, because the module is registered under old name. May be we should store modules as List<CtModule> and `getModule` should always search that list by name. Then you can add the module into that list sooner directly in `factory.Core().createModule()` call - at time when it has no name. WDYT?
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:
May be we can mark setParent here as Derived property and ignore call of setParent here? I guess there is no case when somebody should be able to set different parent then `unnamedModule`...
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:
Not that, because in our case we can be sure that thisMethod belongs to sub class and thatMethod belongs to super class. So origin code is OK
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:
It seems that the class Substitute also use the `SubstitutionVisitor.scan()` usage you let it as it is on purpose or is it a miss?
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:
null check after
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:
are your sure hashCode/equals of SpoonFile are correct? I'm not sure they are well tested.
Source:
public void setBinaryOutputDirectory(File outputDirectory) { modelBuilder.setBinaryOutputDirectory(outputDirectory); getFactory().getEnvironment().setBinaryOutputDirectory(outputDirectory.getAbsolutePath()); }

Target:
Do not duplicate the information. You can use the environment in the in the model builder.
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:
remove change cf scan problem
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:
This can be false if the String API changes in the next version of Java.