auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public VariableDeclarationExpr(final Type type, VariableDeclarator var) { setType(type); List<VariableDeclarator> vars = new ArrayList<>(); vars.add(var); START setVars(vars); END } Why not using Arrays.asList(var) ? or asList(var) with Arrays.asList in a static import

Target:
public VariableDeclarationExpr(final Type type, VariableDeclarator var) { setType(type); setVars(Arrays.asList(var)); }
Source:
public Position withColumn(int column) { START return new Position(line, column); END } should we use "this" on line to make more evident what we are doing

Target:
public Position withColumn(int column) { return new Position(this.line, column); }
Source:
private DB selectDatabase(Mongo mongo) { DB db = mongo.getDB(dbName); // MongoDB defaults are insane, set a reasonable write concern explicitly. MK. // But we would be insane not to override this when writing lock records. LB. db.setWriteConcern(WriteConcern.JOURNALED); if (username != null) { if(authDbName != null) { // authentificating to db which gives access to all other dbs (role - readWriteAnyDatabase) // by default in mongo it should be "admin" START DB authDb = mongo.getDB(authDbName) END authDb.authenticate(username, password.toCharArray()); } else { db.authenticate(username, password.toCharArray()); } } return db; } A missing semicolon [causes the project fail to compile](https://travis-ci.org/michaelklishin/quartz-mongodb/jobs/16463278).

Target:
private DB selectDatabase(Mongo mongo) { DB db = mongo.getDB(dbName); // MongoDB defaults are insane, set a reasonable write concern explicitly. MK. // But we would be insane not to override this when writing lock records. LB. db.setWriteConcern(WriteConcern.JOURNALED); if (username != null) { if(authDbName != null) { // authentificating to db which gives access to all other dbs (role - readWriteAnyDatabase) // by default in mongo it should be "admin" DB authDb = mongo.getDB(authDbName); authDb.authenticate(username, password.toCharArray()); } else { db.authenticate(username, password.toCharArray()); } } return db; }
Source:
public synchronized RegisteredService save(final RegisteredService registeredService, final boolean publishEvent) { publishEvent(new CasRegisteredServicePreSaveEvent(this, registeredService)); START var r = this.serviceRegistry.save(registeredService); END this.services.put(r.getId(), r); saveInternal(registeredService); if (publishEvent) { publishEvent(new CasRegisteredServiceSavedEvent(this, r)); } return r; } Is this change needed?

Target:
public synchronized RegisteredService save(final RegisteredService registeredService, final boolean publishEvent) { publishEvent(new CasRegisteredServicePreSaveEvent(this, registeredService)); val r = this.serviceRegistry.save(registeredService); this.services.put(r.getId(), r); saveInternal(registeredService); if (publishEvent) { publishEvent(new CasRegisteredServiceSavedEvent(this, r)); } return r; }
Source:
public ListFactoryBean ldapPasswordSynchronizationAuthenticationPostProcessorListFactoryBean() { val bean = new ListFactoryBean() { @Override protected void destroyInstance(final List list) { list.forEach(Unchecked.consumer(postProcessor -> { ((DisposableBean) postProcessor).destroy(); })); } }; START bean.setSourceList(new ArrayList()); END return bean; } ```suggestion bean.setSourceList(new ArrayList<>()); ```

Target:
public ListFactoryBean ldapPasswordSynchronizationAuthenticationPostProcessorListFactoryBean() { val bean = new ListFactoryBean() { @Override protected void destroyInstance(final List list) { list.forEach(Unchecked.consumer(postProcessor -> ((DisposableBean) postProcessor).destroy() )); } }; bean.setSourceList(new ArrayList<>()); return bean; }
Source:
private void revokeToken(final OAuth20RefreshToken token) { LOGGER.debug("Revoking token [{}]", token); getOAuthConfigurationContext().getTicketRegistry().deleteTicket(token); token.getAccessTokens().forEach(item-> { LOGGER.debug("Revoking Access Token related to Refresh Token [{}]", item, token); START getOAuthConfigurationContext().getTicketRegistry().deleteTicket(item); END }); } Remove log line, Call `revokeToken` instead in a lambda to avoid duplicate code.

Target:
private void revokeToken(final OAuth20RefreshToken token) { revokeToken(token.getId()); token.getAccessTokens().forEach(item-> { revokeToken(item); }); }
Source:
protected boolean clientNeedAuthentication(final HttpServletRequest request, final HttpServletResponse response) { val clientId = OAuth20Utils.getClientIdAndClientSecret(new JEEContext(request, response, sessionStore)).getLeft(); START val registeredService = OAuth20Utils.getRegisteredOAuthServiceByClientId(servicesManager, clientId); END if (clientId.isEmpty() || registeredService == null) { return true; } return OAuth20Utils.doesServiceNeedAuthentication(registeredService); } If client-id is undefined, return immediately and do not look up the service in registry.

Target:
protected boolean clientNeedAuthentication(final HttpServletRequest request, final HttpServletResponse response) { val clientId = OAuth20Utils.getClientIdAndClientSecret(new JEEContext(request, response, sessionStore)).getLeft(); if (clientId.isEmpty()) { return true; } val registeredService = OAuth20Utils.getRegisteredOAuthServiceByClientId(servicesManager, clientId); if (registeredService == null) { return true; } return OAuth20Utils.doesServiceNeedAuthentication(registeredService); }
Source:
protected ProxyGrantingTicket produceTicketWithAdequateExpirationPolicy( final RegisteredServiceProxyGrantingTicketExpirationPolicy servicePgtPolicy, final ServiceTicket serviceTicket, final Authentication authentication, final String pgtId) { if (servicePgtPolicy != null) { LOGGER.trace("Overriding proxy-granting ticket policy with the specific policy: [{}]", servicePgtPolicy); return serviceTicket.grantProxyGrantingTicket(pgtId, authentication, new HardTimeoutExpirationPolicy(servicePgtPolicy.getMaxTimeToLiveInSeconds())); START } else { LOGGER.trace("Using default ticket-granting ticket policy for proxy-granting ticket"); return serviceTicket.grantProxyGrantingTicket(pgtId, authentication, this.ticketGrantingTicketExpirationPolicy.buildTicketExpirationPolicy()); } END } ```suggestion } LOGGER.trace("Using default ticket-granting ticket policy for proxy-granting ticket"); return serviceTicket.grantProxyGrantingTicket(pgtId, authentication, this.ticketGrantingTicketExpirationPolicy.buildTicketExpirationPolicy()); ```

Target:
protected ProxyGrantingTicket produceTicketWithAdequateExpirationPolicy( final RegisteredServiceProxyGrantingTicketExpirationPolicy servicePgtPolicy, final ServiceTicket serviceTicket, final Authentication authentication, final String pgtId) { if (servicePgtPolicy != null) { LOGGER.trace("Overriding proxy-granting ticket policy with the specific policy: [{}]", servicePgtPolicy); return serviceTicket.grantProxyGrantingTicket(pgtId, authentication, new HardTimeoutExpirationPolicy(servicePgtPolicy.getMaxTimeToLiveInSeconds())); } LOGGER.trace("Using default ticket-granting ticket policy for proxy-granting ticket"); return serviceTicket.grantProxyGrantingTicket(pgtId, authentication, this.ticketGrantingTicketExpirationPolicy.buildTicketExpirationPolicy()); }
Source:
public void onEvent(final CacheEvent<? extends String, ? extends Ticket> event) { START if (LOGGER.isTraceEnabled()) { END LOGGER.trace("Event Type: {}, Ticket Id: {}", event.getType().name(), event.getKey()); } } The if condition here should be unnecessary unless `event.getXyz()` calls are expensive?

Target:
public void onEvent(final CacheEvent<? extends String, ? extends Ticket> event) { LOGGER.trace("Event Type: {}, Ticket Id: {}", event.getType().name(), event.getKey()); }
Source:
START void verifyGroovyResourceClasspathExecution() { END try { val resource = new ClassPathResource("ScriptingUtilsTestGroovyScript.groovy"); val result = ScriptingUtils.executeGroovyScript(resource, "process", String.class, "casuser"); assertEquals("casuser", result); } catch (final Exception e) { throw new AssertionError(e.getMessage(), e); } } `() throws Exception`

Target:
public void verifyGroovyResourceClasspathExecution() { val resource = new ClassPathResource("ScriptingUtilsTestGroovyScript.groovy"); val result = ScriptingUtils.executeGroovyScript(resource, "process", String.class, "casuser"); assertEquals("casuser", result); }
Source:
public static RedisConnectionFactory newRedisConnectionFactory(final BaseRedisProperties redis) { LOGGER.debug("Loaded Redis configuration {}", redis); START final RedisConfiguration redisConfiguration = redis.getSentinel() == null END ? getStandaloneConfig(redis) : getSentinelConfig(redis); val factory = new LettuceConnectionFactory(redisConfiguration, getRedisPoolConfig(redis)); return factory; } Use `val` or `var`?

Target:
public static RedisConnectionFactory newRedisConnectionFactory(final BaseRedisProperties redis) { val redisConfiguration = redis.getSentinel() == null ? (RedisConfiguration) getStandaloneConfig(redis) : getSentinelConfig(redis); val factory = new LettuceConnectionFactory(redisConfiguration, getRedisPoolConfig(redis)); return factory; }
Source:
public void createX509Credential() throws IOException, CertificateException { val request = new MockHttpServletRequest(); try (val inStream = new FileInputStream(new ClassPathResource("ldap-crl.crt").getFile())) { START X509Certificate[] certs = {CertUtils.readCertificate(inStream)}; END request.setAttribute(REQUEST_ATTRIBUTE_X509_CERTIFICATE, certs); val cred = factory.fromRequest(request, null).iterator().next(); assertTrue(cred instanceof X509CertificateCredential); } } val?

Target:
public void createX509Credential() throws IOException, CertificateException { val request = new MockHttpServletRequest(); try (val inStream = new FileInputStream(new ClassPathResource("ldap-crl.crt").getFile())) { val certs = new X509Certificate[]{CertUtils.readCertificate(inStream)}; request.setAttribute(REQUEST_ATTRIBUTE_X509_CERTIFICATE, certs); val cred = factory.fromRequest(request, null).iterator().next(); assertTrue(cred instanceof X509CertificateCredential); } }
Source:
public String decodeSamlAuthnRequest(final String encodedRequestXmlString) { if (StringUtils.isEmpty(encodedRequestXmlString)) { return null; } final byte[] decodedBytes = EncodingUtils.decodeBase64(encodedRequestXmlString); if (decodedBytes == null) { return null; } final String inflated = CompressionUtils.inflate(decodedBytes); if (!StringUtils.isEmpty(inflated)) { return inflated; START } else { END return new String(decodedBytes, StandardCharsets.UTF_8); } } This is fine, but the else clause is redundant here.

Target:
public String decodeSamlAuthnRequest(final String encodedRequestXmlString) { if (StringUtils.isEmpty(encodedRequestXmlString)) { return null; } final byte[] decodedBytes = EncodingUtils.decodeBase64(encodedRequestXmlString); if (decodedBytes == null) { return null; } final String inflated = CompressionUtils.inflate(decodedBytes); if (!StringUtils.isEmpty(inflated)) { return inflated; } return new String(decodedBytes, StandardCharsets.UTF_8); }
Source:
protected void createDefaultEndStates(final Flow flow) { createRedirectUnauthorizedServiceUrlEndState(flow); createServiceErrorEndState(flow); createRedirectEndState(flow); createPostEndState(flow); createInjectHeadersActionState(flow); createGenericLoginSuccessEndState(flow); createServiceWarningViewState(flow); START createMfaDeniedViewState(flow); END createMfaUnavailableViewState(flow); createEndWebflowEndState(flow); } Does this really belong here? I think a better home would perhaps be the thing that configures the mfa flow in general. It would be best to try to keep the flow defn as _pure_ as possible, and only interject when a feature is actually used.

Target:
protected void createDefaultEndStates(final Flow flow) { createRedirectUnauthorizedServiceUrlEndState(flow); createServiceErrorEndState(flow); createRedirectEndState(flow); createPostEndState(flow); createInjectHeadersActionState(flow); createGenericLoginSuccessEndState(flow); createServiceWarningViewState(flow); createEndWebflowEndState(flow); }
Source:
public static String CreateTmpFile(String fileName) { fileName = isFilenameValid(fileName) ? fileName : KEY_FILENAME; File tempFile = getUniqueFile(fileName); try { tempFile.createNewFile(); } catch (IOException e) { START System.err.println("Error: " + e.getMessage()); END e.printStackTrace(); return ""; } return tempFile.getPath(); } don catch exception, better fail than return ""

Target:
public static String CreateTmpFile(String fileName) throws IOException { fileName = isFilenameValid(fileName) ? fileName : KEY_FILENAME; File tempFile = getUniqueFile(fileName); tempFile.createNewFile(); return tempFile.getPath(); }
Source:
public static File getUniqueFile(String fileName) { File tempFile = null; int i = 0; try { do { tempFile = new File(TMP_DIR + DIR_SEPARATOR + fileName + "-" + i + "." + KEY_FILENAME_EXT); i++; } while (tempFile.exists()); } // Catch exception if any catch (Exception e) { START System.err.println("Error: " + e.getMessage()); END } return tempFile; } dont catch, better fail

Target:
public static File getUniqueFile(String fileName) { File tempFile = null; int i = 0; do { tempFile = new File(TMP_DIR + DIR_SEPARATOR + fileName + "-" + i + "." + KEY_FILENAME_EXT); i++; } while (tempFile.exists()); return tempFile; }
Source:
public boolean equals(EmbeddedServerInfo info) { START if (this.serverName.equals(info.serverName) END && this.userDir.getAbsolutePath().equals(info.userDir.getAbsolutePath()) && this.outputDir.getAbsolutePath().equals(info.outputDir.getAbsolutePath())) { return true; } return false; } Technically I think you should use the get methods on `info` to access its variables.

Target:
public boolean equals(EmbeddedServerInfo info) { return this.serverName.equals(info.serverName) && this.userDir.getAbsolutePath().equals(info.userDir.getAbsolutePath()) && this.outputDir.getAbsolutePath().equals(info.outputDir.getAbsolutePath()); }
Source:
public SRResult similarity(String phrase1, String phrase2, Language language, boolean explanations) throws DaoException { if (phrase1 == null || phrase2 == null) { throw new NullPointerException("Null phrase passed to similarity"); } try { TIntDoubleHashMap scores1 = getConceptVector(phrase1, language); TIntDoubleHashMap scores2 = getConceptVector(phrase2, language); double sim = SimUtils.cosineSimilarity(scores1, scores2); START return new SRResult(sim); // TODO: normalize END } catch (WikapidiaException e) { throw new DaoException(e); } } this should be normalize(new SRResult(sim))

Target:
public SRResult similarity(String phrase1, String phrase2, Language language, boolean explanations) throws DaoException { if (phrase1 == null || phrase2 == null) { throw new NullPointerException("Null phrase passed to similarity"); } TIntDoubleHashMap scores1 = getConceptVector(phrase1, language); TIntDoubleHashMap scores2 = getConceptVector(phrase2, language); double sim = SimUtils.cosineSimilarity(scores1, scores2); return new SRResult(sim); // TODO: normalize }
Source:
public Integer getUriOpenedSockets(String uri) { Integer numberOpenedSockets = 0; START for (WebSocketDispatcher dispatcher : dispatchers) { END numberOpenedSockets += dispatcher.getNumberOpenedSocketsByUri(uri); } return numberOpenedSockets; } need to be protected against concurrent accesses

Target:
public Integer getUriOpenedSockets(String uri) { Integer numberOpenedSockets = 0; synchronized (this) { for (WebSocketDispatcher dispatcher : dispatchers) { numberOpenedSockets += dispatcher.getNumberOpenedSocketsByUri(uri); } } return numberOpenedSockets; }
Source:
public Map<String, Integer> getNumberOpenedSockets() { Map<String, Integer> numberOpenedSocketByUri = new LinkedHashMap<>(); START for (Map.Entry<String, List<Socket>> socketByUri : socketsByUri.entrySet()) { END numberOpenedSocketByUri.put(socketByUri.getKey(), socketByUri.getValue().size()); } return numberOpenedSocketByUri; } must be protected against concurrent accesses

Target:
public Map<String, Integer> getNumberOpenedSockets() { Map<String, Integer> numberOpenedSocketByUri = new LinkedHashMap<>(); synchronized (this) { for (Map.Entry<String, List<Socket>> socketByUri : socketsByUri.entrySet()) { numberOpenedSocketByUri.put(socketByUri.getKey(), socketByUri.getValue().size()); } } return numberOpenedSocketByUri; }
Source:
public Integer getNumberOpenedSocketsByUri(String uri) { Integer numberOpenedSocketForUri = 0; START if (socketsByUri.containsKey(uri)) { END numberOpenedSocketForUri = socketsByUri.get(uri).size(); } return numberOpenedSocketForUri; } concurrency issue too

Target:
public Integer getNumberOpenedSocketsByUri(String uri) { Integer numberOpenedSocketForUri = 0; synchronized (this) { if (socketsByUri.containsKey(uri)) { numberOpenedSocketForUri = socketsByUri.get(uri).size(); } } return numberOpenedSocketForUri; }
Source:
public static Organization createDtoFromDbo(DBOOrganization dbo) { Organization dto = new Organization(); START dto.setCreatedBy("" + dbo.getCreatedBy()); END dto.setCreatedOn(dbo.getCreatedOn()); dto.setId(""+dbo.getId()); dto.setName(dbo.getName()); return dto; } String.valueOf

Target:
public static Organization createDtoFromDbo(DBOOrganization dbo) { Organization dto = new Organization(); dto.setCreatedBy(dbo.getCreatedBy().toString()); dto.setCreatedOn(dbo.getCreatedOn()); dto.setId(dbo.getId().toString()); dto.setName(dbo.getName()); return dto; }
Source:
public static String createFlagIssue(JiraClient jiraClient, String principalId, String displayName, String dataObjectId) { Map<String,String> params = new HashMap<String,String>(); params.put(JIRA_PRINCIPAL_ID_ISSUE_FIELD_NAME, principalId); params.put(JIRA_USER_DISPLAY_NAME_ISSUE_FIELD_NAME, displayName); params.put(JIRA_SYNAPSE_ENTITY_ID_FIELD_NAME, dataObjectId); CreatedIssue createdIssue = createIssue(jiraClient, JIRA_FLAG_ISSUE_TYPE_NAME, FLAG_SUMMARY, params); START return (String) createdIssue.getKey(); END } Cast to string can be removed

Target:
public static String createFlagIssue(JiraClient jiraClient, String principalId, String displayName, String dataObjectId) { Map<String,String> params = new HashMap<String,String>(); params.put(JIRA_PRINCIPAL_ID_ISSUE_FIELD_NAME, principalId); params.put(JIRA_USER_DISPLAY_NAME_ISSUE_FIELD_NAME, displayName); params.put(JIRA_SYNAPSE_ENTITY_ID_FIELD_NAME, dataObjectId); CreatedIssue createdIssue = createIssue(jiraClient, JIRA_FLAG_ISSUE_TYPE_NAME, FLAG_SUMMARY, params); return createdIssue.getKey(); }
Source:
public MigratableTableTranslation<DBOVerificationState, DBOVerificationState> getTranslator() { return new BasicMigratableTableTranslation<DBOVerificationState>() { @Override START public DBOVerificationState createDatabaseObjectFromBackup(DBOVerificationState backup) { END if (backup.getEtag() == null) { backup.setEtag(UUID.randomUUID().toString()); } return backup; } }; } remove

Target:
public MigratableTableTranslation<DBOVerificationState, DBOVerificationState> getTranslator() { return new BasicMigratableTableTranslation<>(); }
Source:
public void deleteVerificationSubmission(long verificationId) { wrapSubmissionNotFound(verificationId, () -> { START MapSqlParameterSource param = new MapSqlParameterSource(); END param.addValue(COL_VERIFICATION_SUBMISSION_ID.toLowerCase(), verificationId); basicDao.deleteObjectByPrimaryKey(DBOVerificationSubmission.class, param); return false; }); } not needed here

Target:
public void deleteVerificationSubmission(long verificationId) { MapSqlParameterSource param = new MapSqlParameterSource(); param.addValue(COL_VERIFICATION_SUBMISSION_ID.toLowerCase(), verificationId); basicDao.deleteObjectByPrimaryKey(DBOVerificationSubmission.class, param); }
Source:
public DLNAThumbnailInputStream getThumbnailInputStream() throws IOException { if (thumbURL != null) { return DLNAThumbnailInputStream.toThumbnailInputStream( FileUtil.isUrl(thumbURL) ? downloadAndSend(thumbURL, true) : new FileInputStream(thumbURL) ); } else { try (DLNAThumbnailInputStream dtis = super.getThumbnailInputStream()) { START return dtis; END } } } I am unsure about this one. Before this, we were returning a live stream, and after this we may be returning a closed stream.

Target:
public DLNAThumbnailInputStream getThumbnailInputStream() throws IOException { if (thumbURL != null) { return DLNAThumbnailInputStream.toThumbnailInputStream( FileUtil.isUrl(thumbURL) ? downloadAndSend(thumbURL, true) : new FileInputStream(thumbURL) ); } else { DLNAThumbnailInputStream dtis = super.getThumbnailInputStream(); return dtis; } }
Source:
public static boolean isSupportedMimetype(String mimetype) { boolean supported = true; if ("audio/L24".equalsIgnoreCase(mimetype) || "video/vnd.dlna.mpeg-tts".equalsIgnoreCase(mimetype) || "video/mpeg2".equalsIgnoreCase(mimetype) START || "audio/vnd.dlna.adts".equals(mimetype) END ) supported = false; return supported; } equals ?

Target:
public static boolean isSupportedMimetype(String mimetype) { boolean supported = true; if ("audio/L24".equalsIgnoreCase(mimetype) || "video/vnd.dlna.mpeg-tts".equalsIgnoreCase(mimetype) || "video/mpeg2".equalsIgnoreCase(mimetype) || "audio/vnd.dlna.adts".equalsIgnoreCase(mimetype) ) supported = false; return supported; }
Source:
public boolean isADPCM() { START return getCodecA() != null && getCodecA().equalsIgnoreCase(FormatConfiguration.ADPCM); END } If i remember correctly, getCodecA is now set in lower case so `IgnoreCase` is not need anymore.

Target:
public boolean isADPCM() { return FormatConfiguration.ADPCM.equalsIgnoreCase(getCodecA()); }
Source:
public String[] getSupportedExtensions() { return new String[] { "oga", "ogg", START "oga", END "spx", "opus", }; } @Nadahar Isn't "**oga**" already there ?

Target:
public String[] getSupportedExtensions() { return new String[] { "oga", "ogg", "spx", "opus", }; }
Source:
public void getCapabilitiesGetRequestWorksWithCORS() throws IOException { String url = wpsUrl + "?Service=WPS&Request=GetCapabilities"; method = new GetMethod(url); method.addRequestHeader("Origin", randomOrigin); int code = client.executeMethod(method); assertThat(code, is(equalTo(200))); Header acaoHeader = method.getResponseHeader("Access-Control-Allow-Origin"); START assertThat(acaoHeader.toString(), containsString(randomOrigin.toString())); END } If CORS is not activated, this throws a NPE. I recommend to add an assertNotNull statement.

Target:
public void getCapabilitiesGetRequestWorksWithCORS() throws IOException { String url = wpsUrl + "?Service=WPS&Request=GetCapabilities"; method = new GetMethod(url); method.addRequestHeader("Origin", randomOrigin); int code = client.executeMethod(method); assertThat(code, is(equalTo(200))); Header acaoHeader = method.getResponseHeader("Access-Control-Allow-Origin"); assertNotNull(acaoHeader); assertThat(acaoHeader.toString(), containsString(randomOrigin.toString())); }
Source:
public void describeProcessGetRequestWorksWithCORS() throws IOException { String url = wpsUrl + "?Service=WPS&Request=DescribeProcess&Version=1.0.0&Identifier=" + "org.n52.wps.server.algorithm.test.EchoProcess"; method = new GetMethod(url); method.addRequestHeader("Origin", randomOrigin); int code = client.executeMethod(method); assertThat(code, is(equalTo(200))); Header acaoHeader = method.getResponseHeader("Access-Control-Allow-Origin"); START assertThat(acaoHeader.toString(), containsString(randomOrigin.toString())); END } If CORS is not activated, this throws a NPE. I recommend to add an assertNotNull statement.

Target:
public void describeProcessGetRequestWorksWithCORS() throws IOException { String url = wpsUrl + "?Service=WPS&Request=DescribeProcess&Version=1.0.0&Identifier=" + "org.n52.wps.server.algorithm.test.EchoProcess"; method = new GetMethod(url); method.addRequestHeader("Origin", randomOrigin); int code = client.executeMethod(method); assertThat(code, is(equalTo(200))); Header acaoHeader = method.getResponseHeader("Access-Control-Allow-Origin"); assertNotNull(acaoHeader); assertThat(acaoHeader.toString(), containsString(randomOrigin.toString())); }
Source:
protected String getClassProperty() { START return super.getClassProperty() + ' ' + this.getDescriptor().getId() + "message"; END } The macro might be associated to a specific syntax to it's probably safer to do this.getDescriptor().getId().getId().

Target:
protected String getClassProperty() { return super.getClassProperty() + ' ' + this.getDescriptor().getId().getId() + "message"; }
Source:
private boolean isMetaDataElement(WikiParameters parameters) { if (parameters.getParameter(CLASS_ATTRIBUTE) != null) { return METADATA_CONTAINER_CLASS.equals(parameters.getParameter(CLASS_ATTRIBUTE).getValue()); } START return false; END } This can be written in a single line: return parameters.getParameter(CLASS_ATTRIBUTE) != null && METADATA_CONTAINER_CLASS.equals(parameters.getParameter(CLASS_ATTRIBUTE).getValue());

Target:
private boolean isMetaDataElement(WikiParameters parameters) { return parameters.getParameter(CLASS_ATTRIBUTE) != null && METADATA_CONTAINER_CLASS.equals(parameters.getParameter(CLASS_ATTRIBUTE).getValue()); }
Source:
default Type getType() { START return new DefaultParameterizedType(null, List.class, Block.class); END } The default type should be ``String.class`` I think.

Target:
default Type getType() { return String.class; }
Source:
public boolean equals(Object object) { START if (object == null && object.getClass() != getClass()) { END return false; } if (object == this) { return true; } Syntax rhs = (Syntax) object; return new EqualsBuilder().append(getType(), rhs.getType()).append(getVersion(), rhs.getVersion()) .append(getQualifier(), rhs.getQualifier()).isEquals(); } Since Syntax is not really designed to be extended you would replace this whole if by `if (!(object instanceof Syntax))`. Also I would move it after the `if (object == this)`.

Target:
public boolean equals(Object object) { if (object == this) { return true; } if (!(object instanceof Syntax)) { return false; } Syntax rhs = (Syntax) object; return new EqualsBuilder().append(getType(), rhs.getType()).append(getVersion(), rhs.getVersion()) .append(getQualifier(), rhs.getQualifier()).isEquals(); }
Source:
protected Parser getSyntaxParser(Syntax syntax) throws MacroExecutionException { try { return this.componentManager.getInstance(Parser.class, syntax.toIdString()); } catch (ComponentLookupException e) { START throw new MacroExecutionException(String.format("Cannot find Parser for syntax [%s]", syntax.toIdString()), e); END } } Line too long.

Target:
protected Parser getSyntaxParser(Syntax syntax) throws MacroExecutionException { try { return this.componentManager.getInstance(Parser.class, syntax.toIdString()); } catch (ComponentLookupException e) { throw new MacroExecutionException(String.format("Cannot find Parser for syntax [%s]" + , syntax.toIdString()), e); } }
Source:
public boolean equals(Object object) { START if ((object == null) || (object.getClass() != getClass())) { END return false; } if (object == this) { return true; } MacroId rhs = (MacroId) object; return new EqualsBuilder() .append(getId(), rhs.getId()) .append(getSyntax(), rhs.getSyntax()) .isEquals(); } No need for those parenthesis (they will even produce a Sonar issue).

Target:
public boolean equals(Object object) { if (object == this) { return true; } if (!(object instanceof MacroId)) { return false; } MacroId rhs = (MacroId) object; return new EqualsBuilder() .append(getId(), rhs.getId()) .append(getSyntax(), rhs.getSyntax()) .isEquals(); }
Source:
protected Map<Object, Object> createDestination( MappingContext<Map<?, ?>, Map<Object, Object>> context) { if (context.getDestinationType().isInterface()) { if (SortedMap.class.isAssignableFrom(context.getDestinationType())) { return new TreeMap<Object, Object>(); } return new HashMap<Object, Object>(); } START return context.getMappingEngine().createDestination(context); END } What do you think: ```java if (!context.getDestinationType().isInterface()) return context.getMappingEngine().createDestination(context); if (SortedMap.class.isAssignableFrom(context.getDestinationType())) return new TreeMap<Object, Object>(); return new HashMap<Object, Object>(); ``` to reduce the deeply nested if statement. And we prefer no curly braces if there is only one statement in the if/else as our coding stye.

Target:
protected Map<Object, Object> createDestination( MappingContext<Map<?, ?>, Map<Object, Object>> context) { if (!context.getDestinationType().isInterface()) return context.getMappingEngine().createDestination(context); if (SortedMap.class.isAssignableFrom(context.getDestinationType())) return new TreeMap<Object, Object>(); return new HashMap<Object, Object>(); }
Source:
protected Class<?> findClass(String name) throws ClassNotFoundException { if (name.startsWith("org.modelmapper.internal.cglib")) return internalClassSpace.loadClass(name); for (ClassLoader additionalClassLoader : additionalClassLoaders) { try { return additionalClassLoader.loadClass(name); } START catch (ClassNotFoundException e) // Don't mind... Attempt next class loader END } throw new ClassNotFoundException(); } coding style: ``` try { ... } catch (ClassNotFoundException e) { // Don't mind... Attempt next class loader |

Target:
protected Class<?> findClass(String name) throws ClassNotFoundException { if (name.startsWith("org.modelmapper.internal.cglib")) return internalClassSpace.loadClass(name); for (ClassLoader additionalClassLoader : additionalClassLoaders) { try { return additionalClassLoader.loadClass(name); } catch (ClassNotFoundException e) { // Don't mind... Attempt next class loader } } throw new ClassNotFoundException(name); }
Source:
public boolean isPutIntoOven() throws OvenException { try { final URL url = new URL("https://www.google.com/search?q=potato"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); int inOven = connection.getResponseCode(); return inOven == 200; } catch (IOException ex) { START throw new OvenException(); END } } Should probably include the cause.

Target:
public boolean isPutIntoOven() throws OvenException { try { final URL url = new URL("https://www.google.com/search?q=potato"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); int inOven = connection.getResponseCode(); return inOven == 200; } catch (IOException ex) { throw new OvenException(ex); } }
Source:
Request(HttpMethod method, String url, Map<String, Collection<String>> headers, Body body, RequestTemplate requestTemplate) { this.httpMethod = checkNotNull(method, "httpMethod of %s", method.name()); this.url = checkNotNull(url, "url"); this.headers = checkNotNull(headers, "headers of %s %s", method, url); START this.body = (body != null) ? body : Body.EMPTY; END this.requestTemplate = requestTemplate; } That is going to be a problem... https://github.com/OpenFeign/feign/blob/master/httpclient/src/main/java/feign/httpclient/ApacheHttpClient.java#L135 There are clients out there that change behavior when body is null

Target:
Request(HttpMethod method, String url, Map<String, Collection<String>> headers, Body body, RequestTemplate requestTemplate) { this.httpMethod = checkNotNull(method, "httpMethod of %s", method.name()); this.url = checkNotNull(url, "url"); this.headers = checkNotNull(headers, "headers of %s %s", method, url); this.body = body; this.requestTemplate = requestTemplate; }
Source:
public Options(long connectTimeout, TimeUnit connectTimeoutUnit, long readTimeout, TimeUnit readTimeoutUnit, boolean followRedirects) { super(); this.connectTimeout = connectTimeout; this.connectTimeoutUnit = connectTimeoutUnit; this.readTimeout = readTimeout; this.readTimeoutUnit = readTimeoutUnit; this.followRedirects = followRedirects; START this.allowStreamingMode = true; END } like the idea of defaulting to true

Target:
public Options(long connectTimeout, TimeUnit connectTimeoutUnit, long readTimeout, TimeUnit readTimeoutUnit, boolean followRedirects) { super(); this.connectTimeout = connectTimeout; this.connectTimeoutUnit = connectTimeoutUnit; this.readTimeout = readTimeout; this.readTimeoutUnit = readTimeoutUnit; this.followRedirects = followRedirects; }
Source:
public String expand(Map<String, ?> variables) { String expanded = super.expand(variables); if (this.json) { /* decode only the first and last character */ expanded = expanded.substring( expanded.indexOf(JSON_TOKEN_START_ENCODED) + JSON_TOKEN_START_ENCODED.length()); expanded = JSON_TOKEN_START + expanded; expanded = expanded.substring(0, expanded.lastIndexOf(JSON_TOKEN_END_ENCODED)); START expanded += JSON_TOKEN_END; END } return expanded; } Shouldn't we be using a `StringBuilder` ?

Target:
public String expand(Map<String, ?> variables) { String expanded = super.expand(variables); if (this.json) { /* decode only the first and last character */ StringBuilder sb = new StringBuilder(); sb.append(JSON_TOKEN_START); sb.append(expanded, expanded.indexOf(JSON_TOKEN_START_ENCODED) + JSON_TOKEN_START_ENCODED.length(), expanded.lastIndexOf(JSON_TOKEN_END_ENCODED)); sb.append(JSON_TOKEN_END); return sb.toString(); } return expanded; }
Source:
public String contentUTF8() { if (content != null) { return new String(content, UTF_8); } else { START return null; END } } It may be better to return an empty string here instead of `null`. Unless others look into this code, we may be pushing the null pointer higher. Thoughts?

Target:
public String contentUTF8() { if (content != null) { return new String(content, UTF_8); } else { return ""; } }
Source:
START public Charset charset() { END return (this.encoding != null) ? this.encoding : Util.UTF_8; } Hrmmm, why?! if `encoding` is null usually mean this is a binary protocol

Target:
public Charset charset() { return this.encoding; }
Source:
public Feign build() { if (library == null) { throw new IllegalStateException("A Reactive Streams Library has not been specified"); } START super.contract(new ReactiveDelegatingContract(this.contract)); END super.invocationHandlerFactory(new ReactiveInvocationHandlerFactory(this.library)); return super.build(); } Would recommend checking if contract is an instance of `ReactiveC` and only warp of not

Target:
public Feign build() { if (!(this.contract instanceof ReactiveDelegatingContract)) { super.contract(new ReactiveDelegatingContract(this.contract)); } else { super.contract(this.contract); } return super.build(); }
Source:
START public JAXBContext getContext(Class<?> clazz) throws JAXBException { END JAXBContext jaxbContext = this.jaxbContexts.get(clazz); if (jaxbContext == null) { jaxbContext = JAXBContext.newInstance(clazz); this.jaxbContexts.putIfAbsent(clazz, jaxbContext); } return jaxbContext; } Sorry, how changing visibility makes caching?

Target:
private JAXBContext getContext(Class<?> clazz) throws JAXBException { JAXBContext jaxbContext = this.jaxbContexts.get(clazz); if (jaxbContext == null) { jaxbContext = JAXBContext.newInstance(clazz); this.jaxbContexts.putIfAbsent(clazz, jaxbContext); } return jaxbContext; }
Source:
private void preloadContextCache(List<Class<?>> classes) throws JAXBException { START for (Class<?> clazz : classes) { END getContext(clazz); } } The list can be applied during building: ```java JAXBContextFactory.build(List<Class<?>> classes) ``` Additional classes can then be loaded on demand.

Target:
private void preloadContextCache(List<Class<?>> classes) throws JAXBException { if (classes != null && !classes.isEmpty()) { for (Class<?> clazz : classes) { getContext(clazz); } } }
Source:
START private JacksonIterator(Type type, ObjectMapper mapper, Response response, Reader reader) END throws IOException { this.response = response; this.parser = mapper.getFactory().createParser(reader); this.objectReader = mapper.reader().forType(mapper.constructType(type)); } one thing you'll notice in other feign code is that we infrequently use private access as the modifiers bloat bytecode and sharing packages isn't supported outside feign anyway. if you feel strongly about hiding things, making the type private but default modifiers on the ctor and symbols accomplishes the same.

Target:
JacksonIterator(Type type, ObjectMapper mapper, Response response, Reader reader) throws IOException { this.response = response; this.parser = mapper.getFactory().createParser(reader); this.objectReader = mapper.reader().forType(mapper.constructType(type)); }
Source:
START private Type actualIteratorTypeArgument(Type type) { END if (!(type instanceof ParameterizedType)) { throw new IllegalArgumentException("Not supported type " + type.toString()); } ParameterizedType parameterizedType = (ParameterizedType) type; if (!Iterator.class.equals(parameterizedType.getRawType())) { throw new IllegalArgumentException("Not an iterator type " + parameterizedType.getRawType().toString()); } return ((ParameterizedType) type).getActualTypeArguments()[0]; } looks like this can be static

Target:
private static Type actualIteratorTypeArgument(Type type) { if (!(type instanceof ParameterizedType)) { throw new IllegalArgumentException("Not supported type " + type.toString()); } ParameterizedType parameterizedType = (ParameterizedType) type; if (!Iterator.class.equals(parameterizedType.getRawType())) { throw new IllegalArgumentException("Not an iterator type " + parameterizedType.getRawType().toString()); } return ((ParameterizedType) type).getActualTypeArguments()[0]; }
Source:
START public static String urlEncode(Object arg) { END try { return URLEncoder.encode(String.valueOf(arg), UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } make package private

Target:
static String urlEncode(Object arg) { try { return URLEncoder.encode(String.valueOf(arg), UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Source:
private JAXBDecoder(Builder builder) { START if (builder.jaxbContextFactory == null) { END throw new IllegalStateException("JAXBContextFactory must be non-null"); } this.jaxbContextFactory = builder.jaxbContextFactory; this.namespaceAware = builder.namespaceAware; } Seems like this could go in `build()`.

Target:
private JAXBDecoder(Builder builder) { this.jaxbContextFactory = builder.jaxbContextFactory; this.namespaceAware = builder.namespaceAware; }
Source:
public Response build() { START return Response.create(status, reason, headers, body, request); END } I'd call `new Response(this)`

Target:
public Response build() { return new Response(this); }
Source:
public void reasonPhraseIsOptional() { Response response = Response.builder() .status(200) .reason(null) /* reason phrase */ START .headers(Collections.<String, Collection<String>>emptyMap()) END .body(new byte[0]) .build(); assertThat(response.reason()).isNull(); assertThat(response.toString()).isEqualTo("HTTP/1.1 200\n\n"); } I'd initialize the builder.headers to emptyMap to clear some of this c&p

Target:
public void reasonPhraseIsOptional() { Response response = Response.builder() .status(200) .headers(Collections.<String, Collection<String>>emptyMap()) .body(new byte[0]) .build(); assertThat(response.reason()).isNull(); assertThat(response.toString()).isEqualTo("HTTP/1.1 200\n\n"); }
Source:
private Object expandElements(Expander expander, Object value) { if (value instanceof Iterable) { return expandIterable(expander, (Iterable) value); } else if (value.getClass().isArray()) { START return expandIterable(expander, Arrays.asList((Object[])value)); END } return expander.expand(value); } why are we adding array support?

Target:
private Object expandElements(Expander expander, Object value) { if (value instanceof Iterable) { return expandIterable(expander, (Iterable) value); } return expander.expand(value); }
Source:
private Map<Method, Method> toFallbackMethod(Map<Method, MethodHandler> dispatch) { Map<Method, Method> result = new HashMap<Method, Method>(); for (Map.Entry<Method, MethodHandler> entry : dispatch.entrySet()) { Method key = entry.getKey(); START key.setAccessible(true); END result.put(key, key); } return result; } setAccessible is mutating, so you don't need to save this off

Target:
private Map<Method, Method> toFallbackMethod(Map<Method, MethodHandler> dispatch) { Map<Method, Method> result = new HashMap<Method, Method>(); for (Method method : dispatch.keySet()) { method.setAccessible(true); result.put(method, method); } return result; }
Source:
START public LBClient(ILoadBalancer lb, IClientConfig clientConfig) { END super(lb, clientConfig); this.setRetryHandler(RetryHandler.DEFAULT); this.clientConfig = clientConfig; connectTimeout = clientConfig.get(CommonClientConfigKey.ConnectTimeout); readTimeout = clientConfig.get(CommonClientConfigKey.ReadTimeout); } hide this and expose factory method

Target:
LBClient(ILoadBalancer lb, IClientConfig clientConfig) { super(lb, clientConfig); this.setRetryHandler(RetryHandler.DEFAULT); this.clientConfig = clientConfig; connectTimeout = clientConfig.get(CommonClientConfigKey.ConnectTimeout); readTimeout = clientConfig.get(CommonClientConfigKey.ReadTimeout); }
Source:
public void encodesXml() throws Exception { EncoderBindings bindings = new EncoderBindings(); ObjectGraph.create(bindings).inject(bindings); MockObject mock = new MockObject(); mock.setValue("Test"); RequestTemplate template = new RequestTemplate(); bindings.encoder.encode(mock, template); START System.out.println(new String(template.body())); END assertEquals(new String(template.body(), UTF_8), "<?xml version=\"1.0\" encoding=\"UTF-8\" " + "standalone=\"yes\"?><mockObject><value>Test</value></mockObject>"); } Please scrub out printlns

Target:
public void encodesXml() throws Exception { EncoderBindings bindings = new EncoderBindings(); ObjectGraph.create(bindings).inject(bindings); MockObject mock = new MockObject(); mock.setValue("Test"); RequestTemplate template = new RequestTemplate(); bindings.encoder.encode(mock, template); assertEquals(new String(template.body(), UTF_8), "<?xml version=\"1.0\" encoding=\"UTF-8\" " + "standalone=\"yes\"?><mockObject><value>Test</value></mockObject>"); }
Source:
START public Set<T> getSet() { END return set; } Minor: there is also a method, `Predicates.asSet(In)`, that exposes the inner set. I think the purpose of that was to mimic the use of `Ranges.asSet(Range)`, which has to be a static method because we allow ranges of objects that aren't `Comparable` but back the `asSet` method with a Guava range that requires a `Comparable` type. I'm fine with changing to use this method everywhere, since this is more straight-forward. But I'd like to either use `Predicates.asSet(In)` or `In#getSet()`, not both.

Target:
Set<T> getSet() { return set; }
Source:
public String toString(Schema schema) { // we want the string this returns to be consistent // ensure the set is sorted before calling toString on it. Iterable<String> strings = Iterables.transform(set, new ToString<T>(schema)); START return Joiner.on(',').join(Sets.newTreeSet(strings)); END } I'm not sure I'm clear on what happens here. Generally, we are using a `LinkedHashMap` or `LinkedHashSet` to preserve the order. If we aren't doing that somewhere, then I think it is a bug and should be fixed. URIs should only be normalized when needed, to avoid annoyance. I think that's what you do in this case, but I wanted to make sure.

Target:
public String toString(Schema schema) { return Joiner.on(',').join( Iterables.transform(set, new ToString<T>(schema))); }
Source:
public void testMultipleStringValuesWithEmpty() { Assert.assertEquals("In<Utf8>#toString(STRING)", ",a,b", Predicates.in(new Utf8("a"), new Utf8("b"), new Utf8("")).toString(STRING)); Assert.assertEquals("In#toString(STRING)", START ",a,b", Predicates.in("a", "b", "").toString(STRING)); END Assert.assertEquals("In.fromString(String, STRING)", Predicates.in("a", "b", ""), In.<String>fromString("a,b,", STRING)); } I don't think these should be changed. The `In` implementation should generally preserve order unless normalized to produce a `String`. Normalization should probably be a peer of `toString(Schema)`, `toNormalizedString(Schema)`.

Target:
public void testMultipleStringValuesWithEmpty() { Assert.assertEquals("In<Utf8>#toString(STRING)", "a,b,", Predicates.in(new Utf8("a"), new Utf8("b"), new Utf8("")).toString(STRING)); Assert.assertEquals("In#toString(STRING)", "a,b,", Predicates.in("a", "b", "").toString(STRING)); Assert.assertEquals("In.fromString(String, STRING)", Predicates.in("a", "b", ""), In.<String>fromString("a,b,", STRING)); }
Source:
public void tearDown() { if (morphline != null) { Notifications.notifyShutdown(morphline); Notifications.notifyShutdown(morphline); START morphline = null; END } } Let's also call super.tearDown()

Target:
public void tearDown() throws Exception { if (morphline != null) { Notifications.notifyShutdown(morphline); Notifications.notifyShutdown(morphline); morphline = null; } super.tearDown(); }
Source:
public URI build() { try { URI optionsUri = pattern.construct(options); START StringBuilder uri = new StringBuilder(); END uri.append(isView ? VIEW_SCHEME : DATASET_SCHEME).append(":") .append(optionsUri.getScheme()).append(":") .append(optionsUri.getRawSchemeSpecificPart()); return new URI(uri.toString()); } catch (URISyntaxException e) { throw new IllegalArgumentException("Could not build URI", e); } } Does it work with fewer changes here? Maybe just concatenate: ``` java return new URI(isView ? VIEW_SCHEME : DATASET_SCHEME + ":" + pattern.construct(options).toString()); ```

Target:
public URI build() { try { return new URI((isView ? VIEW_SCHEME : DATASET_SCHEME) + ":" + pattern.construct(options).toString()); } catch (URISyntaxException e) { throw new IllegalArgumentException("Could not build URI", e); } }
Source:
public static Configuration get() { START return conf; END } Configuration is mutable so it would be safer to return a new instance here. Global mutable state is a recipe for hard-to-diagnose bugs.

Target:
public static Configuration get() { return new Configuration(conf); }
Source:
public static void checkDatasetName(String namespace, String name) { Preconditions.checkNotNull(namespace, "Namespace cannot be null"); Preconditions.checkNotNull(name, "Dataset name cannot be null"); START Preconditions.checkArgument(Compatibility.isCompatibleName(name), END "Hive incompatible: Namespace %s is not alphanumeric (plus '_')", namespace); Preconditions.checkArgument(Compatibility.isCompatibleName(name), "Hive incompatible: Dataset name %s is not alphanumeric (plus '_')", name); } Should be namespace, not name.

Target:
public static void checkDatasetName(String namespace, String name) { Preconditions.checkNotNull(namespace, "Namespace cannot be null"); Preconditions.checkNotNull(name, "Dataset name cannot be null"); Preconditions.checkArgument(Compatibility.isCompatibleName(namespace), "Hive incompatible: Namespace %s is not alphanumeric (plus '_')", namespace); Preconditions.checkArgument(Compatibility.isCompatibleName(name), "Hive incompatible: Dataset name %s is not alphanumeric (plus '_')", name); }
Source:
public ConfigBuilder readFrom(View<?> view) { START if (view instanceof Dataset && view instanceof FileSystemDataset) { END FileSystemDataset dataset = (FileSystemDataset) view; conf.set(KITE_PARTITION_DIR, String.valueOf(dataset.getDescriptor().getLocation())); } withType(view.getType()); return readFrom(view.getUri()); } instanceof Dataset is redundant -- why not just a single instanceof FilesystemDataset check?

Target:
public ConfigBuilder readFrom(View<?> view) { if (view instanceof FileSystemDataset) { FileSystemDataset dataset = (FileSystemDataset) view; conf.set(KITE_PARTITION_DIR, String.valueOf(dataset.getDescriptor().getLocation())); } withType(view.getType()); return readFrom(view.getUri()); }
Source:
public static <E> void assertContentEquals(Set<E> expected, View<E> view) { DatasetReader<E> reader = null; try { reader = view.newReader(); Assert.assertEquals(expected, Sets.newHashSet((Iterable<E>) reader)); } finally { START Closeables.closeQuietly(reader); END } } Closeables.closeQuietly is deprecated in Guava 14 so we should avoid using it. See https://code.google.com/p/guava-libraries/issues/detail?id=1118&can=1&q=closeQuietly&sort=id%20-owner&colspec=ID%20Type%20Status%20Milestone%20Summary We could just call `Closeables.close(reader, false)` so the IOException is never swallowed, then if we declare the test method to throw IOException we will fail the test if this condition ever happens.

Target:
public static <E> void assertContentEquals(Set<E> expected, View<E> view) throws IOException { DatasetReader<E> reader = null; try { reader = view.newReader(); Assert.assertEquals(expected, Sets.newHashSet((Iterable<E>) reader)); } finally { Closeables.close(reader, false); } }