auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void emptyMapCausesException() { Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>(); publisher = new DefaultAuthenticationEventPublisher(); publisher.setAdditionalExceptionMappings(mappings); ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class); publisher.setApplicationEventPublisher(appPublisher); }

Target:
Are the last two lines of this test necessary? Let's go ahead and remove any unnecessary lines of code.
Source:
protected OAuth2AccessTokenResponse populateTokenResponse(T grantRequest, OAuth2AccessTokenResponse tokenResponse) { if (CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes())) { Set<String> defaultScopes = defaultScopes(grantRequest); tokenResponse = OAuth2AccessTokenResponse.withResponse(tokenResponse) .scopes(defaultScopes) .build(); } return tokenResponse; }

Target:
Do we need to expose this right now? I'd prefer to make `private` if we don't need to expose now.
Source:
private RequestContextSubscriber(CoreSubscriber<T> delegate, Authentication authentication) { this.delegate = delegate; Context parentContext = this.delegate.currentContext(); Context context; if (parentContext.hasKey(REQUEST_CONTEXT_DATA_HOLDER_ATTR_NAME)) { context = parentContext; } else { context = parentContext.put(REQUEST_CONTEXT_DATA_HOLDER_ATTR_NAME, new RequestContextDataHolder(authentication)); } this.context = context; }

Target:
maybe it would be better not to create empty RequestContextDataHolder? by ```java if (authentication == null || parentContext.hasKey(REQUEST_CONTEXT_DATA_HOLDER_ATTR_NAME)) ```
Source:
private boolean shouldProcessAuthorizationResponse(HttpServletRequest request) { OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository.loadAuthorizationRequest(request); if (authorizationRequest == null) { return false; } MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap()); if (isValidRedirectUrl(request, authorizationRequest.getRedirectUri()) && OAuth2AuthorizationResponseUtils.isAuthorizationResponse(params)) { return true; } return false; }

Target:
@ttddyy This can be simplified as follows: ```java String requestUrl = UrlUtils.buildFullRequestUrl(request); MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap()); if (requestUrl.startsWith(authorizationRequest.getRedirectUri()) && OAuth2AuthorizationResponseUtils.isAuthorizationResponse(params)) { return true; } ```
Source:
public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : getAuthorities(jwt)) { grantedAuthorities.add(new SimpleGrantedAuthority(authorityPrefix + authority)); } return grantedAuthorities; }

Target:
To conform with our team standard, would you please prefix the field with `this.`?
Source:
public RequestContextDataHolder(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable Authentication authentication) { this.request = request; this.response = response; this.authentication = authentication; }

Target:
Make `private`
Source:
public HttpServletRequest getRequest() { return request; }

Target:
Make getters `private` and use `this` on instance members.
Source:
private List<String> getPrimaryBeanNames(String[] beanNamesForType) { final List<String> list = new ArrayList<>(); if (!(applicationContext instanceof ConfigurableApplicationContext)) { return Collections.emptyList(); } for (String beanName: beanNamesForType) { if (((ConfigurableApplicationContext) applicationContext).getBeanFactory() .getBeanDefinition(beanName).isPrimary()) { list.add(beanName); } } return list; }

Target:
So that this aligns with the rest of the codebase, let's remove the `final` keyword here.
Source:
private static Map<String, ClientRegistration> toUnmodifiableConcurrentMap(List<ClientRegistration> registrations) { final ConcurrentHashMap<String, ClientRegistration> result = new ConcurrentHashMap<>(); for (ClientRegistration registration : registrations) { if (result.containsKey(registration.getRegistrationId())) { throw new IllegalStateException(String.format("Duplicate key %s", registration.getRegistrationId())); } result.put(registration.getRegistrationId(), registration); } return Collections.unmodifiableMap(result); }

Target:
Why is this check necessary?
Source:
private LinkedHashSet<String> toLinkedHashSet(String... scope) { final LinkedHashSet<String> result = new LinkedHashSet<>(); Collections.addAll(result, scope); return result; }

Target:
To conform with other Spring Security code, please remove the `final` keyword from in front of local variables.
Source:
private ConcurrentHashMap<String, ClientRegistration> toConcurrentMap(List<ClientRegistration> registrations) { final ConcurrentHashMap<String, ClientRegistration> result = new ConcurrentHashMap<>(); for (ClientRegistration registration : registrations) { result.put(registration.getRegistrationId(), registration); } return result; }

Target:
For consistency across the project, please remove the `final` keyword here.
Source:
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) { Assert.notNull(context, "context cannot be null"); for (OAuth2AuthorizedClientProvider authorizedClientProvider: authorizedClientProviders) { final OAuth2AuthorizedClient oauth2AuthorizedClient = authorizedClientProvider.authorize(context); if (oauth2AuthorizedClient != null) { return oauth2AuthorizedClient; } } return null; }

Target:
Thanks for simplifying this. Will you please also remove the `final` keyword from the local variable here?
Source:
private void rejectedUntrustedHosts(HttpServletRequest request) { String serverName = request.getServerName(); if (this.allowedHostnames != null && !this.allowedHostnames.test(serverName)) { throw new RequestRejectedException("The request was rejected because the domain " + serverName + " is untrusted."); } }

Target:
Sorry, the concern isn't that `this.allowedHostnames` would be `null` at this point, but that `serverName` would be `null`. Because of the change to `DummyRequest`, it's possible for `getServerName` to return `null`. So, we'd want to do: ```suggestion if (serverName != null && !this.allowedHostnames.test(serverName)) { ```
Source:
public SingleKeyJWSKeySelector(JWSAlgorithm expectedJwsAlgorithm, Key key) { Assert.notNull(expectedJwsAlgorithm, "expectedJwsAlgorithm cannot be null"); Assert.notNull(key, "key cannot be null"); this.keySet = Arrays.asList(key); this.expectedJwsAlgorithm = expectedJwsAlgorithm; }

Target:
You can remove the `public` modifier since the class is `package-private`
Source:
public void customWithUriVars() throws Exception { MockHttpServletRequest request = logout().logoutUrl("/uri-logout/{var1}/{var2}", "val1", "val2").buildRequest( servletContext); CsrfToken token = (CsrfToken) request.getAttribute(CsrfRequestPostProcessor.TestCsrfTokenRepository.TOKEN_ATTR_NAME); assertThat(request.getMethod()).isEqualTo("POST"); assertThat(request.getParameter(token.getParameterName())).isEqualTo( token.getToken()); assertThat(request.getRequestURI()).isEqualTo("/uri-logout/val1/val2"); }

Target:
This `throws` clause is redundant.
Source:
public MockMethodInvocation(Object targetObject, Class clazz, String methodName, Class[] parameterTypes, Object[] arguments) throws NoSuchMethodException { this.method = clazz.getMethod(methodName, parameterTypes); this.targetObject = targetObject; this.arguments = arguments; }

Target:
Is there any reason you aren't calling `this(targetObject, clazz, methodName, parameterTypes)`? If not, would you mind changing this? I realize it's a minor point, but it's one less thing to keep track off.
Source:
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { if (this.clientRegistrationRepository != null && this.authorizedClientRepository != null) { OAuth2AuthorizedClientArgumentResolver authorizedClientArgumentResolver = new OAuth2AuthorizedClientArgumentResolver( this.clientRegistrationRepository, this.authorizedClientRepository); if (accessTokenResponseClient != null) { authorizedClientArgumentResolver.setClientCredentialsTokenResponseClient(accessTokenResponseClient); } argumentResolvers.add(authorizedClientArgumentResolver); } }

Target:
Please update `accessTokenResponseClient` to `this.accessTokenResponseClient` - it's common practice within the team to prefix `this` for class members.
Source:
public Consumer<WebClient.Builder> oauth2Configuration() { Hooks.onLastOperator(REQUEST_CONTEXT_OPERATOR_KEY, Operators.lift((s, sub) -> createRequestContextSubscriber(sub))); return builder -> builder.defaultRequest(defaultRequest()).filter(this); }

Target:
We can make this implement DisposableBean to clean up the hooks
Source:
public void issuerWhenTokenEndpointAuthMethodsNoneThenMethodIsNone() throws Exception { this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("none")); ClientRegistration registration = registration("") .clientAuthenticationMethod(ClientAuthenticationMethod.NONE) .build(); assertThat(registration.getClientAuthenticationMethod()).isEqualTo(ClientAuthenticationMethod.NONE); }

Target:
This line should be removed to ensure `clientAuthenticationMethod` is `ClientAuthenticationMethod.NONE`
Source:
public void writeHeadersWhenWhiteList() { WhiteListedAllowFromStrategy whitelist = new WhiteListedAllowFromStrategy(Collections.singletonList("example.com")); XFrameOptionsHeaderWriter writer = new XFrameOptionsHeaderWriter(whitelist); writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderValue(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("DENY"); }

Target:
Is this change necessary for this PR? I see that you are using `Collections.singletonList` below in your test, but I'd recommend bringing other tests into conformance be in a different PR. (For example, you could also change old tests to refer to member variables via `this.`, but we aren't doing that here since that isn't the purpose of this PR)
Source:
public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { headerWriters.forEach(headerWriter -> headerWriter.writeHeaders(request, response)); }

Target:
Just a quick reminder here, too, about `this`, so ```suggestion this.headerWriters.forEach(headerWriter -> headerWriter.writeHeaders(request, response)); ```
Source:
public C requestMatchers(RequestMatcher... requestMatchers) { if (!Objects.equals(requestMatchers[0], AnyRequestMatcher.INSTANCE)){ Assert.state(!this.anyRequestConfigured, "Can't configure requestMatchers after anyRequest"); } return chainRequestMatchers(Arrays.asList(requestMatchers)); }

Target:
@ankurpathak, this approach won't work because it changes the inheritance behavior. For example, if I had overridden `requestMatchers`, I may be expecting `anyMatcher` to call it (since it originally was). `anyMatcher` needs to continue to call `requestMatchers` in order to remain backwards compatible.
Source:
public OAuth2IntrospectionAuthenticationToken(OAuth2AccessToken token, Map<String, Object> attributes, Collection<? extends GrantedAuthority> authorities) { this(token, attributes, authorities, null); setAuthenticated(true); }

Target:
`setAuthenticated(true)` should get pushed to the 4 arg constructor.
Source:
public void setVariable(String name, @Nullable Object value) { if (name == null) throw new IllegalArgumentException("name should not be null"); else super.setVariable(name, value); }

Target:
Please add `{` to follow Spring Security's code conventions
Source:
public HeaderBearerTokenResolver(String header) { Assert.notNull(header, "header cannot be null"); Assert.hasText(header, "header cannot be empty"); this.header = header; }

Target:
Is there a need to have both asserts? The reason I'd prefer only one is that I don't want the user to get one error, fix it, and then get another. Since `nonNull` is implied by `hasText`, we can give the user only one error message that will repair both problems.
Source:
protected ServerOAuth2AuthorizedClientExchangeFilterFunction(ServerOAuth2AuthorizedClientRepository authorizedClientRepository, OAuth2AuthorizedClientResolver authorizedClientResolver) { this.authorizedClientRepository = authorizedClientRepository; this.authorizedClientResolver = authorizedClientResolver; }

Target:
Let's remove `protected` so it's package-private instead.
Source:
public JdbcAclService(DataSource dataSource, LookupStrategy lookupStrategy) { Assert.notNull(dataSource, "DataSource required"); Assert.notNull(lookupStrategy, "LookupStrategy required"); this.jdbcOperations = new JdbcTemplate(dataSource); this.lookupStrategy = lookupStrategy; this.aclClassIdUtils = new AclClassIdUtils(); }

Target:
This constructor can just invoke `this(new JdbcTemplate(dataSource), lookupStrategy)`
Source:
protected ReactiveAuthenticationManager getAuthenticationManager() { if (this.authenticationManager == null) { ReactiveJwtDecoder jwtDecoder = getJwtDecoder(); ReactiveAuthenticationManager authenticationManager = new JwtReactiveAuthenticationManager(jwtDecoder); return authenticationManager; } return this.authenticationManager; }

Target:
Can this be private?
Source:
public static OAuth2AuthorizationRequest.Builder request() { String registrationId = "registration-id"; String clientId = "client-id"; Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put(OAuth2ParameterNames.REGISTRATION_ID, registrationId); return OAuth2AuthorizationRequest.authorizationCode() .authorizationUri("https://example.com/login/oauth/authorize") .clientId(clientId) .scope("openid") .redirectUri("https://example.com/authorize/oauth2/code/registration-id") .state("state") .additionalParameters(additionalParameters); }

Target:
Did you verify this isn't going to break any existing test assumptions? We probably shouldn't modify this as we don't know what impact this is having on existing tests. It may invalidate a test that has different expectations of the scopes.
Source:
public JwtConfigurer jwt() { if ( this.jwtConfigurer == null ) { ApplicationContext context = this.getBuilder().getSharedObject(ApplicationContext.class); this.jwtConfigurer = new JwtConfigurer(context); } return this.jwtConfigurer; }

Target:
Assert notNull
Source:
private String getKey() { if (this.key == null && this.rememberMeServices instanceof AbstractRememberMeServices) { this.key = ((AbstractRememberMeServices) rememberMeServices).getKey(); } if (this.key == null) { this.key = UUID.randomUUID().toString(); } return this.key; }

Target:
Please move this check into the `null` check bellow, since we are already checking if `this.key == null`.
Source:
protected void configure(HttpSecurity http) throws Exception { // @formatter:off http.rememberMe() .rememberMeServices(new TokenBasedRememberMeServices("key", userDetailsService())); // @formatter:on }

Target:
I believe I misled you in my previous review, we will need additional configuration here. ``` // @formatter:off http .authorizeRequests() .anyRequest().hasRole("USER") .and() .formLogin() .and() .rememberMe() .rememberMeServices(new TokenBasedRememberMeServices("key", userDetailsService())); // @formatter:on ```
Source:
private boolean isTransientAuthentication(Authentication authentication) { if (authentication == null ) { return false; } return AnnotationUtils.getAnnotation(authentication.getClass(), TransientAuthentication.class) != null; }

Target:
This check is not needed as `authentication` is never `null` based on the call path
Source:
SessionCreationPolicy getSessionCreationPolicy() { if (this.sessionPolicy != null) { return this.sessionPolicy; } SessionCreationPolicy shared = getBuilder().getSharedObject(SessionCreationPolicy.class); return shared == null ? SessionCreationPolicy.IF_REQUIRED : shared; }

Target:
Rename variable `shared` to `sessionCreationPolicy`
Source:
public RequestMatcherDelegatingAccessDeniedHandler( LinkedHashMap<RequestMatcher, AccessDeniedHandler> handlers, AccessDeniedHandler defaultHandler) { Assert.notEmpty(handlers, "handlers cannot be null or empty"); Assert.notNull(defaultHandler, "defaultHandler cannot be null"); this.handlers = handlers; this.defaultHandler = defaultHandler; }

Target:
Do a defensive copy for `handlers` into a new instance of `Map`
Source:
public OAuth2ResourceServerConfigurer<B> resourceServer() throws Exception { if (this.resourceServerConfigurer == null) { this.initResourceServerConfigurer(); } return this.resourceServerConfigurer; }

Target:
Remove `throws Exception` as it's never thrown
Source:
public OAuth2Configurer<HttpSecurity> oauth2() throws Exception { return getOrApply(new OAuth2Configurer<>()); }

Target:
Add @since 5.1
Source:
public Object cors() throws Exception { return getOrApply(new CorsConfigurer<HttpSecurity>()); }

Target:
Should return type `CorsConfigurer<HttpSecurity>`
Source:
public RequestSpec connectTimeout(Duration duration) { delegate.connectTimeout(duration); return null; }

Target:
`return this`?
Source:
public RequestSpecBacking(MutableHeaders headers, URI uri, ByteBufAllocator byteBufAllocator, RequestParams requestParams) { this.headers = headers; this.uri = uri; this.byteBufAllocator = byteBufAllocator; this.requestParams = requestParams; this.bodyByteBuf = byteBufAllocator.buffer(0, 0); this.decompressResponse = false; }

Target:
+1 > On 27 May 2015, at 21:15, Rus notifications@github.com wrote: > > In ratpack-core/src/main/java/ratpack/http/client/internal/RequestSpecBacking.java: > > > @@ -51,6 +52,7 @@ public RequestSpecBacking(MutableHeaders headers, URI uri, ByteBufAllocator byte > > this.byteBufAllocator = byteBufAllocator; > > this.requestParams = requestParams; > > this.bodyByteBuf = byteBufAllocator.buffer(0, 0); > > - this.decompressResponse = false; > > I would say now is the time, before 1.0, to get this how we want. Let's take advantage of not being concerned about backwards compatibility while we still can :) > > — > Reply to this email directly or view it on GitHub.
Source:
public void handle(Context context) throws Exception { if (!name.equals(DEFAULT_NAME_TOKEN)) { handleByName(context, name); } else { handleAll(context); } }

Target:
This logic doesn't seem right. What we want to support is running a particular check if its name was specified as a path token. This classes param should indicate the name of the path token to look for. If the token is present, we only render the check whose name matches.
Source:
public Boolean isAjaxRequest() { return HttpHeaderConstants.XML_HTTP_REQUEST.equals(headers.get(HttpHeaderConstants.X_REQUESTED_WITH)); }

Target:
Should this match be case-sensitive, or case-insensitive?
Source:
private void transmit(final BasicFileAttributes basicFileAttributes, final Object message) throws Exception { transmitterAction.execute(new Action<ResponseTransmitter>() { @Override public void execute(ResponseTransmitter responseTransmitter) { HttpHeaders httpHeaders = new DefaultHttpHeaders(false); MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(httpHeaders); responseTransmitter.transmit(HttpResponseStatus.OK, responseHeaders, basicFileAttributes.size(), message); } }); }

Target:
Why are we doing this instead of using the headers given in the constructor?
Source:
public String getFullRequestURL() { final PublicAddress publicAddress = context.get(PublicAddress.class); return publicAddress.getAddress(context).toString() + context.getRequest().getUri(); }

Target:
There's currently a helper method in this class for getting the public address. I think this line can become: ``` return getAddress().toString() + context.getRequest().getUri(); ```
Source:
public HandlebarsTemplateRenderer(Handlebars handlebars) { this.handlebars = handlebars; this.templateCache = CacheBuilder.newBuilder() .expireAfterAccess(5, TimeUnit.MINUTES) .build(new CacheLoader<String, com.github.jknack.handlebars.Template>() { @Override public com.github.jknack.handlebars.Template load(String key) throws Exception { return HandlebarsTemplateRenderer.this.handlebars.compile(key); } }); }

Target:
Isn't this redundant and not used anywhere anyway?
Source:
public PlayerColor getPiranha() { if (state == RED) return PlayerColor.RED; else if (state == BLUE) return PlayerColor.BLUE; return null; }

Target:
lieber ein `Optional<PlayerColor>` zurueckgeben
Source:
public LogItemViewHolder(View rootView) { this.rootView = rootView; ButterKnife.inject(this, rootView); rootView.setTag(this); }

Target:
I don't like this side-effect. Can you do it in a static method rather than ctor?
Source:
@Inject public DebugIntentFactory(@IsMockMode boolean isMockMode, @UseExternalApps BooleanPreference useExternalApps) { super(); this.isMockMode = isMockMode; this.useExternalApps = useExternalApps; }

Target:
Delete
Source:
@Override protected void onAttachedToWindow() { super.onAttachedToWindow(); subscriptions.add(timespanSubject // .flatMap(trendingSearch) // .map(new SearchResultToRepositoryList()), // trendingAdapter); // Load the default selection. timespanSubject.onNext(timespanAdapter.getItem(timespanView.getSelectedItemPosition())); }

Target:
Is this guy stateless? There should be a static `instance()` method on it.
Source:
@Override public String toString() { return createdSince == null ? "" : "created:>=" + ISO_8601_DATE.print(createdSince); }

Target:
While it's kind of not cool to return `null` from `toString`, returning `null` will omit the query parameter from the URL altogether.
Source:
protected boolean evaluateFilter(JsonBuilderContext context) { if (filter == null) return true; int i = 0; JsonBuilderContext evaluationContenxt = context; while (i < filterContextPos) { evaluationContenxt = evaluationContenxt.getParent(); i++; } return filter.evaluate(evaluationContenxt.getCurrentObj()); }

Target:
Why couldn't this be written using a simple for loop? I don't see odd exit conditions.
Source:
public PropertyNameTypeBinding( FilterFactory2 filterFactory, NamespaceSupport namespaceSupport, Catalog catalog) { super(filterFactory, namespaceSupport); this.namespaceSupport = namespaceSupport; this.catalog = catalog; }

Target:
Is this just me, or this assignement became useless? ``` this.namespaceSupport = namespaceSupport; ```
Source:
private boolean isJsonLdMIME(Request request) { String accept = request.getHttpRequest().getHeader(HttpHeaders.ACCEPT); if (accept != null && accept.contains(JSONLDGetFeatureResponse.MIME)) return true; else if (request.getKvp().get("f") != null && request.getKvp().get("f").equals(JSONLDGetFeatureResponse.MIME)) return true; else return false; }

Target:
Upside down, "f" override accepts, so it should be tested first.
Source:
public JsonLdConfiguration(GeoServerDataDirectory dd) { this.dd = dd; templateCache = CacheBuilder.newBuilder() .maximumSize(10) .initialCapacity(1) .expireAfterAccess(120, TimeUnit.MINUTES) .build( new CacheLoader<CacheKey, JsonLdTemplate>() { @Override public JsonLdTemplate load(CacheKey key) { Resource resource = dd.get(key.getResource(), key.getPath()); JsonLdTemplate template = new JsonLdTemplate(resource); return template; } }); }

Target:
The default seems a bit small... maybe up to 100 and make it configurable via System variable? Ideally it would be nice to make it runtime configurable, like for example matching the number of cached feature types in the "global settings", but I'm guessing that would come with some complications, like possibly rebuilding the cache. Just thinking out loud here mind, not asking for this change to be actually implemented.
Source:
private boolean checkWMSLayerMinMaxScale(WMSLayerInfo wmsLayerInfo, double mapScale) { // // if none configured if (wmsLayerInfo.getMinScale() == null && wmsLayerInfo.getMaxScale() == null) return true; if (wmsLayerInfo.getMinScale() != null) if (mapScale < wmsLayerInfo.getMinScale()) return false; // return false map scale is below min if (wmsLayerInfo.getMaxScale() != null) if (mapScale > wmsLayerInfo.getMaxScale()) return false; // return false map scale is above max return true; }

Target:
You can use ``&& mapScale < wmsLayerInfo.getMinScale()`` in the first if, there is short-circuit evaluation
Source:
protected String relativeDataFileURL(String url, Catalog catalog) { if (catalog == null) { return url; } File baseDirectory = catalog.getResourceLoader().getBaseDirectory(); File f = Resources.find(Resources.fromURL(Files.asResource(baseDirectory), url), true); return f == null ? url : "file:" + Paths.convert(baseDirectory, f); }

Target:
There should be a static constant of some sort constant or method for better readability.... Looks like we are doing a round trip from Path --> File --> Resource --> File above? Hold on, this method is used by data sources to access data, was trying to do this with Files (and only use Resources when working with configuration information).
Source:
public void testGetGeoJsonResponseWfs20() throws Exception { // execute the WFS 2.0 request JSON response = getAsJSON( "wfs?request=GetFeature&version=2.0" + "&typenames=st_gml32:Station_gml32&outputFormat=application/json"); print(response); // validate the obtained response checkStation1Exists(response); }

Target:
A miss?
Source:
public RestListWrapper<EchoParameter> getEchoParameters() { return new RestListWrapper<>( EchoParametersDao.getEchoParameters().stream().collect(Collectors.toList()), EchoParameter.class, this, "id", null); }

Target:
`EchoParametersDao.getEchoParameters()` already returns a list.
Source:
public static String toString(Document document) throws TransformerException { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(writer)); return writer.getBuffer().toString(); }

Target:
Does it need to be ``public`` is ``protected`` not enough ?
Source:
public ReferencedEnvelope getBounds(Filter filter) { try { GranuleSource source = reader.getGranules(reader.getGridCoverageNames()[0], true); Query query = new Query(null, filter); if (filter != null) { query.setFilter(filter); } // reading the features using the build query FeatureCollection featureCollection = source.getGranules(query); return featureCollection.getBounds(); } catch (Exception exception) { throw new RuntimeException("Failed to collect bounds", exception); } }

Target:
I'm not sure, but if we provide the filter in the constructor do we need do set it here ?
Source:
private static Number parseValue(String s, Class dataType) throws ParseException { if (Date.class.isAssignableFrom(dataType)) { long period = TimeParser.parsePeriod(s); return period; } else { // TODO: add support for Number, e.g., elevation throw new IllegalArgumentException("Unsupported value type " + dataType); } }

Target:
Can be returned right away.
Source:
public FileSystemResource(String path) { this.path = Paths.convert(path); this.file = Paths.toFile(baseDirectory, path); }

Target:
So adding this logic here is not quite what was intended, paths are supposed to be within the data directory. For the rare case, mostly test cases, that you need to use a file as a resource there is the [Files.asResource( file )](https://github.com/geoserver/geoserver/blob/master/src/platform/src/main/java/org/geoserver/platform/resource/Files.java#L308) method. The [Paths.convert( file, file )](https://github.com/geoserver/geoserver/blob/55c4740060eb2b8809ae935a510ac83eeb923313/src/platform/src/main/java/org/geoserver/platform/resource/Paths.java#L257) should be used rather than insert this logic?
Source:
public void setKeywords(List<KeywordInfo> keywords) { if (keywords == null) { this.keywords = new ArrayList<>(); } this.keywords = keywords; }

Target:
So you first set this.keywords to a non null value, and then set it to null? I guess you wanted something like: ```` if (keywords == null) { keywords = new ArrayList<>(); } this.keywords = keywords;
Source:
public void testWorkspaceQualifiedNoLayersError() throws Exception { Document dom = getAsDOM("sf/wms?bbox=" + bbox + "&styles=" + "&layers=" + "&format=image/png" + "&request=GetMap" + "&width=550" + "&height=250" + "&srs=EPSG:4326", Charset.defaultCharset().displayName()); print(dom); assertEquals("ServiceExceptionReport", dom.getDocumentElement().getNodeName()); assertTrue(dom.getDocumentElement().getTextContent().contains("No LAYERS has been requested")); }

Target:
Leftover print
Source:
public boolean existsRole(String rolename) { try { if(logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "Checking Role [" + rolename + "] on ActiveRoleService [" + securityManager.getActiveRoleService() + "]"); } return securityManager.getActiveRoleService().getRoleByName(rolename) != null; } catch (IOException e) { logger.log(Level.WARNING, "No matching Role [" + rolename + "] on ActiveRoleService", e); return false; } }

Target:
Misleading message here?
Source:
public void testGridSetLoading() throws Exception { // let's wait a max of 30 seconds for the grid set registration GWC gwc = GWC.get(); int waited = 0; while(waited <= 30000 && GWC.get().getGridSetBroker().get(INSPIRE_GRID_SET_NAME) == null) { // let' wait 100 milliseconds Thread.sleep(100); waited += 100; } // let's see if the inspire grid set has been correctly registered assertThat(gwc.getGridSetBroker().get(INSPIRE_GRID_SET_NAME), notNullValue()); assertThat(gwc.isInternalGridSet(INSPIRE_GRID_SET_NAME), is(true)); }

Target:
Confused, why do we have to wait, are the context loaded notifications happening in a background thread? By the time the method is run the full initialization should have happened already or not?
Source:
public JMSSettingsModifyEvent(SettingsInfo source, List<String> propertyNames, List<Object> oldValues, List<Object> newValues, JMSEventType eventType) { super(source, propertyNames, oldValues, newValues); this.eventType = eventType; }

Target:
Does it make sense to have this for a class that states it's "modified"?
Source:
public void loadConfiguration(GeoServerResourceLoader resourceLoader) throws IOException { synchronized (this) { Resource controlflow = resourceLoader.get(PROPERTYFILENAME); if (Resources.exists(controlflow)) { configFile = new PropertyFileWatcher(controlflow); configFile.setKnownLastModified(System.currentTimeMillis()); } } }

Target:
Done this way, isStale() is not going to return true after a configuration restore, or not? I may be wrong, but given it's already look at the files, it's likely that leaving this method empty will already do the trick... although looking at the FileWatcher code, it might fail if the file was there before, and gets removed later. But I don't see a reason to re-create the watcher otherwise.
Source:
public List<Resource> getFileLocations() throws IOException { List<Resource> configurationFiles = new ArrayList<>(); GeoServerResourceLoader loader = GeoServerExtensions.bean(GeoServerResourceLoader.class); if (loader != null) { Resource f = getConfigurationFile(loader); configurationFiles.add(f); } else if (fw != null && fw.getResource() != null) { configurationFiles.add(fw.getResource()); } return configurationFiles; }

Target:
The loader is already available via construtor injection, why look it up dynamically at runtime?
Source:
protected void setUpTestData(SystemTestData testData) throws Exception { testData.setUpSecurity(); System.setProperty("DefaultCatalogStore", "org.geoserver.csw.store.simple.GeoServerSimpleCatalogStore"); System.setProperty("ALLOW_ENV_PARAMETRIZATION", "true"); // copy all records into the data directory File root = testData.getDataDirectoryRoot(); File catalog = new File(root, "catalog"); File records = new File("./src/test/resources/org/geoserver/csw/records"); FileUtils.copyDirectory(records, catalog); }

Target:
Probably best to set it in the base test class, and make sure it gets cleaned at the end of the test?
Source:
public boolean isEnabled(final String serviceId) { checkNotNull(serviceId); if ("wms".equalsIgnoreCase(serviceId)) { return isWMSCEnabled(); } if ("wmts".equalsIgnoreCase(serviceId)) { throw new ServiceException("To check if WMTS service is enable or disable use service info."); } if ("tms".equalsIgnoreCase(serviceId)) { return isTMSEnabled(); } return true; }

Target:
ServiceExceptions are to be used for OGC errors, this is an internal programming error instead no? You have moved the check for WMTS being enabled or not to a normal ServiceInfo, and this check should not be used anymore, right?
Source:
public Optional<String> getVersion() { if (provider.contains("OracleJDK")) { return version.ofNullable(System.getProperty("java.version")); } else { return version.empty(); } }

Target:
Why do you have `Optional` instance `version` if all you ever use it for is to call these static methods?
Source:
public void convertInput() { visitChildren(TextArea.class, (Component component, final IVisit<Void> visit) -> { if (component instanceof TextArea) { TextArea textArea = (TextArea) component; textArea.updateModel(); } }); setConvertedInput(new DefaultValueConfigurations(configurations)); }

Target:
Found out the lambda conversion could be less verbose and just use `(component, visit) ->`, the compiler seems to be able to infer the argument types on its own. Or did you do it on purpose to help the reader?
Source:
public GeoJSONBuilder value(Object value) { if (value instanceof java.util.Date || value instanceof Calendar) { value = Converters.convert(value, String.class); } if (value instanceof Double) { value = roundToNumberOfDecimalPlaces((Double)value); } super.value(value); return this; }

Target:
"else if" maybe?
Source:
void cacheData(Resource res, File file) throws IOException { assert res.getType()==Type.RESOURCE; OutputStream out = new FileOutputStream(file); try { InputStream in = res.in(); try { IOUtils.copy(in, out); } finally { in.close(); } } finally { out.close(); } }

Target:
Could this be a single try-with-resources block with two resources and a single statement in the body?
Source:
public int anyUpdateQuery(QueryBuilder query) { try (Connection c = ds.getConnection()) { LOGGER.log(Level.FINEST, query.toString()); PreparedStatement stmt = query.toStatement(c); try { return stmt.executeUpdate(); } finally { stmt.close(); } } catch (SQLException ex) { throw new IllegalStateException("UpdateQuery Failed",ex); } }

Target:
try-with-resources; you could move the logging into the body which is a slightly different ordering, or before as it does not need the resources.
Source:
public void theoryLeavesHaveIstream(String path) throws Exception { Resource res = getResource(path); assumeThat(res, is(resource())); InputStream result = res.in(); try { assertThat(result, notNullValue()); } finally { result.close(); } }

Target:
try-with-resources?
Source:
public DocumentFile(Resource path) throws JDOMException, IOException { if (!Resources.exists(path)) { throw new IllegalArgumentException("Unable to locate the file path: \'" + path + "\'"); } this.path = path; InputStream in = path.in(); try { this.body = IOUtils.toString(in); } finally { in.close(); } }

Target:
@NielsCharlier try-with-resources?
Source:
public void testMapResult() throws Exception { String ext = getExtension(); String xml = "<wps:Execute service='WPS' version='1.0.0' xmlns:wps='http://www.opengis.net/wps/1.0.0' " + "xmlns:ows='http://www.opengis.net/ows/1.1'>" + "<ows:Identifier>" + ext + ":map</ows:Identifier>" + "<wps:DataInputs>" + "</wps:DataInputs>" + "<wps:ResponseForm>" + "<wps:RawDataOutput mimeType=\"text/xml\">" + "<ows:Identifier>result</ows:Identifier>" + "</wps:RawDataOutput>" + "</wps:ResponseForm>" + "</wps:Execute>"; Document doc = postAsDOM("wps", xml); print(doc); assertEquals("map", doc.getDocumentElement().getLocalName()); assertXpathEvaluatesTo("widget", "/map/name", doc); assertXpathEvaluatesTo("12.99", "/map/price", doc); }

Target:
@jodygarnett @aaime do we still discourage use of GeoServerSystemTestSupport.print(Document) (etc) since -DquietTests was introduced? I think so. @NielsCharlier we like tests to not flood the console, so perhaps this line should be removed.
Source:
public CoordinateReferenceSystem readPrjToCRS() throws IOException { Resource prj = getPrjFile(); if (prj == null || !Resources.exists(prj)) { return null; } InputStream is = prj.in(); String wkt = IOUtils.toString(is); is.close(); try { return CRS.parseWKT(wkt); } catch (Exception e) { throw (IOException) new IOException().initCause(e); } }

Target:
@NielsCharlier is this a possible resource leak? Needs a try-with-resource?
Source:
public void putTransformInfo(TransformInfo transform) throws IOException { if (transform.getName() == null) { throw new IllegalArgumentException("Transformation does not have a name set"); } Resource file = getTransformInfoFile(transform.getName()); OutputStream fos = null; try { fos = file.out(); xs.toXML(transform, fos); } finally { IOUtils.closeQuietly(fos); } infoCache.put(transform, file); }

Target:
Perhaps try-with-resources? I need to understand suppressed exceptions ...
Source:
public static @Nullable LoggingInfo getLogging(GeoServerResourceLoader loader) throws IOException { // Exposing this is a hack to provide JDBCConfig with the information it needs to compute // the "change" between logging.xml and the versions stored in JDBC. KS // TODO find a better solution than re-initializing on JDBCCOnfig startup. Resource f= loader.get( "logging.xml" ); if ( f != null ) { XStreamPersister xp = new XStreamPersisterFactory().createXMLPersister(); BufferedInputStream in = new BufferedInputStream( f.in() ); try { LoggingInfo loginfo = xp.load(in,LoggingInfo.class); return loginfo; } finally { in.close(); } } else { return null; } }

Target:
Justin spaces.
Source:
public void storeKeyStore() throws IOException{ // store away the keystore assertActivatedKeyStore(); OutputStream fos = getResource().out(); char[] passwd = securityManager.getMasterPassword(); try { ks.store(fos, passwd); } catch (Exception e) { throw new IOException(e); } finally { securityManager.disposePassword(passwd); } fos.close(); }

Target:
Perhaps try-with-resources? Needs care with the disposePassword.
Source:
public boolean synchronize(DocumentFile event) throws Exception { OutputStream fout = null; try { fout = event.getPath().out(); xstream.toXML(event.getBody(), fout); return true; } catch (IllegalStateException e) { if (LOGGER.isLoggable(java.util.logging.Level.SEVERE)) LOGGER.severe(e.getLocalizedMessage()); throw e; } finally { IOUtils.closeQuietly(fout); } }

Target:
Please convert these tabs to spaces. Can this be converted to a Java 7 try-with-resources?
Source:
public String getIdValue(Object object, int index) { switch ((StyleType) object) { case GENERIC: return "Generic"; case LINE: return "Line"; case POINT: return "Point"; case POLYGON: return "Polygon"; case RASTER: return "Raster"; default: return ""; } }

Target:
Consider moving to the Enum, also a bit confused on this - is it an "id" used for wicket communication - or is it human readable (in which case it should be translatable).
Source:
private AuthenticationCache lookupAuthenticationCache() { AuthenticationCache authCache = GeoServerExtensions.bean(AuthenticationCache.class); if (authCache==null) { Disposer disposer = GeoServerExtensions.bean(Disposer.class); authCache = new GuavaAuthenticationCacheImpl(1000); if(disposer!=null) { disposer.register((DisposableBean)authCache); } else { LOGGER.warning("Disposer not available to register for disposal. GuavaAuthenticationCacheImpl may not be closed at application shutdown."); } } return authCache; }

Target:
Strictly speaking this is API change IMHO, but that's ok :)
Source:
public synchronized void addListener(File file, String path, ResourceListener listener) { if( watcher == null ){ // Would be better if we could make FileSystemResource a DisposableBean instead Disposer disposer = GeoServerExtensions.bean(Disposer.class); watcher = new FileSystemWatcher(); if(disposer!=null) { disposer.register(watcher); } else { LOGGER.warning("Disposer not available to register for disposal. FileSystemWatcher may not be closed at application shutdown."); } } watcher.addListener( file, path, listener ); }

Target:
This code block is repeated over and over (lookup, register and log...) maybe make it a static method in Disposer?
Source:
public DefaultControlFlowConfigurator() { GeoServerResourceLoader loader = (GeoServerResourceLoader) GeoServerExtensions.bean( "resourceLoader"); Resource controlflow = loader.get(PROPERTYFILENAME); configFile = new PropertyFileWatcher(controlflow); //configFile = new PropertyFileWatcher(new File(GeoserverDataDirectory.getGeoserverDataDirectory(), PROPERTYFILENAME)); }

Target:
Nitpick: using GeoServerExtensions.bean(GeoServerResourceLoader.class) makes it refactor safe and avoids the cast. I believe we'll have a single GeoServerResourceLoader in GS anyways (or not?)
Source:
Resource getConfigFile(String configFileLocation ) throws IOException { File file = new File(configFileLocation); Resource resource; if( file.isAbsolute() ){ if( file.canRead() ){ return Files.asResource(file); // used by test cases } else { throw new IOException("Cannot read file: "+file.getCanonicalPath()); } } return null; }

Target:
Several points not respecting our coding conventions here (space in if condition, else not in the same line as the if closing brace)
Source:
private static void registerGeoShapeBoundsAggregator(ValuesSourceRegistry.Builder builder) { builder.register(GeoBoundsAggregationBuilder.NAME, GeoShapeValuesSourceType.instance(), (GeoBoundsAggregatorSupplier) (name, aggregationContext, parent, valuesSourceConfig, wrapLongitude, metadata) -> new GeoShapeBoundsAggregator(name, aggregationContext, parent, valuesSourceConfig, wrapLongitude, metadata)); }

Target:
Can this be a ctor reference like the others? It *looks* like it from here.
Source:
protected void mergeOptions(FieldMapper other, List<String> conflicts) { // TODO we should ban updating analyzers as well if (this.enablePositionIncrements != ((TokenCountFieldMapper)other).enablePositionIncrements) { conflicts.add("mapper [" + name() + "] has a different [enable_position_increments] setting"); } if (Objects.equals(this.nullValue, ((TokenCountFieldMapper)other).nullValue) == false) { conflicts.add("mapper [" + name() + "] has a different [null_value] setting"); } this.analyzer = ((TokenCountFieldMapper)other).analyzer; }

Target:
for my info, are these newly introduced checks or were they just moved?
Source:
public ModelPlotConfig(StreamInput in) throws IOException { enabled = in.readBoolean(); terms = in.readOptionalString(); if (in.getVersion().onOrAfter(Version.V_7_9_0)) { annotationsEnabled = in.readBoolean(); } else { annotationsEnabled = enabled; } }

Target:
I would just delete the version check from master. The logic is very simple and unlikely to cause clashes that are hard to resolve even in the unlikely event of someone adding another field in the lifetime of 7.x.
Source:
public void writeTo(StreamOutput out) throws IOException { out.writeBoolean(enabled); out.writeOptionalString(terms); if (out.getVersion().onOrAfter(Version.V_7_9_0)) { out.writeBoolean(annotationsEnabled); } }

Target:
As above, you might as well just delete this line.
Source:
public void testProjectUnresolvedAliasInFilter() { assertEquals("1:8: Unknown column [tni]", error("SELECT tni AS i FROM test WHERE i > 10 GROUP BY i")); assertEquals("1:31: Unknown column [i]", error("SELECT i AS i FROM test WHERE i > 10 GROUP BY i")); }

Target:
Please extra this check in its own test method.
Source:
protected Object parseSourceValue(Object value) { return value.toString(); }

Target:
nit: I was wondering if we should use covariance here and anywhere we return Strings, like we do for other types.
Source:
public void worked(final int work) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { if (progressBar.getSelection() >= 100) { progressBar.setSelection(0); System.out.println("reset"); } else { progressBar.setSelection(progressBar.getSelection() + work); System.out.println("sel=" + progressBar.getSelection() + work); } } }); }

Target:
Does that print out in Eclipse?
Source:
public DataSink<T> writeAsCsv(String filePath, String rowDelimiter, String fieldDelimiter) { return internalWriteAsCsv(new Path(filePath), rowDelimiter, fieldDelimiter, FileOutputFormat.getDefaultWriteMode()); }

Target:
No sure, if we should do it this way. If no write mode is explicitly specified, the system default write mode will be used. If we decide to introduce something like a client option to set the write mode for a session, this would be overwritten by the system default. Why not having two internalWriteAsCsv methods, one with explicit write mode and one without?
Source:
public boolean isConverged(int iteration, LongValue value) { if ( value.getValue() > 3 ) { return true; } else return false; }

Target:
checkstyle will complain here, missing {}.
Source:
public static final int compare(MemorySegment seg1, MemorySegment seg2, int offset1, int offset2, int len) { final byte[] b1 = seg1.memory; final byte[] b2 = seg2.memory; int val = 0; for (int pos = 0; pos < len && (val = (b1[offset1 + pos] & 0xff) - (b2[offset2 + pos] & 0xff)) == 0; pos++) { ; } return val; }

Target:
But this would mean that we deactivate the rule globally. I rather suggest to disable the rule for this specific code block: http://stackoverflow.com/questions/2640110/how-can-you-suppress-checkstyle-checks-within-a-block-of-code-only-for-specific
Source:
public static void writeObjectToConfig(Object o, Configuration config, String key) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(o); byte[] bytes = baos.toByteArray(); config.setBytes(key, bytes); oos.close(); }

Target:
I think this should be after `oos.writeObject(o);`, in case there is buffered data. In any case, before obtaining the `byte[]` result.
Source:
public int compareTo(BlockLocation o) { return (new Long(offset)).compareTo(o.getOffset()); }

Target:
Why are you creating a new Long here? I think a cast should suffice
Source:
public Path getWorkingDirectory() { return new Path(pathToString(workingDirectory)); }

Target:
Why can't you just return `this.workingDirectory` ?
Source:
public void initialize(){ ScheduleExpression scheduleExpression = new ScheduleExpression(); scheduleExpression.hour("*"); scheduleExpression.minute("*"); scheduleExpression.second("*/5"); TimerConfig timerConfig = new TimerConfig(); timerConfig.setInfo("Every 5 second timer"); timerService.createCalendarTimer(scheduleExpression, timerConfig); }

Target:
It might be a little cleaner to use the builder pattern.
Source:
public static String javaVersion(final String def) { final String javaVersionProperty = SafePropertyAccessor.getProperty("java.version", def); if (javaVersionProperty.equals("0")) return "1.7.0"; // Android return javaVersionProperty; }

Target:
makes it no longer null-safe (as it was before) - could you please swap the equals comparison, just in case
Source:
public MongoFeedStatisticsStore build() { return new MongoFeedStatisticsStore(mongo, taskStore, clock, destinationType); }

Target:
same, pass the builder object in
Source:
private static Predicate<Location> isYouViewPlatform() { return new Predicate<Location>() { @Override public boolean apply(Location input) { Policy policy = input.getPolicy(); if (policy == null) { return false; } return Platform.YOUVIEW_IPLAYER.equals(policy.getPlatform()); } }; }

Target:
`return policy != null && Platform.YOUVIEW_IPLAYER.equals(policy.getPlatform())`
Source:
public String generateVersionCrid(Item item, Version version) { String versionCrid = delegate.generateVersionCrid(item, version); Optional<String> value = idMappingStore.getValueFor(version.getCanonicalUri()); if (!value.isPresent() || !versionCrid.equals(value.get())) { idMappingStore.storeMapping(version.getCanonicalUri(), versionCrid); } return versionCrid; }

Target:
This is something that should be private to the store itself. It's a mongo thing we need to protect writes, so a user of it shouldn't need to care.