auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Properties readTDConf() { Properties p = new Properties(); File file = new File(System.getProperty("user.home", "./"), String.format(".td/td.conf")); if (!file.exists()) { START logger.debug(String.format("config file %s is not found", file)); END return p; } return readTDConf(file); } Since this method is designed to read `$HOME/.td/td.conf`, it is better to print the warning in case of file not found.

Target:
public static Properties readTDConf() { Properties p = new Properties(); File file = new File(System.getProperty("user.home", "./"), String.format(".td/td.conf")); if (!file.exists()) { logger.warn(String.format("config file %s is not found", file)); return p; } return readTDConf(file); }
Source:
START public static <T> void checkPresence(Optional<T> opt, String errorMessage) END { if (!opt.isPresent()) { throw new TDClientException(TDClientException.ErrorType.INVALID_INPUT, errorMessage); } } Should this method be private?

Target:
private static <T> void checkPresence(Optional<T> opt, String errorMessage) { if (!opt.isPresent()) { throw new TDClientException(TDClientException.ErrorType.INVALID_INPUT, errorMessage); } }
Source:
private static String validateTableName(String tableName) START { END return validateName(tableName, "Table"); } Why is the modifier private? We should set same modifiers to validateDatabaseName and validateTableNamet methods.

Target:
static String validateTableName(String tableName) { return validateName(tableName, "Table"); }
Source:
public StubSchemaManagementWorkAssert matches(StubSchemaManagementWork expected) { ToStringTreeBuilder builder = new ToStringTreeBuilder( ToStringStyle.multilineDelimiterStructure() ); builder.startObject(); boolean hasAnyMismatch; boolean mismatch = checkForMismatch( builder, "type", expected.getType(), actual.getType() ); START hasAnyMismatch = mismatch; END builder.endObject(); if ( hasAnyMismatch ) { Assert.fail( messageBase + builder.toString() ); } return this; } Do we need the `mismatch` variable? Shouldn't we assign the result of checkForMismatch directly to `hasAnyMismatch`?

Target:
public StubSchemaManagementWorkAssert matches(StubSchemaManagementWork expected) { ToStringTreeBuilder builder = new ToStringTreeBuilder( ToStringStyle.multilineDelimiterStructure() ); builder.startObject(); boolean hasAnyMismatch = checkForMismatch( builder, "type", expected.getType(), actual.getType() ); builder.endObject(); if ( hasAnyMismatch ) { Assert.fail( messageBase + builder.toString() ); } return this; }
Source:
public void setup() { setupHelper.start( BACKEND_1_NAME ) START .withBackendProperty( BACKEND_1_NAME, "directory.type", directoryType ) END .withIndex( INDEX_NAME_1_1, ctx -> this.indexMapping_1_1 = new IndexMapping_1_1( ctx.getSchemaElement() ), indexMapping -> this.indexManager_1_1 = indexMapping ) .withIndex( INDEX_NAME_1_2, ctx -> this.indexMapping_1_2 = new IndexMapping_1_2( ctx.getSchemaElement() ), indexMapping -> this.indexManager_1_2 = indexMapping ) .setup(); initData(); } You no longer need to define and pass a backend name. You can call `start()` and `withBackendProperty( "directory.type", directoryType )`.

Target:
public void setup() { setupHelper.start() .withBackendProperty( "directory.type", directoryType ) .withIndex( INDEX_NAME_1_1, ctx -> this.indexMapping_1_1 = new IndexMapping_1_1( ctx.getSchemaElement() ), indexMapping -> this.indexManager_1_1 = indexMapping ) .withIndex( INDEX_NAME_1_2, ctx -> this.indexMapping_1_2 = new IndexMapping_1_2( ctx.getSchemaElement() ), indexMapping -> this.indexManager_1_2 = indexMapping ) .setup(); initData(); }
Source:
void closeOnFailure() { try ( Closer<RuntimeException> closer = new Closer<>() ) { closer.push( IdentifierMappingImplementor::close, identifierMapping ); closer.push( RoutingKeyProvider::close, routingKeyProvider ); START closer.push( BeanHolder::close, providedIdentifierBridgeHolder ); END } } I don't think you need this, as `identifierMapping.close()` (above) will effectively close the bridge, and it's very unlikely (impossible?) that a failure occurs between the assignment of `providedIdentifierBridgeHolder` and the assignment of `identifierMapping`. So, to clarify: you can remove `providedIdentifierBridgeHolder` and use a local variable instead, then remove this line.

Target:
void closeOnFailure() { try ( Closer<RuntimeException> closer = new Closer<>() ) { closer.push( IdentifierMappingImplementor::close, identifierMapping ); closer.push( RoutingKeyProvider::close, routingKeyProvider ); } }
Source:
public void handle(FailureContext context) { // <1> try { String failingOperationDescription = context.getFailingOperation().toString(); // <2> Throwable throwable = context.getThrowable(); // <3> // ... report the failure ... // <4> } catch (Throwable t) { // ... handle the failure and do *not* propagate the throwable ... // <5> START } END } Why leave the burden of capturing the exception to the user?

Target:
public void handle(FailureContext context) { // <1> String failingOperationDescription = context.getFailingOperation().toString(); // <2> Throwable throwable = context.getThrowable(); // <3> // ... report the failure ... // <4> }
Source:
public boolean hasCompatibleAnalyzer(ElasticsearchFieldPredicateBuilderFactory other) { if ( !getClass().equals( other.getClass() ) ) { return false; } ElasticsearchTextFieldPredicateBuilderFactory castedOther = (ElasticsearchTextFieldPredicateBuilderFactory) other; return Objects.equals( analyzer, castedOther.analyzer ) && START Objects.equals( searchAnalyzer, castedOther.searchAnalyzer ) && END Objects.equals( normalizer, castedOther.normalizer ); } If the search analyzers are the same but the analyzers are different, this should return true, I think. And the tests should probably reflect that... ? In fact, you could solve this easily by only keeping the search analyzer in this class, and using the analyzer as a default when the search analyzer is `null`.

Target:
public boolean hasCompatibleAnalyzer(ElasticsearchFieldPredicateBuilderFactory other) { if ( !getClass().equals( other.getClass() ) ) { return false; } ElasticsearchTextFieldPredicateBuilderFactory castedOther = (ElasticsearchTextFieldPredicateBuilderFactory) other; return Objects.equals( analyzer, castedOther.analyzer ) && Objects.equals( normalizer, castedOther.normalizer ); }
Source:
public Instant toIndexedValue(Date value, ValueBridgeToIndexedValueContext context) { if ( value == null ) { return null; } // java.sql.Date does not support toInstant(). See HSEARCH-3670. // We're using here the same strategy applied on DefaultJavaSqlDateValueBridge to handle them. START return value instanceof java.sql.Date ? Instant.ofEpochMilli( value.getTime() ) : value.toInstant(); END } Couldn't we always use `Instant.ofEpochMilli( value.getTime() )`? That would spare us one `instanceof`.

Target:
public Instant toIndexedValue(Date value, ValueBridgeToIndexedValueContext context) { if ( value == null ) { return null; } // java.sql.* types do not support toInstant(). See HSEARCH-3670 return Instant.ofEpochMilli( value.getTime() ); }
Source:
START void process() { END sendCommandsToDelegate(); getDelegate().prepare(); } Is there a reason to use `process` at mapper level and `prepare` at engine/backend level?

Target:
void process() { sendCommandsToDelegate(); getDelegate().process(); }
Source:
public SortField customType() { START BytesRef byteRefMissingValue = new BytesRef( missingValue.toString() ); END return new SortField( absoluteFieldPath, new LuceneMissingValueComparatorSource( byteRefMissingValue ), order == SortOrder.DESC ); } I'd rather use `(String) missingValue` than `missingValue.toString()`. That way, if we ever end up with anything else than a `String` here, it will fail and we will know something is wrong. But more to the point... You could just make `org.hibernate.search.backend.lucene.types.sort.impl.LuceneTextFieldSortBuilder#encodeMissingAs` return the `BytesRef` directly. Right now `encodeMissingAs` method converts the `BytesRef` to a `String`, then `customType` converts it back to a `BytesRef`. And as far as I can tell, only `customType` uses the value, since the call to `setEffectiveMissingValue` will only ever happen if `missingValue` is `null` or `SortMissingValue.MISSING_FIRST` or `SortMissingValue.MISSING_LAST`.

Target:
public SortField customType() { return new SortField( absoluteFieldPath, new LuceneMissingValueComparatorSource( (BytesRef) missingValue ), order == SortOrder.DESC ); }
Source:
START public static void initializeIndexIfNeeded(Directory directory, EventContext eventContext) throws IOException { END if ( DirectoryReader.indexExists( directory ) ) { return; } try { IndexWriterConfig iwriterConfig = new IndexWriterConfig( AnalyzerConstants.KEYWORD_ANALYZER ) .setOpenMode( OpenMode.CREATE_OR_APPEND ); //Needs to have a timeout higher than zero to prevent race conditions over (network) RPCs //for distributed indexes (Infinispan but probably also NFS and similar) SleepingLockWrapper delayedDirectory = new SleepingLockWrapper( directory, 2000, 20 ); IndexWriter iw = new IndexWriter( delayedDirectory, iwriterConfig ); iw.close(); } catch (LockObtainFailedException lofe) { log.lockingFailureDuringInitialization( directory.toString() ); } } I'm not sure that the parameter `eventContext` is used in the method body.

Target:
public static void initializeIndexIfNeeded(Directory directory, EventContext eventContext) throws IOException { if ( DirectoryReader.indexExists( directory ) ) { return; } try { IndexWriterConfig iwriterConfig = new IndexWriterConfig( AnalyzerConstants.KEYWORD_ANALYZER ) .setOpenMode( OpenMode.CREATE_OR_APPEND ); //Needs to have a timeout higher than zero to prevent race conditions over (network) RPCs //for distributed indexes (Infinispan but probably also NFS and similar) SleepingLockWrapper delayedDirectory = new SleepingLockWrapper( directory, 2000, 20 ); IndexWriter iw = new IndexWriter( delayedDirectory, iwriterConfig ); iw.close(); } catch (LockObtainFailedException lofe) { log.lockingFailureDuringInitialization( directory.toString(), eventContext ); } }
Source:
START public Integer getScalingFactor() { END return scalingFactor; } I think I mentioned that: there should be a new test regarding validation of this attribute in `ElasticsearchSchemaAttributeValidationIT`. Unless I missed it, there isn't any?

Target:
public Double getScalingFactor() { return scalingFactor; }
Source:
public ScaledNumberIndexFieldTypeContext<?, BigDecimal> asBigDecimal() { START return new StubScaledNumberIndexFieldTypeContext( BigDecimal.class, defaultsProvider ); END } Missing `<>`, this is a raw type.

Target:
public ScaledNumberIndexFieldTypeContext<?, BigDecimal> asBigDecimal() { return new StubScaledNumberIndexFieldTypeContext<>( BigDecimal.class, defaultsProvider ); }
Source:
START public void setComponent(T component) { END this.component = component; } I don't see why you introduced mutability here? Local variables would have worked just as well. If you really want that, please at least make the setters package-private.

Target:
void setComponent(T component) { this.component = component; }
Source:
START public static Instant parseInstant(String value) { END // Using the default ISO format DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT; try { return Instant.parse( value ); } catch (DateTimeParseException e) { throw log.unableToParseTemporal( Instant.class, value, formatter, e ); } } I just noticed that you were displaying the formatter in the error message, so you probably wanted to actually use that formatter when parsing. That makes sense. Anyway, you already changed it, it will work just as well :)

Target:
public static Instant parseInstant(String value) { try { // Using the default ISO format return Instant.parse( value ); } catch (DateTimeParseException e) { throw log.unableToParseTemporal( Instant.class, value, DateTimeFormatter.ISO_INSTANT, e ); } }
Source:
START public BackendInitialBuildState<?> getBackend(String backendName) { END if ( StringHelper.isEmpty( backendName ) ) { backendName = getDefaultBackendName(); } return backendBuildStateByName.computeIfAbsent( backendName, this::createBackend ); } It's not critical, but shall we need to expose this method outside, instead of exposing just: `getIndexManagerBuildingState( backendName, indexName, multiTenancyEnabled )`?

Target:
BackendInitialBuildState<?> getBackend(String backendName) { if ( StringHelper.isEmpty( backendName ) ) { backendName = getDefaultBackendName(); } return backendBuildStateByName.computeIfAbsent( backendName, this::createBackend ); }
Source:
public FieldProjectionContext<Object> rawField(String absoluteFieldPath) { START return field( absoluteFieldPath, Object.class ); END } This seems wrong, it should be `rawField( absoluteFieldPath, Object.class )`. And tests do not fail, so you're missing a test here.

Target:
public FieldProjectionContext<Object> rawField(String absoluteFieldPath) { return rawField( absoluteFieldPath, Object.class ); }
Source:
public Optional<FieldProjectionExpectations<Double>> getFieldProjectionExpectations() { return Optional.of( new FieldProjectionExpectations<>( START 1.001, 3.0, 5.1 END ) ); } While we're at it... Maybe use a negative value in there, too?

Target:
public Optional<FieldProjectionExpectations<Double>> getFieldProjectionExpectations() { return Optional.of( new FieldProjectionExpectations<>( -1.001, 3.0, 5.1 ) ); }
Source:
public Integer encode(MonthDay value) { if ( value == null ) { return null; } START return 37 * value.getMonthValue() + value.getDayOfMonth(); END } Not sure where that `37` comes from. I suppose it's because it's the first prime number above `31`. Just multiplying by `100` would have made the trick here, not sure it's worth trying this hard.

Target:
public Integer encode(MonthDay value) { if ( value == null ) { return null; } return 100 * value.getMonthValue() + value.getDayOfMonth(); }
Source:
public Borrowal(Account account, DocumentCopy<?> copy, BorrowalType type) { this.account = account; this.copy = copy; this.type = type; account.getBorrowals().add( this ); START copy.getBorrowals().add( this ); END } Yeah... same as the other ones. I don't think this is a good idea, this should be in the repository or service code.

Target:
public Borrowal(Account account, DocumentCopy<?> copy, BorrowalType type) { this.account = account; this.copy = copy; this.type = type; }
Source:
START public long getResultSize() { END try { return searchQuery.executeCount(); } catch (QueryExecutionRequestException | ArithmeticException e) { throw new IllegalStateException( e ); } catch (TypeMismatchException e) { throw new IllegalArgumentException( e ); } catch (HibernateException he) { throw getExceptionConverter().convert( he ); } } Could you move this method next to `doHibernateSearchList`? This class is already a bit hard to read due to the many methods, so we should take extra care to keep related methods together... Sorry, I know we shouldn't have to do that :/

Target:
public long getResultSize() { try { return searchQuery.executeCount(); } catch (QueryExecutionRequestException e) { throw new IllegalStateException( e ); } catch (TypeMismatchException e) { throw new IllegalArgumentException( e ); } catch (HibernateException he) { throw getExceptionConverter().convert( he ); } }
Source:
protected Query doBuild(LuceneSearchPredicateContext context) { Builder builder = new BooleanQuery.Builder(); START values.forEach( value -> builder.add( termQuery( value ), Occur.SHOULD ) ); END BooleanQuery query = builder.build(); return query; } Same here, I would avoid the lambda.

Target:
protected Query doBuild(LuceneSearchPredicateContext context) { Builder builder = new BooleanQuery.Builder(); for ( String value : values ) { builder.add( termQuery( value ), Occur.SHOULD ); } return builder.build(); }
Source:
public Object get(Object thiz) { try { return getter.invoke( thiz ); } catch (Error e) { throw e; } catch (Throwable e) { if ( e instanceof InterruptedException ) { Thread.currentThread().interrupt(); } START throw log.errorInvokingMember( member.getName(), thiz.toString(), e ); END } } Just pass `thiz` with type `Object` instead of `thiz.toString()` here, the JBoss logger should call `toString()` automatically, and if for some reason `thiz` is null, it will not throw an NPE like this code.

Target:
public Object get(Object thiz) { try { return getter.invoke( thiz ); } catch (Error e) { throw e; } catch (Throwable e) { if ( e instanceof InterruptedException ) { Thread.currentThread().interrupt(); } throw log.errorInvokingMember( member, thiz, e ); } }
Source:
public Analyzer wrapNormalizer(String name, Analyzer normalizer) { START return new HibernateSearchNormalizerWrapper( normalizer, name ); END } Minor nitpicking but it's weird to have the order of parameters reversed between these 2 lines.

Target:
public Analyzer wrapNormalizer(String name, Analyzer normalizer) { return new HibernateSearchNormalizerWrapper( name, normalizer ); }
Source:
public LuceneCollectors build() { if ( luceneCollectors.isEmpty() ) { START throw new AssertionFailure( "No collectors have been defined: we need at least one." ); END } Collector compositeCollector; if ( luceneCollectors.size() == 1 ) { compositeCollector = topDocsCollector != null ? topDocsCollector : totalHitCountCollector; } else { compositeCollector = MultiCollector.wrap( luceneCollectors ); } return new LuceneCollectors( topDocsCollector, totalHitCountCollector, compositeCollector ); } Wouldn't that happen when someone projects on an empty list of projections? Which, granted, doesn't seem very useful, but could nevertheless happen, especially when someone is only after the number of results. Maybe a safer approach would be to use a `TotalHitCountCollector` by default.

Target:
public LuceneCollectors build() { Collector compositeCollector; if ( luceneCollectors.size() == 1 ) { compositeCollector = luceneCollectors.get( 0 ); } else { compositeCollector = MultiCollector.wrap( luceneCollectors ); } return new LuceneCollectors( topDocsCollector, totalHitCountCollector, compositeCollector ); }
Source:
public boolean isCompatibleWith(LuceneIndexSchemaFieldNode<?> other) { return converter.isDslCompatibleWith( other.converter ) && Objects.equals( codec, other.codec ) && predicateBuilderFactory.isDslCompatibleWith( other.predicateBuilderFactory ) && Objects.equals( sortContributor, other.sortContributor ) START && Objects.equals( projectionBuilderFactory, other.projectionBuilderFactory ); END } Ok, as discussed on HipChat, let's drop support for index-sensitive projections for now, and restore it later (maybe).

Target:
public boolean isCompatibleWith(LuceneIndexSchemaFieldNode<?> other) { return converter.isDslCompatibleWith( other.converter ) && Objects.equals( codec, other.codec ) && predicateBuilderFactory.isDslCompatibleWith( other.predicateBuilderFactory ) && Objects.equals( sortContributor, other.sortContributor ) && projectionBuilderFactory.isDslCompatibleWith( other.projectionBuilderFactory ); }
Source:
START protected void setUp() throws Exception { END buildSessionFactories( getAnnotatedClasses(), getAnnotatedPackages(), getXmlFiles() ); lastTestClass = getClass(); } You should probably make the method `public` just for consistency... Same for `tearDown`.

Target:
public void setUp() throws Exception { buildSessionFactories( getAnnotatedClasses(), getAnnotatedPackages(), getXmlFiles() ); lastTestClass = getClass(); }
Source:
public static <T> T instanceFromClass(Class<T> targetSuperType, Class<?> classToLoad, String componentDescription) { checkClassType( classToLoad, componentDescription ); START final Constructor<?> constructor = getNoArgConstructor( classToLoad, componentDescription ); END final Object instance = untypedInstanceFromClass( classToLoad, componentDescription ); return verifySuperTypeCompatibility( targetSuperType, instance, classToLoad, componentDescription ); } This variable is never used. Maybe this line should be removed?

Target:
public static <T> T instanceFromClass(Class<T> targetSuperType, Class<?> classToLoad, String componentDescription) { checkClassType( classToLoad, componentDescription ); final Object instance = untypedInstanceFromClass( classToLoad, componentDescription ); return verifySuperTypeCompatibility( targetSuperType, instance, classToLoad, componentDescription ); }
Source:
synchronized void stopVirtual() { userCounter--; if ( userCounter == 0 ) { if ( status != ServiceStatus.RUNNING ) { stateExpectedFailure(); } START stopReal(); END } else if ( status != ServiceStatus.RUNNING ) { //Could happen on circular dependencies stateExpectedFailure(); } } If I understand correctly, this commit also makes the wrappers remain in the cache when they are stopped. But I suppose it is on purpose?

Target:
synchronized void stopVirtual() { userCounter--; if ( userCounter == 0 ) { //Do not check for the expected status in this case: we don't want a previous service start failure to //prevent us to further attempt to stop services. stopReal(); } }
Source:
public TokenizerClassNameToElasticsearchTypeNameTransformer(Class<?> factoryClass, String parameterName) { START super(); END this.factoryClass = factoryClass; this.parameterName = parameterName; } You can remove the `super();`.

Target:
public TokenizerClassNameToElasticsearchTypeNameTransformer(Class<?> factoryClass, String parameterName) { this.factoryClass = factoryClass; this.parameterName = parameterName; }
Source:
public void configureFieldMetadata(String name, FieldMetadataBuilder builder) { START builder.field( "value", FieldType.OBJECT ); END } This should not be a hardcoded constant (`"value"`), but simply `name`. I know this won't change anything in practice, but it's just in case people copy/paste this code.

Target:
public void configureFieldMetadata(String name, FieldMetadataBuilder builder) { builder.field( name, FieldType.OBJECT ); }
Source:
public void configureFieldMetadata(String name, FieldMetadataBuilder builder) { FieldMetadataCreationContext field = builder.field( name, FieldType.OBJECT ); if ( dynamicType != null ) { START field.mappedOn( Elasticsearch.class ) END .dynamic( DynamicType.TRUE ); } } `Elasticsearch` and `DynamicType` are impl types as per there packages. They should not be accessed here.

Target:
public void configureFieldMetadata(String name, FieldMetadataBuilder builder) { FieldMetadataCreationContext field = builder.field( name, FieldType.OBJECT ); if ( dynamicType != null ) { field.mappedOn( Elasticsearch.class ) .dynamic( dynamicType ); } }
Source:
START static String getDocumentId(LuceneWork work) { END return work.getTenantId() == null ? work.getIdInString() : work.getTenantId() + "_" + work.getIdInString(); } Is it used anywhere else? If not, let's make it private (I suppose it was the purpose of dropping `DocumentIdHelper`).

Target:
private String getDocumentId(LuceneWork work) { return work.getTenantId() == null ? work.getIdInString() : work.getTenantId() + "_" + work.getIdInString(); }
Source:
public void setUp() throws Exception { super.setUp(); Transaction tx = openSession().beginTransaction(); START A a = new A(); END a.value = "1"; getSession().save( a ); tx.commit(); getSession().close(); this.fullTextSession = Search.getFullTextSession( openSession() ); } Why do you need to have a value for Elasticsearch?

Target:
public void setUp() throws Exception { super.setUp(); Transaction tx = openSession().beginTransaction(); getSession().save( new A() ); tx.commit(); getSession().close(); this.fullTextSession = Search.getFullTextSession( openSession() ); }
Source:
private String analyzerName(Class<?> entityType, DocumentFieldMetadata fieldMetadata) { AnalyzerReference analyzer = fieldMetadata.getAnalyzer(); if ( analyzer.is( RemoteAnalyzerReference.class ) ) { return analyzer.unwrap( RemoteAnalyzerReference.class ).getName(); } START LOG.analyzerIsNotRemote( entityType, fieldMetadata.getFieldName(), analyzer.toString() ); END return null; } if you simply delete the "toString", you can have the formatter invoke that if it's needed. That will avoid creating the String when the log level is disabled.. although it's WARN in this case so it shouldn't matter much, just pointing out that a `toString()` looks suspicious

Target:
private String analyzerName(Class<?> entityType, DocumentFieldMetadata fieldMetadata) { AnalyzerReference analyzer = fieldMetadata.getAnalyzer(); if ( analyzer.is( RemoteAnalyzerReference.class ) ) { return analyzer.unwrap( RemoteAnalyzerReference.class ).getName(); } LOG.analyzerIsNotRemote( entityType, fieldMetadata.getFieldName(), analyzer ); return null; }
Source:
public static boolean isSupported(Class<? extends DeletionQuery> type) { if ( SUPPORTED_TYPES == null ) { // LAZY init, but don't to it more than once START SUPPORTED_TYPES_LOCK.lock(); END try { if ( SUPPORTED_TYPES == null ) { Set<Class<? extends DeletionQuery>> set = new HashSet<>(); set.add( SingularTermDeletionQuery.class ); SUPPORTED_TYPES = Collections.unmodifiableSet( set ); } } finally { SUPPORTED_TYPES_LOCK.unlock(); } } return SUPPORTED_TYPES.contains( type ); } You still do the locking thingy here. I'd if/else on the given class and you are done. Esp. since there is no way to plug in another type anyways. Or is there? Also the single user of this method raises an exception in case the type would be "not supported". This all seems still a bit odd to me, at least I don't see how it would work.

Target:
public static boolean isSupported(Class<? extends DeletionQuery> type) { if ( SingularTermDeletionQuery.class == type ) { return true; } return false; }
Source:
private ErrorHandler createErrorHandlerFromString(String errorHandlerClassName, ClassLoaderService classLoaderService) { START if ( StringHelper.isEmpty( errorHandlerClassName ) || "log".equals( errorHandlerClassName.trim() ) ) { END return new LogErrorHandler(); } else { Class<?> errorHandlerClass = classLoaderService.classForName( errorHandlerClassName ); return ClassLoaderHelper.instanceFromClass( ErrorHandler.class, errorHandlerClass, "Error Handler" ); } } Should 'log' maybe be a constant, making it clear that it is the shortcut name of the logging error handler?

Target:
private ErrorHandler createErrorHandlerFromString(String errorHandlerClassName, ClassLoaderService classLoaderService) { if ( StringHelper.isEmpty( errorHandlerClassName ) || ErrorHandler.LOG.equals( errorHandlerClassName.trim() ) ) { return new LogErrorHandler(); } else { Class<?> errorHandlerClass = classLoaderService.classForName( errorHandlerClassName ); return ClassLoaderHelper.instanceFromClass( ErrorHandler.class, errorHandlerClass, "Error Handler" ); } }
Source:
private void wakeUpConsumer() { START if ( LockSupport.getBlocker( consumerThread ) != null ) { END LockSupport.unpark( consumerThread ); } } I think we might have a tricky race condition here: fail to unpark the consumer thread, while the consumer is about to park (but already did check that the queue is empty).

Target:
private void wakeUpConsumer() { LockSupport.unpark( consumerThread ); }
Source:
public void startWatching(Collection<File> paths) { START closeLock.readLock().lock(); END try { ensureOpen(); startWatching0(server, toAbsolutePaths(paths)); } finally { closeLock.readLock().unlock(); } } I am not sure we need to make the `FileWatcher` here thread safe. I think it is perfectly fine if it isn't thread safe.

Target:
public void startWatching(Collection<File> paths) { ensureOpen(); startWatching0(server, toAbsolutePaths(paths)); }
Source:
public <T> T findAndDelete(final Query<T> query) { FindAndModifyOptions options = new FindAndModifyOptions() START .remove(true) END .returnNew(false) .upsert(false); return findAndDelete(query, options); } These three lines are redundant with lines 291-293 below

Target:
public <T> T findAndDelete(final Query<T> query) { return findAndDelete(query, new FindAndModifyOptions()); }
Source:
public T get(final FindOptions options) { final MorphiaIterator<T, T> it = fetch(options .copy() .limit(1)); T t = (it.hasNext()) ? it.next() : null; START it.close(); END return t; } If you're going to add a close best to do it in a finally block.

Target:
public T get(final FindOptions options) { final MorphiaIterator<T, T> it = fetch(options .copy() .limit(1)); try { return (it.hasNext()) ? it.next() : null; } finally { it.close(); } }
Source:
START DatastoreImpl(final Morphia morphia, final MongoClient mongoClient, final String dbName) { END this(morphia, morphia.getMapper(), mongoClient, dbName); } What are the implications of breaking binary compatibility here? What class of users is this likely to affect? If at all possible the existing public constructors should be deprecated rather than removed.

Target:
public DatastoreImpl(final Morphia morphia, final MongoClient mongoClient, final String dbName) { this(morphia, morphia.getMapper(), mongoClient, dbName); }
Source:
public DB getDB() { START return db != null ? db : mongoClient.getDB(database.getName()); END } I don't see much point in making db lazily created. It's not an expensive operation.

Target:
public DB getDB() { return db; }
Source:
public static IndexType fromValue(final Object value) { for (IndexType indexType : values()) { START if (indexType.type.equals(value) || indexType.name().equals(value)) { END return indexType; } } throw new IllegalArgumentException("No enum value found for " + value); } Don't allow comparison against both the name and the value. That's confusing.

Target:
public static IndexType fromValue(final Object value) { for (IndexType indexType : values()) { if (indexType.type.equals(value)) { return indexType; } } throw new IllegalArgumentException("No enum value found for " + value); }
Source:
START List<ClassMethodPair> getLifecycleMethods(final Class<Annotation> clazz) { END return lifecycleMethods.get(clazz); } Why the binary compat break?

Target:
public List<ClassMethodPair> getLifecycleMethods(final Class<Annotation> clazz) { return lifecycleMethods.get(clazz); }
Source:
public GCModel read() throws IOException { getLogger().info("Reading Shenandoah format..."); GCModel model = new GCModel(); model.setFormat(GCModel.Format.RED_HAT_SHENANDOAH_GC); START Stream<String> lines = new BufferedReader(in).lines(); END lines.filter(this::lineNotInExcludedStrings) .map(this::parseShenandoahEvent) .filter(Objects::nonNull) .forEach(model::add); return model; } No need to wrap "in" in a BufferedReader. It is a LineNumberReader, which is a subclass of BufferedReader.

Target:
public GCModel read() throws IOException { getLogger().info("Reading Shenandoah format..."); GCModel model = new GCModel(); model.setFormat(GCModel.Format.RED_HAT_SHENANDOAH_GC); Stream<String> lines = in.lines(); lines.filter(this::lineNotInExcludedStrings) .map(this::parseShenandoahEvent) .filter(Objects::nonNull) .forEach(model::add); return model; }
Source:
public Iterable<String> getColNames() { return Iterables.transform(fields, new Function<Field, String>() { @Override @Nullable START public String apply(Field arg0) END { return arg0.getSqlName(); } }); } @Nullable annotation implies that the argument could be null. Correct fix is to keep the @Nullable annotation and do the following: return arg0 != null ? arg0.getSqlName() : null;

Target:
public Iterable<String> getColNames() { return Iterables.transform(fields, new Function<Field, String>() { @Override @Nullable public String apply(@Nullable Field arg0) { return arg0 != null ? arg0.getSqlName() : null; } }); }
Source:
public static String getDownloadUrlSuffix(Release.Edition edition) { switch (edition) { case DEVELOPER: return DOWNLOAD_DEVELOPER_URL_SUFFIX; case ENTERPRISE: return DOWNLOAD_ENTERPRISE_URL_SUFFIX; case DATACENTER: return DOWNLOAD_DATACENTER_URL_SUFFIX; default: START case COMMUNITY: END return DOWNLOAD_URL_SUFFIX; } } This `case` looks redundant with the `default`.

Target:
public static String getDownloadUrlSuffix(Release.Edition edition) { switch (edition) { case DEVELOPER: return DOWNLOAD_DEVELOPER_URL_SUFFIX; case ENTERPRISE: return DOWNLOAD_ENTERPRISE_URL_SUFFIX; case DATACENTER: return DOWNLOAD_DATACENTER_URL_SUFFIX; default: return DOWNLOAD_URL_SUFFIX; } }
Source:
public LineRecordWriter(DataOutputStream out) { this.out = out; jsonMapper.getFactory() .configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true); jsonWriter = jsonMapper.writer(new JsonIndenter()); try { START out.writeBytes("["); END } catch (IOException e) { } } With JSON lines the opening `[` isn't necessary anymore.

Target:
public LineRecordWriter(DataOutputStream out) { this.out = out; jsonMapper.getFactory() .configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true); jsonWriter = jsonMapper.writer(new JsonIndenter()); }
Source:
public boolean filter(String fromUrl, String toUrl) { //this implementation doesnt do anything with fromUrl if (exemptions != null) { for (Pattern pattern : exemptions) { START if (pattern.matcher(toUrl).matches()) { END return true; //If a regex matches, then exempted } } } //not exempted return false; } Could possibly use Pattern.find() instead of Pattern.matches(): - would make patterns often shorter: `\.jpg$` instead of `.*\.jpg` (or `.*\.jpg$`) - (more important) the syntax would be the same as for urlfilter-regex rules

Target:
public boolean filter(String fromUrl, String toUrl) { //this implementation does not consider fromUrl param. //the regex rules are applied to toUrl. return this.filter(toUrl) != null; }
Source:
START private String getVersionInformation(PersistentEntity persistentEntity, Object domainObject){ END if(persistentEntity.hasVersionProperty()) { BeanWrapper<Object> beanWrapper = BeanWrapper.create(domainObject, conversionService); Object version = beanWrapper.getProperty(persistentEntity.getVersionProperty()); try { return "\"" + objectMapper.writeValueAsString(version) + "\""; } catch (JsonProcessingException e) { LOG.error("Creation of Etag header failed", e); } } return null; } What's the reason we invoke Jackson mapping here? Shouldn't a plain `toString()` be sufficient?

Target:
private String getVersionInformation(PersistentEntity persistentEntity, Object domainObject) { if (persistentEntity.hasVersionProperty()) { BeanWrapper<Object> beanWrapper = BeanWrapper.create(domainObject, conversionService); Object version = beanWrapper.getProperty(persistentEntity.getVersionProperty()); return "\"" + version.toString() + "\""; } return null; }
Source:
public void should_generate_yaml() throws Exception { RestxSpec testCase = restxSpecLoader.load( "restx/tests/restx_test_case_example_1.yaml"); String actual = testCase.toString(); System.out.println("actual = " + actual); START assertThat(replaceNewLine(actual)).isEqualTo(replaceNewLine(Resources.toString( END Resources.getResource("restx/tests/expected_restx_case_example_1.yaml"), Charsets.UTF_8))); } Is it really worth replacing new lines on *both* sides here ? (sounds like useless as it is, but I may be missing something)

Target:
public void should_generate_yaml() throws Exception { RestxSpec testCase = restxSpecLoader.load( "restx/tests/restx_test_case_example_1.yaml"); String actual = testCase.toString(); // System.out.println("actual = " + actual); assertThat(actual).isEqualTo(Resources.toString( Resources.getResource("restx/tests/expected_restx_case_example_1.yaml"), Charsets.UTF_8)); }
Source:
private ResourceLock newWriteUnlocker() { START return () -> CloseableReentrantReadWriteLock.this.writeLock().unlock(); END } why `this.writeLock().unlock()` is not enough?

Target:
private ResourceLock newWriteUnlocker() { return () -> this.writeLock().unlock(); }
Source:
private WFSTCompletionLookup build(final IndexReader indexReader, final String field) throws IOException { WFSTInputIterator iterator = new WFSTInputIterator( new LuceneDictionary(indexReader, field).getEntryIterator(), indexReader, field, getSearchCounts(field)); WFSTCompletionLookup lookup = createWFST(); lookup.build(iterator); START if (iterator.termLengthAccumulator > 0) { END double averageLength = (double) iterator.termLengthAccumulator / lookup.getCount(); averageLengths.put(field, averageLength); } return lookup; } I'd prefer the condition to check `lookup.getCount()` but that's not a big deal.

Target:
private WFSTCompletionLookup build(final IndexReader indexReader, final String field) throws IOException { WFSTInputIterator iterator = new WFSTInputIterator( new LuceneDictionary(indexReader, field).getEntryIterator(), indexReader, field, getSearchCounts(field)); WFSTCompletionLookup lookup = createWFST(); lookup.build(iterator); if (lookup.getCount() > 0) { double averageLength = (double) iterator.termLengthAccumulator / lookup.getCount(); averageLengths.put(field, averageLength); } return lookup; }
Source:
static String getHighestMessageLevel(Collection<MessagesContainer.AcceptedMessage> messages) { return messages. stream(). map(MessagesContainer.AcceptedMessage::getMessageLevel). START max(VALUE_COMPARATOR). END map(Message.MessageLevel::toString). orElse(null); } I'd qualify here with the class name so the name does not seem a little out of context.

Target:
static String getHighestMessageLevel(Collection<MessagesContainer.AcceptedMessage> messages) { return messages. stream(). map(MessagesContainer.AcceptedMessage::getMessageLevel). max(Message.MessageLevel.VALUE_COMPARATOR). map(Message.MessageLevel::toString). orElse(null); }
Source:
public void close() { if (loggerThread == null) { return; } try { run = false; synchronized (sync) { sync.notify(); } START loggerThread.join(0); END } catch (InterruptedException e) { logger.log(Level.WARNING, "logger thread interrupted"); } } Is perhaps `join()` more understandable by not having to remember that 0 means "wait forever"?

Target:
public void close() { if (loggerThread == null) { return; } try { run = false; synchronized (sync) { sync.notify(); } loggerThread.join(); } catch (InterruptedException e) { logger.log(Level.WARNING, "logger thread interrupted"); } }
Source:
public AuthorizationFramework getAuthorizationFramework() { try { authFrameworkLock.readLock().lock(); if (authFramework == null) { START authFramework = new AuthorizationFramework(getPluginDirectory(), getPluginStack()); END } return authFramework; } finally { authFrameworkLock.readLock().unlock(); } } Theoretically, this can be accessed by multiple threads. Is it okay? If we truly want a singleton, then maybe we should revise this.

Target:
public AuthorizationFramework getAuthorizationFramework() { synchronized (authFrameworkLock) { if (authFramework == null) { authFramework = new AuthorizationFramework(getPluginDirectory(), getPluginStack()); } return authFramework; } }
Source:
private RuntimeEnvironment() { configuration = new Configuration(); configLock = new ReentrantReadWriteLock(); START authFrameworkLock = new ReentrantLock(); END watchDog = new WatchDogService(); lzIndexerParallelizer = LazilyInstantiate.using(() -> new IndexerParallelizer(this)); lzSearchExecutor = LazilyInstantiate.using(() -> newSearchExecutor()); } i think with this you can just use new Object() and synchronize on that object

Target:
private RuntimeEnvironment() { configuration = new Configuration(); configLock = new ReentrantReadWriteLock(); watchDog = new WatchDogService(); lzIndexerParallelizer = LazilyInstantiate.using(() -> new IndexerParallelizer(this)); lzSearchExecutor = LazilyInstantiate.using(() -> newSearchExecutor()); }
Source:
public void serialize( final Duration duration, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider ) throws IOException { if (duration != null) { START jsonGenerator.writeString(Util.encode(duration.toString())); END } else { jsonGenerator.writeNull(); } } is it necessary to encode duration iso standard?

Target:
public void serialize( final Duration duration, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider ) throws IOException { if (duration != null) { jsonGenerator.writeString(duration.toString()); } else { jsonGenerator.writeNull(); } }
Source:
private static String messagesToJson(List<String> tags) { START String[] array = new String[tags.size()]; END return messagesToJson(tags.toArray(array)); } IDEA says that using `toArray(new String[collection.size()])` has no performance improvement over `toArray(new String[0])` so the second call is encouraged.

Target:
private static String messagesToJson(List<String> tags) { return messagesToJson(tags.toArray(new String[0])); }
Source:
public static String redactUrl(String path) { URL url; try { url = new URL(path); } catch (MalformedURLException e) { // not an URL return path; } if (url.getUserInfo() != null) { return url.toString().replace(url.getUserInfo(), REDACTED_USER_INFO); } else { START return url.toString(); END } } Maybe just return `path` here? Can somehow `url.toString()` differ from `path`?

Target:
public static String redactUrl(String path) { URL url; try { url = new URL(path); } catch (MalformedURLException e) { // not an URL return path; } if (url.getUserInfo() != null) { return url.toString().replace(url.getUserInfo(), REDACTED_USER_INFO); } else { return path; } }
Source:
public Map<String,Project> getProjects() { Map<String,Project> projects = (Map<String,Project>)getConfigurationValue("projects"); START return projects; END } simplify return

Target:
public Map<String,Project> getProjects() { return (Map<String,Project>)getConfigurationValue("projects"); }
Source:
public static void setUpClass() throws Exception { repository = new TestRepository(); repository.create( HistoryGuru.class.getResourceAsStream("repositories.zip")); RuntimeEnvironment env = RuntimeEnvironment.getInstance(); START env.setHistoryEnabled(true); END env.setRepositories(repository.getSourceRoot()); } Since `RuntimeEnvironment` is shared between all runs of tests, usually I have noticed a reversion of original settings — e.g. `env.setHistoryEnabled(originalIsHistoryEnabled)` in `@AfterClass`. I see tests passing but wonder if it should be done anyway for correctness.

Target:
public static void setUpClass() throws Exception { repository = new TestRepository(); repository.create( HistoryGuru.class.getResourceAsStream("repositories.zip")); RuntimeEnvironment env = RuntimeEnvironment.getInstance(); env.setRepositories(repository.getSourceRoot()); env.setHistoryEnabled(true); }
Source:
public boolean isHandleRenamedFiles() { START return handleRenamedFiles; END } this cause potential NPE when `handleRenamedFiles` is null, doesn't it?

Target:
public boolean isHandleRenamedFiles() { return handleRenamedFiles != null && handleRenamedFiles; }
Source:
public void setMandoc(String value) { START mandoc = value; END } use this.mandoc to be consistent with setCtags() ?

Target:
public void setMandoc(String value) { this.mandoc = value; }
Source:
START LockFactory pickLockFactory(RuntimeEnvironment env) { END String luceneLocking = env.getLuceneLocking(); switch (luceneLocking) { case LuceneLockName.OFF: return NoLockFactory.INSTANCE; case LuceneLockName.ON: case LuceneLockName.SIMPLE: return SimpleFSLockFactory.INSTANCE; case LuceneLockName.NATIVE: return NativeFSLockFactory.INSTANCE; default: LOGGER.log(Level.WARNING, "Unknown Lucene locking mode: {0}", luceneLocking); return NoLockFactory.INSTANCE; } } lockpick factory :-D

Target:
LockFactory pickLockFactory(RuntimeEnvironment env) { switch (env.getLuceneLocking()) { case ON: case SIMPLE: return SimpleFSLockFactory.INSTANCE; case NATIVE: return NativeFSLockFactory.INSTANCE; case OFF: default: return NoLockFactory.INSTANCE; } }
Source:
public void load(Map<String, Object> parameters) { super.load(parameters); if ((objectClass = (String) parameters.get(OBJECT_CLASS)) == null) { throw new NullPointerException("Missing param [" + OBJECT_CLASS + "] in the setup"); } if (!isAlphanumeric(objectClass)) { throw new NullPointerException("object class '" + objectClass + "' contains non-alphanumeric characters"); } START usernameCnPattern = Pattern.compile("(cn=[a-zA-Z_]+)"); END LOGGER.log(Level.FINE, "LdapUser plugin loaded with objectclass={0}", objectClass); } why here and not in the property definition?

Target:
public void load(Map<String, Object> parameters) { super.load(parameters); if ((objectClass = (String) parameters.get(OBJECT_CLASS)) == null) { throw new NullPointerException("Missing param [" + OBJECT_CLASS + "] in the setup"); } if (!isAlphanumeric(objectClass)) { throw new NullPointerException("object class '" + objectClass + "' contains non-alphanumeric characters"); } LOGGER.log(Level.FINE, "LdapUser plugin loaded with objectclass={0}", objectClass); }
Source:
public void testUserPage() { RuntimeEnvironment instance = RuntimeEnvironment.getInstance(); String page = "http://www.myserver.org/viewProfile.jspa?username="; assertNull(instance.getUserPage()); // default value is null START instance.setUserPage(page.substring(5)); END assertEquals(page.substring(5), instance.getUserPage()); } I wonder what was the purpose of these `substring` operations. Perhaps they can be removed ?

Target:
public void testUserPage() { RuntimeEnvironment instance = RuntimeEnvironment.getInstance(); String page = "http://www.myserver.org/viewProfile.jspa?username="; assertNull(instance.getUserPage()); // default value is null instance.setUserPage(page); assertEquals(page, instance.getUserPage()); }
Source:
START FileEntry(String name, String href, long lastModified, int size, List<FileEntry> subdirs) { END this.name = name; this.href = href; this.lastModified = lastModified; this.size = size; this.subdirs = subdirs; } pls keep the old method signature and make it a wrapper so that old calls do not have to be adjusted with the `null` argument.

Target:
private FileEntry(String name, String href, long lastModified, int size, List<FileEntry> subdirs) { this(); this.name = name; this.href = href; this.lastModified = lastModified; this.size = size; this.subdirs = subdirs; }
Source:
START private synchronized boolean performCheck(Nameable entity, Predicate<IAuthorizationPlugin> predicate) { END lock.readLock().lock(); try { return stack.isAllowed(entity, predicate); } finally { lock.readLock().unlock(); } } the `synchronized` should still be present ?

Target:
private boolean performCheck(Nameable entity, Predicate<IAuthorizationPlugin> predicate) { lock.readLock().lock(); try { return stack.isAllowed(entity, predicate); } finally { lock.readLock().unlock(); } }
Source:
public void addRequest(HttpServletRequest req, String category) { AtomicLong val = requestCategories.get(category); if (val == null) { START val = new AtomicLong(0); END } val.incrementAndGet(); requestCategories.put(category, val); } Not sure this would work. If 2 threads are racing for this code while `val` is still `null`, both can read `val` as `null` so both will create new instance and 1 count can be lost given the last of them will update the map so possibly using `synchronized` for cases like this is actually needed.

Target:
synchronized public void addRequest(HttpServletRequest req, String category) { Long val = requestCategories.get(category); if (val == null) { val = new Long(0); } val += 1; requestCategories.put(category, val); }
Source:
public static Project getByName(String name) { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); if (env.hasProjects()) { for (Project proj : env.getProjects()) { START if (name.equals(proj.getName())) { END return (proj); } } } return null; } Actually if there is this change, the container type can be finally changed from `List` to `Set (TreeSet)` which will cause ultra speedup for this lookup. By ultra I mean this is really significant when looking for single project in container of size app. 700. And I'm not event saying that this might be done several times per request.

Target:
public static Project getByName(String name) { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); if (env.hasProjects()) { Project proj; if ((proj = env.getProjects().get(name)) != null) { return (proj); } } return null; }
Source:
START public HashSet<Project> getProjects() { END return projects; } use supertype `Set`

Target:
public Map<String,Project> getProjects() { return projects; }
Source:
START public HashSet<Project> getProjects() { END return threadConfig.get().getProjects(); } use supertype `Set`

Target:
public Map<String,Project> getProjects() { return threadConfig.get().getProjects(); }
Source:
public boolean hasProjects() { START Set<String> proj = getProjects().keySet(); END return (proj != null && !proj.isEmpty()); } doesn't the `size` method return the number of mappings? I mean maybe it's not necessary to get the keySet at all

Target:
public boolean hasProjects() { return (getProjects().size() > 0); }