auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START public JwtConfigurer jwt() { END if ( this.jwtConfigurer == null ) { ApplicationContext context = this.getBuilder().getSharedObject(ApplicationContext.class); this.jwtConfigurer = new JwtConfigurer(context); } return this.jwtConfigurer; } Assert notNull

Target:
public JwtConfigurer jwt() { if ( this.jwtConfigurer == null ) { this.jwtConfigurer = new JwtConfigurer(this.context); } return this.jwtConfigurer; }
Source:
private String getKey() { START if (this.key == null && this.rememberMeServices instanceof AbstractRememberMeServices) { END this.key = ((AbstractRememberMeServices) rememberMeServices).getKey(); } if (this.key == null) { this.key = UUID.randomUUID().toString(); } return this.key; } Please move this check into the `null` check bellow, since we are already checking if `this.key == null`.

Target:
private String getKey() { if (this.key == null) { if (this.rememberMeServices instanceof AbstractRememberMeServices) { this.key = ((AbstractRememberMeServices) rememberMeServices).getKey(); } else { this.key = UUID.randomUUID().toString(); } } return this.key; }
Source:
protected void configure(HttpSecurity http) throws Exception { // @formatter:off START http.rememberMe() END .rememberMeServices(new TokenBasedRememberMeServices("key", userDetailsService())); // @formatter:on } 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 ```

Target:
protected void configure(HttpSecurity http) throws Exception { super.configure(http); // @formatter:off http.rememberMe() .rememberMeServices(new TokenBasedRememberMeServices("key", userDetailsService())); // @formatter:on }
Source:
private boolean isTransientAuthentication(Authentication authentication) { START if (authentication == null ) { END return false; } return AnnotationUtils.getAnnotation(authentication.getClass(), TransientAuthentication.class) != null; } This check is not needed as `authentication` is never `null` based on the call path

Target:
private boolean isTransientAuthentication(Authentication authentication) { return AnnotationUtils.getAnnotation(authentication.getClass(), TransientAuthentication.class) != null; }
Source:
SessionCreationPolicy getSessionCreationPolicy() { if (this.sessionPolicy != null) { return this.sessionPolicy; } START SessionCreationPolicy shared = getBuilder().getSharedObject(SessionCreationPolicy.class); END return shared == null ? SessionCreationPolicy.IF_REQUIRED : shared; } Rename variable `shared` to `sessionCreationPolicy`

Target:
SessionCreationPolicy getSessionCreationPolicy() { if (this.sessionPolicy != null) { return this.sessionPolicy; } SessionCreationPolicy sessionPolicy = getBuilder().getSharedObject(SessionCreationPolicy.class); return sessionPolicy == null ? SessionCreationPolicy.IF_REQUIRED : sessionPolicy; }
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"); START this.handlers = handlers; END this.defaultHandler = defaultHandler; } Do a defensive copy for `handlers` into a new instance of `Map`

Target:
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 = new LinkedHashMap<>(handlers); this.defaultHandler = defaultHandler; }
Source:
START public OAuth2ResourceServerConfigurer<B> resourceServer() throws Exception { END if (this.resourceServerConfigurer == null) { this.initResourceServerConfigurer(); } return this.resourceServerConfigurer; } Remove `throws Exception` as it's never thrown

Target:
public OAuth2ResourceServerConfigurer<B> resourceServer() { if (this.resourceServerConfigurer == null) { this.initResourceServerConfigurer(); } return this.resourceServerConfigurer; }
Source:
START public OAuth2Configurer<HttpSecurity> oauth2() throws Exception { END return getOrApply(new OAuth2Configurer<>()); } Add @since 5.1

Target:
public OAuth2Configurer oauth2() throws Exception { return getOrApply(new OAuth2Configurer()); }
Source:
START public Object cors() throws Exception { END return getOrApply(new CorsConfigurer<HttpSecurity>()); } Should return type `CorsConfigurer<HttpSecurity>`

Target:
public CorsConfigurer<HttpSecurity> cors() throws Exception { return getOrApply(new CorsConfigurer<HttpSecurity>()); }
Source:
public RequestSpec connectTimeout(Duration duration) { delegate.connectTimeout(duration); START return null; END } `return this`?

Target:
public RequestSpec connectTimeout(Duration duration) { delegate.connectTimeout(duration); 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); START this.decompressResponse = false; END } +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.

Target:
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 = true; }
Source:
public void handle(Context context) throws Exception { START if (!name.equals(DEFAULT_NAME_TOKEN)) { END handleByName(context, name); } else { handleAll(context); } } 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.

Target:
public void handle(Context context) throws Exception { if (name != null && !"".equals(name)) { handleByName(context, name); } else { handleAll(context); } }
Source:
public Boolean isAjaxRequest() { START return HttpHeaderConstants.XML_HTTP_REQUEST.equals(headers.get(HttpHeaderConstants.X_REQUESTED_WITH)); END } Should this match be case-sensitive, or case-insensitive?

Target:
public boolean isAjaxRequest() { return HttpHeaderConstants.XML_HTTP_REQUEST.equalsIgnoreCase(headers.get(HttpHeaderConstants.X_REQUESTED_WITH)); }
Source:
private void transmit(final BasicFileAttributes basicFileAttributes, final Object message) throws Exception { transmitterAction.execute(new Action<ResponseTransmitter>() { @Override public void execute(ResponseTransmitter responseTransmitter) { START HttpHeaders httpHeaders = new DefaultHttpHeaders(false); END MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(httpHeaders); responseTransmitter.transmit(HttpResponseStatus.OK, responseHeaders, basicFileAttributes.size(), message); } }); } Why are we doing this instead of using the headers given in the constructor?

Target:
private void transmit(final BasicFileAttributes basicFileAttributes, final Object message) throws Exception { transmitterAction.execute(new Action<ResponseTransmitter>() { @Override public void execute(ResponseTransmitter responseTransmitter) { MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(httpHeaders); responseTransmitter.transmit(HttpResponseStatus.OK, responseHeaders, basicFileAttributes.size(), message); } }); }
Source:
public String getFullRequestURL() { final PublicAddress publicAddress = context.get(PublicAddress.class); START return publicAddress.getAddress(context).toString() + context.getRequest().getUri(); END } 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(); ```

Target:
public String getFullRequestURL() { return getAddress().toString() + context.getRequest().getUri(); }
Source:
public HandlebarsTemplateRenderer(Handlebars handlebars) { this.handlebars = handlebars; START this.templateCache = CacheBuilder.newBuilder() END .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); } }); } Isn't this redundant and not used anywhere anyway?

Target:
public HandlebarsTemplateRenderer(Handlebars handlebars) { this.handlebars = handlebars; }
Source:
public PlayerColor getPiranha() { if (state == RED) return PlayerColor.RED; else if (state == BLUE) return PlayerColor.BLUE; START return null; END } lieber ein `Optional<PlayerColor>` zurueckgeben

Target:
public Optional<PlayerColor> getPiranha() { if (state == RED) return Optional.of(PlayerColor.RED); else if (state == BLUE) return Optional.of(PlayerColor.BLUE); return Optional.empty(); }
Source:
public LogItemViewHolder(View rootView) { this.rootView = rootView; ButterKnife.inject(this, rootView); START rootView.setTag(this); END } I don't like this side-effect. Can you do it in a static method rather than ctor?

Target:
public LogItemViewHolder(View rootView) { this.rootView = rootView; ButterKnife.inject(this, rootView); }
Source:
@Inject public DebugIntentFactory(@IsMockMode boolean isMockMode, @UseExternalApps BooleanPreference useExternalApps) { START super(); END this.isMockMode = isMockMode; this.useExternalApps = useExternalApps; } Delete

Target:
@Inject public DebugIntentFactory(@IsMockMode boolean isMockMode, @UseExternalApps BooleanPreference useExternalApps) { this.isMockMode = isMockMode; this.useExternalApps = useExternalApps; }
Source:
@Override protected void onAttachedToWindow() { super.onAttachedToWindow(); subscriptions.add(timespanSubject // .flatMap(trendingSearch) // START .map(new SearchResultToRepositoryList()), // END trendingAdapter); // Load the default selection. timespanSubject.onNext(timespanAdapter.getItem(timespanView.getSelectedItemPosition())); } Is this guy stateless? There should be a static `instance()` method on it.

Target:
@Override protected void onAttachedToWindow() { super.onAttachedToWindow(); subscriptions.add(timespanSubject // .flatMap(trendingSearch) // .map(SearchResultToRepositoryList.instance()), // trendingAdapter); // Load the default selection. timespanSubject.onNext(timespanAdapter.getItem(timespanView.getSelectedItemPosition())); }
Source:
@Override public String toString() { START return createdSince == null ? "" : "created:>=" + ISO_8601_DATE.print(createdSince); END } While it's kind of not cool to return `null` from `toString`, returning `null` will omit the query parameter from the URL altogether.

Target:
@Override public String toString() { // Returning null here is not ideal, but it lets retrofit drop the query param altogether. return createdSince == null ? null : "created:>=" + ISO_8601_DATE.print(createdSince); }
Source:
protected boolean evaluateFilter(JsonBuilderContext context) { if (filter == null) return true; START int i = 0; END JsonBuilderContext evaluationContenxt = context; while (i < filterContextPos) { evaluationContenxt = evaluationContenxt.getParent(); i++; } return filter.evaluate(evaluationContenxt.getCurrentObj()); } Why couldn't this be written using a simple for loop? I don't see odd exit conditions.

Target:
protected boolean evaluateFilter(JsonBuilderContext context) { if (filter == null) return true; JsonBuilderContext evaluationContenxt = context; for (int i = 0; i < filterContextPos; i++) { evaluationContenxt = evaluationContenxt.getParent(); } return filter.evaluate(evaluationContenxt.getCurrentObj()); }
Source:
public PropertyNameTypeBinding( FilterFactory2 filterFactory, NamespaceSupport namespaceSupport, Catalog catalog) { super(filterFactory, namespaceSupport); START this.namespaceSupport = namespaceSupport; END this.catalog = catalog; } Is this just me, or this assignement became useless? ``` this.namespaceSupport = namespaceSupport; ```

Target:
public PropertyNameTypeBinding( FilterFactory2 filterFactory, NamespaceSupport namespaceSupport, Catalog catalog) { super(filterFactory, namespaceSupport); this.catalog = catalog; }
Source:
private boolean isJsonLdMIME(Request request) { String accept = request.getHttpRequest().getHeader(HttpHeaders.ACCEPT); START if (accept != null && accept.contains(JSONLDGetFeatureResponse.MIME)) return true; END else if (request.getKvp().get("f") != null && request.getKvp().get("f").equals(JSONLDGetFeatureResponse.MIME)) return true; else return false; } Upside down, "f" override accepts, so it should be tested first.

Target:
private boolean isJsonLdMIME(Request request) { String accept = request.getHttpRequest().getHeader(HttpHeaders.ACCEPT); if (request.getKvp().get("f") != null && request.getKvp().get("f").equals(JSONLDGetFeatureResponse.MIME)) return true; else if (accept != null && accept.contains(JSONLDGetFeatureResponse.MIME)) return true; else return false; }
Source:
public JsonLdConfiguration(GeoServerDataDirectory dd) { this.dd = dd; templateCache = CacheBuilder.newBuilder() .maximumSize(10) START .initialCapacity(1) END .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; } }); } 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.

Target:
public JsonLdConfiguration(GeoServerDataDirectory dd) { this.dd = dd; templateCache = CacheBuilder.newBuilder() .maximumSize(100) .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; } }); }
Source:
private boolean checkWMSLayerMinMaxScale(WMSLayerInfo wmsLayerInfo, double mapScale) { // // if none configured if (wmsLayerInfo.getMinScale() == null && wmsLayerInfo.getMaxScale() == null) return true; START if (wmsLayerInfo.getMinScale() != null) END 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; } You can use ``&& mapScale < wmsLayerInfo.getMinScale()`` in the first if, there is short-circuit evaluation

Target:
private boolean checkWMSLayerMinMaxScale(WMSLayerInfo wmsLayerInfo, double mapScale) { // if none configured if (wmsLayerInfo.getMinScale() == null && wmsLayerInfo.getMaxScale() == null) return true; // return false map scale is below min if (wmsLayerInfo.getMinScale() != null && mapScale < wmsLayerInfo.getMinScale()) return false; // return false map scale is above max if (wmsLayerInfo.getMaxScale() != null && mapScale > wmsLayerInfo.getMaxScale()) return false; return true; }
Source:
protected String relativeDataFileURL(String url, Catalog catalog) { if (catalog == null) { return url; } File baseDirectory = catalog.getResourceLoader().getBaseDirectory(); START File f = Resources.find(Resources.fromURL(Files.asResource(baseDirectory), url), true); END return f == null ? url : "file:" + Paths.convert(baseDirectory, f); } 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).

Target:
protected String relativeDataFileURL(String url, Catalog catalog) { if (catalog == null) { return url; } File baseDirectory = catalog.getResourceLoader().getBaseDirectory(); File f = Files.url(baseDirectory, url); return f == null ? url : "file:" + Paths.convert(baseDirectory, f); }
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"); START print(response); END // validate the obtained response checkStation1Exists(response); } A miss?

Target:
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"); // validate the obtained response checkStation1Exists(response); }
Source:
public RestListWrapper<EchoParameter> getEchoParameters() { return new RestListWrapper<>( START EchoParametersDao.getEchoParameters().stream().collect(Collectors.toList()), END EchoParameter.class, this, "id", null); } `EchoParametersDao.getEchoParameters()` already returns a list.

Target:
public RestListWrapper<EchoParameter> getEchoParameters() { return new RestListWrapper<>( EchoParametersDao.getEchoParameters(), EchoParameter.class, this, "id", null); }
Source:
START public static String toString(Document document) throws TransformerException { END 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(); } Does it need to be ``public`` is ``protected`` not enough ?

Target:
protected 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(); }
Source:
public ReferencedEnvelope getBounds(Filter filter) { try { GranuleSource source = reader.getGranules(reader.getGridCoverageNames()[0], true); Query query = new Query(null, filter); START if (filter != null) { END 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); } } I'm not sure, but if we provide the filter in the constructor do we need do set it here ?

Target:
public ReferencedEnvelope getBounds(Filter filter) { try { GranuleSource source = reader.getGranules(reader.getGridCoverageNames()[0], true); Query query = new Query(); 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); } }
Source:
private static Number parseValue(String s, Class dataType) throws ParseException { if (Date.class.isAssignableFrom(dataType)) { long period = TimeParser.parsePeriod(s); START return period; END } else { // TODO: add support for Number, e.g., elevation throw new IllegalArgumentException("Unsupported value type " + dataType); } } Can be returned right away.

Target:
private static Number parseValue(String s, Class dataType) throws ParseException { if (Date.class.isAssignableFrom(dataType)) { return TimeParser.parsePeriod(s); } // TODO: add support for Number, e.g., elevation throw new IllegalArgumentException("Unsupported value type " + dataType); }
Source:
public FileSystemResource(String path) { START this.path = Paths.convert(path); END this.file = Paths.toFile(baseDirectory, path); } 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?

Target:
public FileSystemResource(String path) { this.path = path; this.file = Paths.toFile(baseDirectory, path); }
Source:
public void setKeywords(List<KeywordInfo> keywords) { if (keywords == null) { this.keywords = new ArrayList<>(); } START this.keywords = keywords; END } 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;

Target:
public void setKeywords(List<KeywordInfo> keywords) { this.keywords = keywords == null ? new ArrayList<>() : 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()); START print(dom); END assertEquals("ServiceExceptionReport", dom.getDocumentElement().getNodeName()); assertTrue(dom.getDocumentElement().getTextContent().contains("No LAYERS has been requested")); } Leftover print

Target:
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()); assertEquals("ServiceExceptionReport", dom.getDocumentElement().getNodeName()); assertTrue(dom.getDocumentElement().getTextContent().contains("No LAYERS has been requested")); }
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) { START logger.log(Level.WARNING, "No matching Role [" + rolename + "] on ActiveRoleService", e); END return false; } } Misleading message here?

Target:
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, e.getMessage(), e); return false; } }
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; START while(waited <= 30000 && GWC.get().getGridSetBroker().get(INSPIRE_GRID_SET_NAME) == null) { END // 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)); } 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?

Target:
public void testGridSetLoading() throws Exception { GWC gwc = GWC.get(); // 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)); }
Source:
public JMSSettingsModifyEvent(SettingsInfo source, List<String> propertyNames, List<Object> oldValues, List<Object> newValues, JMSEventType eventType) { super(source, propertyNames, oldValues, newValues); START this.eventType = eventType; END } Does it make sense to have this for a class that states it's "modified"?

Target:
public JMSSettingsModifyEvent(SettingsInfo source, List<String> propertyNames, List<Object> oldValues, List<Object> newValues, JMSEventType eventType) { super(source, propertyNames, oldValues, newValues, eventType); }
Source:
public void loadConfiguration(GeoServerResourceLoader resourceLoader) throws IOException { synchronized (this) { Resource controlflow = resourceLoader.get(PROPERTYFILENAME); if (Resources.exists(controlflow)) { configFile = new PropertyFileWatcher(controlflow); START configFile.setKnownLastModified(System.currentTimeMillis()); END } } } 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.

Target:
public void loadConfiguration(GeoServerResourceLoader resourceLoader) throws IOException { synchronized (this) { Resource controlflow = resourceLoader.get(PROPERTYFILENAME); if (Resources.exists(controlflow)) { configFile = new PropertyFileWatcher(controlflow); } } }
Source:
public List<Resource> getFileLocations() throws IOException { List<Resource> configurationFiles = new ArrayList<>(); START GeoServerResourceLoader loader = GeoServerExtensions.bean(GeoServerResourceLoader.class); END if (loader != null) { Resource f = getConfigurationFile(loader); configurationFiles.add(f); } else if (fw != null && fw.getResource() != null) { configurationFiles.add(fw.getResource()); } return configurationFiles; } The loader is already available via construtor injection, why look it up dynamically at runtime?

Target:
public List<Resource> getFileLocations() throws IOException { List<Resource> configurationFiles = new ArrayList<>(); if (loader != null) { Resource f = getConfigurationFile(loader); configurationFiles.add(f); } else if (fw != null && fw.getResource() != null) { configurationFiles.add(fw.getResource()); } return configurationFiles; }
Source:
protected void setUpTestData(SystemTestData testData) throws Exception { testData.setUpSecurity(); System.setProperty("DefaultCatalogStore", "org.geoserver.csw.store.simple.GeoServerSimpleCatalogStore"); START System.setProperty("ALLOW_ENV_PARAMETRIZATION", "true"); END // 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); } Probably best to set it in the base test class, and make sure it gets cleaned at the end of the test?

Target:
protected void setUpTestData(SystemTestData testData) throws Exception { testData.setUpSecurity(); System.setProperty("DefaultCatalogStore", "org.geoserver.csw.store.simple.GeoServerSimpleCatalogStore"); // 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); }
Source:
public boolean isEnabled(final String serviceId) { checkNotNull(serviceId); if ("wms".equalsIgnoreCase(serviceId)) { return isWMSCEnabled(); } if ("wmts".equalsIgnoreCase(serviceId)) { START throw new ServiceException("To check if WMTS service is enable or disable use service info."); END } if ("tms".equalsIgnoreCase(serviceId)) { return isTMSEnabled(); } return true; } 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?

Target:
public boolean isEnabled(final String serviceId) { checkNotNull(serviceId); if ("wms".equalsIgnoreCase(serviceId)) { return isWMSCEnabled(); } if ("wmts".equalsIgnoreCase(serviceId)) { throw new RuntimeException("To check if WMTS service is enable or disable use service info."); } if ("tms".equalsIgnoreCase(serviceId)) { return isTMSEnabled(); } return true; }
Source:
public Optional<String> getVersion() { if (provider.contains("OracleJDK")) { START return version.ofNullable(System.getProperty("java.version")); END } else { return version.empty(); } } Why do you have `Optional` instance `version` if all you ever use it for is to call these static methods?

Target:
public Optional<String> getVersion() { if (provider.contains("OracleJDK")) { return Optional.ofNullable(System.getProperty("java.version")); } else { return Optional.empty(); } }
Source:
public void convertInput() { START visitChildren(TextArea.class, (Component component, final IVisit<Void> visit) -> { END if (component instanceof TextArea) { TextArea textArea = (TextArea) component; textArea.updateModel(); } }); setConvertedInput(new DefaultValueConfigurations(configurations)); } 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?

Target:
public void convertInput() { visitChildren(TextArea.class, (component, visit) -> { if (component instanceof TextArea) { TextArea textArea = (TextArea) component; textArea.updateModel(); } }); setConvertedInput(new DefaultValueConfigurations(configurations)); }
Source:
public GeoJSONBuilder value(Object value) { if (value instanceof java.util.Date || value instanceof Calendar) { value = Converters.convert(value, String.class); } START if (value instanceof Double) { END value = roundToNumberOfDecimalPlaces((Double)value); } super.value(value); return this; } "else if" maybe?

Target:
public GeoJSONBuilder value(Object value) { if (value instanceof java.util.Date || value instanceof Calendar) { value = Converters.convert(value, String.class); } super.value(value); return this; }
Source:
void cacheData(Resource res, File file) throws IOException { assert res.getType()==Type.RESOURCE; START OutputStream out = new FileOutputStream(file); END try { InputStream in = res.in(); try { IOUtils.copy(in, out); } finally { in.close(); } } finally { out.close(); } } Could this be a single try-with-resources block with two resources and a single statement in the body?

Target:
void cacheData(Resource res, File file) throws IOException { assert res.getType()==Type.RESOURCE; try (OutputStream out = new FileOutputStream(file)) { try (InputStream in = res.in()) { IOUtils.copy(in, out); } } }
Source:
public int anyUpdateQuery(QueryBuilder query) { START try (Connection c = ds.getConnection()) { END 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); } } 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.

Target:
public int anyUpdateQuery(QueryBuilder query) { LOGGER.log(Level.FINEST, query.toString()); try (Connection c = ds.getConnection()) { try (PreparedStatement stmt = query.toStatement(c)) { return stmt.executeUpdate(); } } catch (SQLException ex) { throw new IllegalStateException("UpdateQuery Failed",ex); } }
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 { START result.close(); END } } try-with-resources?

Target:
public void theoryLeavesHaveIstream(String path) throws Exception { Resource res = getResource(path); assumeThat(res, is(resource())); try (InputStream result = res.in()) { assertThat(result, notNullValue()); } }
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(); START } END } @NielsCharlier try-with-resources?

Target:
public DocumentFile(Resource path) throws JDOMException, IOException { if (!Resources.exists(path)) { throw new IllegalArgumentException("Unable to locate the file path: \'" + path + "\'"); } this.path = path; try (InputStream in = path.in()) { this.body = IOUtils.toString(in); } }
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); START print(doc); END assertEquals("map", doc.getDocumentElement().getLocalName()); assertXpathEvaluatesTo("widget", "/map/name", doc); assertXpathEvaluatesTo("12.99", "/map/price", doc); } @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.

Target:
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); }
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); START is.close(); END try { return CRS.parseWKT(wkt); } catch (Exception e) { throw (IOException) new IOException().initCause(e); } } @NielsCharlier is this a possible resource leak? Needs a try-with-resource?

Target:
public CoordinateReferenceSystem readPrjToCRS() throws IOException { Resource prj = getPrjFile(); if (prj == null || !Resources.exists(prj)) { return null; } try (InputStream is = prj.in()) { return CRS.parseWKT(IOUtils.toString(is)); } catch (Exception e) { throw (IOException) new IOException().initCause(e); } }
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 { START IOUtils.closeQuietly(fos); END } infoCache.put(transform, file); } Perhaps try-with-resources? I need to understand suppressed exceptions ...

Target:
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()); try (OutputStream fos = file.out()){ xs.toXML(transform, fos); } infoCache.put(transform, file); }
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(); START BufferedInputStream in = new BufferedInputStream( f.in() ); END try { LoggingInfo loginfo = xp.load(in,LoggingInfo.class); return loginfo; } finally { in.close(); } } else { return null; } } Justin spaces.

Target:
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(); try (BufferedInputStream in = new BufferedInputStream(f.in())) { LoggingInfo loginfo = xp.load(in,LoggingInfo.class); return loginfo; } } else { return null; } }
Source:
public void storeKeyStore() throws IOException{ // store away the keystore assertActivatedKeyStore(); START OutputStream fos = getResource().out(); END char[] passwd = securityManager.getMasterPassword(); try { ks.store(fos, passwd); } catch (Exception e) { throw new IOException(e); } finally { securityManager.disposePassword(passwd); } fos.close(); } Perhaps try-with-resources? Needs care with the disposePassword.

Target:
public void storeKeyStore() throws IOException{ // store away the keystore assertActivatedKeyStore(); try (OutputStream fos = getResource().out()) { char[] passwd = securityManager.getMasterPassword(); try { ks.store(fos, passwd); } catch (Exception e) { throw new IOException(e); } finally { securityManager.disposePassword(passwd); } } }
Source:
public boolean synchronize(DocumentFile event) throws Exception { START OutputStream fout = null; END 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); } } Please convert these tabs to spaces. Can this be converted to a Java 7 try-with-resources?

Target:
public boolean synchronize(DocumentFile event) throws Exception { try (OutputStream 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; } }
Source:
public String getIdValue(Object object, int index) { switch ((StyleType) object) { case GENERIC: START return "Generic"; END case LINE: return "Line"; case POINT: return "Point"; case POLYGON: return "Polygon"; case RASTER: return "Raster"; default: return ""; } } 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).

Target:
public String getIdValue(Object object, int index) { return object.toString(); }
Source:
START private AuthenticationCache lookupAuthenticationCache() { END 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; } Strictly speaking this is API change IMHO, but that's ok :)

Target:
AuthenticationCache lookupAuthenticationCache() { AuthenticationCache authCache = GeoServerExtensions.bean(AuthenticationCache.class); return authCache != null ? authCache : new GuavaAuthenticationCacheImpl(1000); }
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 START Disposer disposer = GeoServerExtensions.bean(Disposer.class); END 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 ); } This code block is repeated over and over (lookup, register and log...) maybe make it a static method in Disposer?

Target:
public synchronized void addListener(File file, String path, ResourceListener listener) { if( watcher == null ){ watcher = new FileSystemWatcher(); } watcher.addListener( file, path, listener ); }
Source:
public DefaultControlFlowConfigurator() { START GeoServerResourceLoader loader = (GeoServerResourceLoader) GeoServerExtensions.bean( "resourceLoader"); END Resource controlflow = loader.get(PROPERTYFILENAME); configFile = new PropertyFileWatcher(controlflow); //configFile = new PropertyFileWatcher(new File(GeoserverDataDirectory.getGeoserverDataDirectory(), PROPERTYFILENAME)); } 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?)

Target:
public DefaultControlFlowConfigurator() { GeoServerResourceLoader loader = GeoServerExtensions.bean(GeoServerResourceLoader.class); Resource controlflow = loader.get(PROPERTYFILENAME); configFile = new PropertyFileWatcher(controlflow); }
Source:
Resource getConfigFile(String configFileLocation ) throws IOException { File file = new File(configFileLocation); Resource resource; START if( file.isAbsolute() ){ END if( file.canRead() ){ return Files.asResource(file); // used by test cases } else { throw new IOException("Cannot read file: "+file.getCanonicalPath()); } } return null; } Several points not respecting our coding conventions here (space in if condition, else not in the same line as the if closing brace)

Target:
Resource getConfigFile(String configFileLocation) throws IOException { File file = new File(configFileLocation); 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; }
Source:
private static void registerGeoShapeBoundsAggregator(ValuesSourceRegistry.Builder builder) { builder.register(GeoBoundsAggregationBuilder.NAME, GeoShapeValuesSourceType.instance(), (GeoBoundsAggregatorSupplier) (name, aggregationContext, parent, valuesSourceConfig, wrapLongitude, metadata) START -> new GeoShapeBoundsAggregator(name, aggregationContext, parent, valuesSourceConfig, wrapLongitude, metadata)); END } Can this be a ctor reference like the others? It *looks* like it from here.

Target:
private static void registerGeoShapeBoundsAggregator(ValuesSourceRegistry.Builder builder) { builder.register(GeoBoundsAggregationBuilder.NAME, GeoShapeValuesSourceType.instance(), (GeoBoundsAggregatorSupplier) GeoShapeBoundsAggregator::new); }
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"); START } END this.analyzer = ((TokenCountFieldMapper)other).analyzer; } for my info, are these newly introduced checks or were they just moved?

Target:
protected void mergeOptions(FieldMapper other, List<String> conflicts) { // TODO we should ban updating analyzers and null values as well if (this.enablePositionIncrements != ((TokenCountFieldMapper)other).enablePositionIncrements) { conflicts.add("mapper [" + name() + "] has a different [enable_position_increments] setting"); } this.analyzer = ((TokenCountFieldMapper)other).analyzer; }
Source:
public ModelPlotConfig(StreamInput in) throws IOException { enabled = in.readBoolean(); terms = in.readOptionalString(); START if (in.getVersion().onOrAfter(Version.V_7_9_0)) { END annotationsEnabled = in.readBoolean(); } else { annotationsEnabled = enabled; } } 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.

Target:
public ModelPlotConfig(StreamInput in) throws IOException { enabled = in.readBoolean(); terms = in.readOptionalString(); annotationsEnabled = in.readBoolean(); }
Source:
public void writeTo(StreamOutput out) throws IOException { out.writeBoolean(enabled); out.writeOptionalString(terms); START if (out.getVersion().onOrAfter(Version.V_7_9_0)) { END out.writeBoolean(annotationsEnabled); } } As above, you might as well just delete this line.

Target:
public void writeTo(StreamOutput out) throws IOException { out.writeBoolean(enabled); out.writeOptionalString(terms); out.writeBoolean(annotationsEnabled); }
Source:
public void testProjectUnresolvedAliasInFilter() { assertEquals("1:8: Unknown column [tni]", error("SELECT tni AS i FROM test WHERE i > 10 GROUP BY i")); START assertEquals("1:31: Unknown column [i]", error("SELECT i AS i FROM test WHERE i > 10 GROUP BY i")); END } Please extra this check in its own test method.

Target:
public void testProjectUnresolvedAliasInFilter() { assertEquals("1:8: Unknown column [tni]", error("SELECT tni AS i FROM test WHERE i > 10 GROUP BY i")); }
Source:
START protected Object parseSourceValue(Object value) { END return value.toString(); } nit: I was wondering if we should use covariance here and anywhere we return Strings, like we do for other types.

Target:
protected String parseSourceValue(Object value) { return value.toString(); }
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); START System.out.println("sel=" + progressBar.getSelection() + work); END } } }); } Does that print out in Eclipse?

Target:
public void worked(final int work) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { if (progressBar.getSelection() >= 100) { progressBar.setSelection(0); } else { progressBar.setSelection(progressBar.getSelection() + work); } } }); }