auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ScaledNumberIndexFieldTypeContext<?, BigDecimal> asBigDecimal() { return new StubScaledNumberIndexFieldTypeContext( BigDecimal.class, defaultsProvider ); }

Target:
Missing `<>`, this is a raw type.
Source:
public void setComponent(T component) { this.component = component; }

Target:
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.
Source:
public static Instant parseInstant(String value) { // 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 ); } }

Target:
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 :)
Source:
public BackendInitialBuildState<?> getBackend(String backendName) { if ( StringHelper.isEmpty( backendName ) ) { backendName = getDefaultBackendName(); } return backendBuildStateByName.computeIfAbsent( backendName, this::createBackend ); }

Target:
It's not critical, but shall we need to expose this method outside, instead of exposing just: `getIndexManagerBuildingState( backendName, indexName, multiTenancyEnabled )`?
Source:
public FieldProjectionContext<Object> rawField(String absoluteFieldPath) { return field( absoluteFieldPath, Object.class ); }

Target:
This seems wrong, it should be `rawField( absoluteFieldPath, Object.class )`. And tests do not fail, so you're missing a test here.
Source:
public Optional<FieldProjectionExpectations<Double>> getFieldProjectionExpectations() { return Optional.of( new FieldProjectionExpectations<>( 1.001, 3.0, 5.1 ) ); }

Target:
While we're at it... Maybe use a negative value in there, too?
Source:
public Integer encode(MonthDay value) { if ( value == null ) { return null; } return 37 * value.getMonthValue() + value.getDayOfMonth(); }

Target:
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.
Source:
public Borrowal(Account account, DocumentCopy<?> copy, BorrowalType type) { this.account = account; this.copy = copy; this.type = type; account.getBorrowals().add( this ); copy.getBorrowals().add( this ); }

Target:
Yeah... same as the other ones. I don't think this is a good idea, this should be in the repository or service code.
Source:
public long getResultSize() { 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 ); } }

Target:
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 :/
Source:
protected Query doBuild(LuceneSearchPredicateContext context) { Builder builder = new BooleanQuery.Builder(); values.forEach( value -> builder.add( termQuery( value ), Occur.SHOULD ) ); BooleanQuery query = builder.build(); return query; }

Target:
Same here, I would avoid the lambda.
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(); } throw log.errorInvokingMember( member.getName(), thiz.toString(), e ); } }

Target:
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.
Source:
public Analyzer wrapNormalizer(String name, Analyzer normalizer) { return new HibernateSearchNormalizerWrapper( normalizer, name ); }

Target:
Minor nitpicking but it's weird to have the order of parameters reversed between these 2 lines.
Source:
public LuceneCollectors build() { if ( luceneCollectors.isEmpty() ) { throw new AssertionFailure( "No collectors have been defined: we need at least one." ); } Collector compositeCollector; if ( luceneCollectors.size() == 1 ) { compositeCollector = topDocsCollector != null ? topDocsCollector : totalHitCountCollector; } else { compositeCollector = MultiCollector.wrap( luceneCollectors ); } return new LuceneCollectors( topDocsCollector, totalHitCountCollector, compositeCollector ); }

Target:
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.
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 ) && Objects.equals( projectionBuilderFactory, other.projectionBuilderFactory ); }

Target:
Ok, as discussed on HipChat, let's drop support for index-sensitive projections for now, and restore it later (maybe).
Source:
protected void setUp() throws Exception { buildSessionFactories( getAnnotatedClasses(), getAnnotatedPackages(), getXmlFiles() ); lastTestClass = getClass(); }

Target:
You should probably make the method `public` just for consistency... Same for `tearDown`.
Source:
public static <T> T instanceFromClass(Class<T> targetSuperType, Class<?> classToLoad, String componentDescription) { checkClassType( classToLoad, componentDescription ); final Constructor<?> constructor = getNoArgConstructor( classToLoad, componentDescription ); final Object instance = untypedInstanceFromClass( classToLoad, componentDescription ); return verifySuperTypeCompatibility( targetSuperType, instance, classToLoad, componentDescription ); }

Target:
This variable is never used. Maybe this line should be removed?
Source:
synchronized void stopVirtual() { userCounter--; if ( userCounter == 0 ) { if ( status != ServiceStatus.RUNNING ) { stateExpectedFailure(); } stopReal(); } else if ( status != ServiceStatus.RUNNING ) { //Could happen on circular dependencies stateExpectedFailure(); } }

Target:
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?
Source:
public TokenizerClassNameToElasticsearchTypeNameTransformer(Class<?> factoryClass, String parameterName) { super(); this.factoryClass = factoryClass; this.parameterName = parameterName; }

Target:
You can remove the `super();`.
Source:
public void configureFieldMetadata(String name, FieldMetadataBuilder builder) { builder.field( "value", FieldType.OBJECT ); }

Target:
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.
Source:
public void configureFieldMetadata(String name, FieldMetadataBuilder builder) { FieldMetadataCreationContext field = builder.field( name, FieldType.OBJECT ); if ( dynamicType != null ) { field.mappedOn( Elasticsearch.class ) .dynamic( DynamicType.TRUE ); } }

Target:
`Elasticsearch` and `DynamicType` are impl types as per there packages. They should not be accessed here.
Source:
static String getDocumentId(LuceneWork work) { return work.getTenantId() == null ? work.getIdInString() : work.getTenantId() + "_" + work.getIdInString(); }

Target:
Is it used anywhere else? If not, let's make it private (I suppose it was the purpose of dropping `DocumentIdHelper`).
Source:
public void setUp() throws Exception { super.setUp(); Transaction tx = openSession().beginTransaction(); A a = new A(); a.value = "1"; getSession().save( a ); tx.commit(); getSession().close(); this.fullTextSession = Search.getFullTextSession( openSession() ); }

Target:
Why do you need to have a value for Elasticsearch?
Source:
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.toString() ); return null; }

Target:
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
Source:
public static boolean isSupported(Class<? extends DeletionQuery> type) { if ( SUPPORTED_TYPES == null ) { // LAZY init, but don't to it more than once SUPPORTED_TYPES_LOCK.lock(); 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 ); }

Target:
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.
Source:
private ErrorHandler createErrorHandlerFromString(String errorHandlerClassName, ClassLoaderService classLoaderService) { if ( StringHelper.isEmpty( errorHandlerClassName ) || "log".equals( errorHandlerClassName.trim() ) ) { return new LogErrorHandler(); } else { Class<?> errorHandlerClass = classLoaderService.classForName( errorHandlerClassName ); return ClassLoaderHelper.instanceFromClass( ErrorHandler.class, errorHandlerClass, "Error Handler" ); } }

Target:
Should 'log' maybe be a constant, making it clear that it is the shortcut name of the logging error handler?
Source:
private void wakeUpConsumer() { if ( LockSupport.getBlocker( consumerThread ) != null ) { LockSupport.unpark( consumerThread ); } }

Target:
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).
Source:
public void startWatching(Collection<File> paths) { closeLock.readLock().lock(); try { ensureOpen(); startWatching0(server, toAbsolutePaths(paths)); } finally { closeLock.readLock().unlock(); } }

Target:
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.
Source:
public <T> T findAndDelete(final Query<T> query) { FindAndModifyOptions options = new FindAndModifyOptions() .remove(true) .returnNew(false) .upsert(false); return findAndDelete(query, options); }

Target:
These three lines are redundant with lines 291-293 below
Source:
public T get(final FindOptions options) { final MorphiaIterator<T, T> it = fetch(options .copy() .limit(1)); T t = (it.hasNext()) ? it.next() : null; it.close(); return t; }

Target:
If you're going to add a close best to do it in a finally block.
Source:
DatastoreImpl(final Morphia morphia, final MongoClient mongoClient, final String dbName) { this(morphia, morphia.getMapper(), mongoClient, dbName); }

Target:
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.
Source:
public DB getDB() { return db != null ? db : mongoClient.getDB(database.getName()); }

Target:
I don't see much point in making db lazily created. It's not an expensive operation.
Source:
public static IndexType fromValue(final Object value) { for (IndexType indexType : values()) { if (indexType.type.equals(value) || indexType.name().equals(value)) { return indexType; } } throw new IllegalArgumentException("No enum value found for " + value); }

Target:
Don't allow comparison against both the name and the value. That's confusing.
Source:
List<ClassMethodPair> getLifecycleMethods(final Class<Annotation> clazz) { return lifecycleMethods.get(clazz); }

Target:
Why the binary compat break?
Source:
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 = new BufferedReader(in).lines(); lines.filter(this::lineNotInExcludedStrings) .map(this::parseShenandoahEvent) .filter(Objects::nonNull) .forEach(model::add); return model; }

Target:
No need to wrap "in" in a BufferedReader. It is a LineNumberReader, which is a subclass of BufferedReader.
Source:
public Iterable<String> getColNames() { return Iterables.transform(fields, new Function<Field, String>() { @Override @Nullable public String apply(Field arg0) { return arg0.getSqlName(); } }); }

Target:
@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;
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: case COMMUNITY: return DOWNLOAD_URL_SUFFIX; } }

Target:
This `case` looks redundant with the `default`.
Source:
public LineRecordWriter(DataOutputStream out) { this.out = out; jsonMapper.getFactory() .configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true); jsonWriter = jsonMapper.writer(new JsonIndenter()); try { out.writeBytes("["); } catch (IOException e) { } }

Target:
With JSON lines the opening `[` isn't necessary anymore.
Source:
public boolean filter(String fromUrl, String toUrl) { //this implementation doesnt do anything with fromUrl if (exemptions != null) { for (Pattern pattern : exemptions) { if (pattern.matcher(toUrl).matches()) { return true; //If a regex matches, then exempted } } } //not exempted return false; }

Target:
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
Source:
private String getVersionInformation(PersistentEntity persistentEntity, Object domainObject){ 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; }

Target:
What's the reason we invoke Jackson mapping here? Shouldn't a plain `toString()` be sufficient?
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); assertThat(replaceNewLine(actual)).isEqualTo(replaceNewLine(Resources.toString( Resources.getResource("restx/tests/expected_restx_case_example_1.yaml"), Charsets.UTF_8))); }

Target:
Is it really worth replacing new lines on *both* sides here ? (sounds like useless as it is, but I may be missing something)
Source:
private ResourceLock newWriteUnlocker() { return () -> CloseableReentrantReadWriteLock.this.writeLock().unlock(); }

Target:
why `this.writeLock().unlock()` is not enough?
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); if (iterator.termLengthAccumulator > 0) { double averageLength = (double) iterator.termLengthAccumulator / lookup.getCount(); averageLengths.put(field, averageLength); } return lookup; }

Target:
I'd prefer the condition to check `lookup.getCount()` but that's not a big deal.
Source:
static String getHighestMessageLevel(Collection<MessagesContainer.AcceptedMessage> messages) { return messages. stream(). map(MessagesContainer.AcceptedMessage::getMessageLevel). max(VALUE_COMPARATOR). map(Message.MessageLevel::toString). orElse(null); }

Target:
I'd qualify here with the class name so the name does not seem a little out of context.
Source:
public void close() { if (loggerThread == null) { return; } try { run = false; synchronized (sync) { sync.notify(); } loggerThread.join(0); } catch (InterruptedException e) { logger.log(Level.WARNING, "logger thread interrupted"); } }

Target:
Is perhaps `join()` more understandable by not having to remember that 0 means "wait forever"?
Source:
public AuthorizationFramework getAuthorizationFramework() { try { authFrameworkLock.readLock().lock(); if (authFramework == null) { authFramework = new AuthorizationFramework(getPluginDirectory(), getPluginStack()); } return authFramework; } finally { authFrameworkLock.readLock().unlock(); } }

Target:
Theoretically, this can be accessed by multiple threads. Is it okay? If we truly want a singleton, then maybe we should revise this.
Source:
private RuntimeEnvironment() { configuration = new Configuration(); configLock = new ReentrantReadWriteLock(); authFrameworkLock = new ReentrantLock(); watchDog = new WatchDogService(); lzIndexerParallelizer = LazilyInstantiate.using(() -> new IndexerParallelizer(this)); lzSearchExecutor = LazilyInstantiate.using(() -> newSearchExecutor()); }

Target:
i think with this you can just use new Object() and synchronize on that object
Source:
public void serialize( final Duration duration, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider ) throws IOException { if (duration != null) { jsonGenerator.writeString(Util.encode(duration.toString())); } else { jsonGenerator.writeNull(); } }

Target:
is it necessary to encode duration iso standard?
Source:
private static String messagesToJson(List<String> tags) { String[] array = new String[tags.size()]; return messagesToJson(tags.toArray(array)); }

Target:
IDEA says that using `toArray(new String[collection.size()])` has no performance improvement over `toArray(new String[0])` so the second call is encouraged.
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 { return url.toString(); } }

Target:
Maybe just return `path` here? Can somehow `url.toString()` differ from `path`?
Source:
public Map<String,Project> getProjects() { Map<String,Project> projects = (Map<String,Project>)getConfigurationValue("projects"); return projects; }

Target:
simplify return
Source:
public static void setUpClass() throws Exception { repository = new TestRepository(); repository.create( HistoryGuru.class.getResourceAsStream("repositories.zip")); RuntimeEnvironment env = RuntimeEnvironment.getInstance(); env.setHistoryEnabled(true); env.setRepositories(repository.getSourceRoot()); }

Target:
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.
Source:
public boolean isHandleRenamedFiles() { return handleRenamedFiles; }

Target:
this cause potential NPE when `handleRenamedFiles` is null, doesn't it?
Source:
public void setMandoc(String value) { mandoc = value; }

Target:
use this.mandoc to be consistent with setCtags() ?
Source:
LockFactory pickLockFactory(RuntimeEnvironment env) { 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; } }

Target:
lockpick factory :-D
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"); } usernameCnPattern = Pattern.compile("(cn=[a-zA-Z_]+)"); LOGGER.log(Level.FINE, "LdapUser plugin loaded with objectclass={0}", objectClass); }

Target:
why here and not in the property definition?
Source:
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.substring(5)); assertEquals(page.substring(5), instance.getUserPage()); }

Target:
I wonder what was the purpose of these `substring` operations. Perhaps they can be removed ?
Source:
FileEntry(String name, String href, long lastModified, int size, List<FileEntry> subdirs) { this.name = name; this.href = href; this.lastModified = lastModified; this.size = size; this.subdirs = subdirs; }

Target:
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.
Source:
private synchronized boolean performCheck(Nameable entity, Predicate<IAuthorizationPlugin> predicate) { lock.readLock().lock(); try { return stack.isAllowed(entity, predicate); } finally { lock.readLock().unlock(); } }

Target:
the `synchronized` should still be present ?
Source:
public void addRequest(HttpServletRequest req, String category) { AtomicLong val = requestCategories.get(category); if (val == null) { val = new AtomicLong(0); } val.incrementAndGet(); requestCategories.put(category, val); }

Target:
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.
Source:
public static Project getByName(String name) { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); if (env.hasProjects()) { for (Project proj : env.getProjects()) { if (name.equals(proj.getName())) { return (proj); } } } return null; }

Target:
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.
Source:
public HashSet<Project> getProjects() { return projects; }

Target:
use supertype `Set`
Source:
public HashSet<Project> getProjects() { return threadConfig.get().getProjects(); }

Target:
use supertype `Set`
Source:
public boolean hasProjects() { Set<String> proj = getProjects().keySet(); return (proj != null && !proj.isEmpty()); }

Target:
doesn't the `size` method return the number of mappings? I mean maybe it's not necessary to get the keySet at all
Source:
public void setProjects(Map<String,Project> projects) { this.projects = (HashMap<String, Project>) projects; }

Target:
if you do it [here](https://github.com/OpenGrok/OpenGrok/pull/1543/files#r113946427) the this cast is not necessary
Source:
public void readConfiguration(File file) throws IOException, FileNotFoundException { setConfiguration(Configuration.read(file)); }

Target:
FileNotFoundException is a subclass of IOException
Source:
public byte[] apply(RuntimeEnvironment env) throws IOException { if (hasTag("reindex")) { env.applyConfig(this, true); } else { env.applyConfig(this, false); } return null; }

Target:
Possibly shorter to just write ```java env.applyConfig(this, hasTag("reindex")); ``` but this is ok
Source:
public void setTextFromFile(String filepath) { try { byte[] encoded = Files.readAllBytes(Paths.get(filepath)); this.text = new String(encoded); } catch (IOException ex) { System.err.println("Cannot read '" + filepath + "': " + ex); System.exit(1); } }

Target:
Do not use system.exit, this is not a main program. Throw an exception or return a boolean and check it in the main program
Source:
public static boolean isLocal(Project project, String path) { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); String srcRoot = env.getSourceRootPath(); if (path.startsWith(srcRoot)) { if (env.hasProjects()) { String relPath = path.substring(srcRoot.length()); if (project != null && project.equals(Project.getProject(relPath))) { // File is under the current project, so it's local. return true; } } else { // File is under source root, and we don't have projects, so // consider it local. return true; } } return false; }

Target:
could do the project != null check here to avoid the substring operation
Source:
public void setTags(final List<String> tags) { this.tags = tags != null ? SetUniqueList.decorate(tags) : null; }

Target:
For my knowledge: What is the impact of that ? Before it was possible to have multiple time the same value in tag list ?
Source:
public Set<String> getCollections() { return collections != null ? new TreeSet<>(collections) : null; }

Target:
Avoid logic in this class. This is inconsistent with other collection fields. You can't do an update with this field set to null. Also, why a tree set?
Source:
public void setCollections(final Set<String> collections) { this.collections = collections != null ? new TreeSet<>(collections) : null; }

Target:
Avoid logic in this class.
Source:
private static ObjectMapper createObjectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.setDateFormat(new ISO8601DateFormat()); return mapper; }

Target:
Remove this (ORDER_MAP_ENTRIES_BY_KEYS).
Source:
static public Drive getDriveService(String token) { GoogleCredential credential = new GoogleCredential().setAccessToken(token); return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setHttpRequestInitializer(new HttpRequestInitializer() { @Override public void initialize(HttpRequest httpRequest) throws IOException { credential.initialize(httpRequest); httpRequest.setConnectTimeout(300 * 60000); // 300 minutes connect timeout httpRequest.setReadTimeout(300 * 60000); // 300 minutes read timeout } }) .setApplicationName(SERVICE_APP_NAME).build(); }

Target:
@jackyq2015 Is this timeout value still what Google recommends ? I know that Apache HTTP has a internal default of 3 minutes timeout that can be overridden in Apache's newer package version.
Source:
static public LocalDateTime stringToLocalDate(String s) { if (s.endsWith("Z")) { // UTC time Instant instant = Instant.parse(s); return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); } else return LocalDateTime.parse(s, DateTimeFormatter.ISO_LOCAL_DATE_TIME); }

Target:
Missing brace
Source:
private static boolean mayHaveValidDate(final String value) { List<String> matches = fetchDateStrings(value); if (!matches.isEmpty()) { try { DateTimeFormat dateTimeFormat = DateTimeFormat.getFormat("yyyy-MM-dd"); matches.forEach(dateTimeFormat::parseStrict); } catch (Exception e) { return false; } } return true; }

Target:
I understand that the key point is the use of the `DateTimeFormat.parseStrict` method. Once calling it, if an execptoin occurs, we can assume that the given date is not valid. But maybe we can be more specific on the exception type being catched on this assumption - does it makes sense assuming once any "generic" exception occurs is due to the date is not valid (eg: leap days)? Is there any other Exception subtype we could use for the catch block instead? Just brainstorming, just asking :)
Source:
private static int getIndexOfFileSeparator(String string) { int index = string.indexOf('/'); if (index == -1) { return string.indexOf('\\'); } return index; }

Target:
can be inlined into a single return line
Source:
protected String composeUniqueNodeName(final String name) { final String originalName = Optional.ofNullable(name).orElse(""); try { final MatchResult nameSuffixMatcher = NAME_SUFFIX_REGEX.exec(originalName); if (nameSuffixMatcher != null) { return buildNameWithIncrementedSuffixIndex(originalName, nameSuffixMatcher); } } catch (Exception e) { LOGGER.warning("There was an issue while parsing node with name " + originalName + " - A fallback will be used for it"); } return joinPrefixWithIndexedSuffix(originalName); }

Target:
Small suggestion to investigate how could we avoid a generic exception since that would be hard to inspect if something would happen if exec will throw any exception like IndexOutOfBounds or buildNameWithIncrementedSuffixIndex throw some exception(bcs it would probably just skipped)
Source:
public void setValue(String value, boolean fireEvents) { String oldValue = current; current = value; if (current.equals("0")) { view.setLocalTimeZone(); } else { view.setValue(current); } if (fireEvents) { ValueChangeEvent.fireIfNotEqual(this, oldValue, value); } }

Target:
I just understood the condition now at the first read, great!! thanks a lot for this small things, I think those become important at the long term, easier to maintan... :+1:
Source:
protected String getInvalidCharsInName(final String value) { return getInvalidCharsInName(regExp, value); }

Target:
can be `private`? or at least package protected access?
Source:
protected String testForInvalidValue(final String value) { if (value == null || value.isEmpty() || invalidValues == null) { return null; } String testValue; if (!isCaseSensitive) { testValue = value.toLowerCase(); } else { testValue = value; } if (invalidValues.contains(testValue)) { return invalidValueErrorMessage; } else { return null; } }

Target:
can be `private`? or at least package protected access?
Source:
public void setCurrentContainer(FormsContainer container) { this.container = container; }

Target:
this method should not be `public`, otherwise doesn't make sense the arguments for the `flush(ClientSession, String)` method, as each session (editor) will have a different associated `FormsContainer` instance, which could not be the one set in `setCurrentContainer`... Can you please change it to package protected access (so no access modifier set)? Does it work/make sense for you?
Source:
public String getName() { if (StringUtils.isEmpty(name)) { this.name = getNewRuleAnnotationClauseName(); } return this.name; }

Target:
Can this be `private` (or at least package protected)? It's only used by this class.
Source:
public Optional<RuleAnnotationClauseColumn> getUiModelColumn() { return uiModelColumn; }

Target:
In fact why do we need it at all!? If it's only use is this class or the test, the value is know by the test already as it constructs the instance.
Source:
public ZoomLevelSelectorPresenter show() { cancelHide(); floatingView.show(); if(zoomLevelInit){ zoomLevelInit = false; scheduleHide(); } return this; }

Target:
Hi @handreyrc can you appply KIE style formatting?
Source:
public static JSITLiteralExpression dmnFromWB(final OutputClauseLiteralExpression wb) { if (Objects.isNull(wb)) { return null; } else if (StringUtils.isEmpty(wb.getText().getValue())) { return null; } return LiteralExpressionPropertyConverter.dmnFromWB(wb); }

Target:
`wb.getText()` never returns `null`?
Source:
public void testPopulateMenu() { placeManager = mock(PlaceManager.class); final DMNEditorMenuSessionItems menuItems = spy(new DMNEditorMenuSessionItems(builder, sessionCommands, placeManager)); final MenuItem menuItem = mock(MenuItem.class); doNothing().when(menuItems).superPopulateMenu(any()); doReturn(menuItem).when(menuItems).newPerformAutomaticLayout(); menuItems.populateMenu(fileMenuBuilder); verify(menuItems).addPerformAutomaticLayout(any()); }

Target:
You don't need to `mock(..)` it if you've `@Mock`'ed it.
Source:
public static IThenable.ThenOnFulfilledCallbackFn<List<String>, Object> getListObjectThenOnFulfilledCallbackFn(List<String> simpleDataTypes, ListBoxValues dataTypeListBoxValues) { return serverDataTypes -> { List<String> mergedList = new ArrayList<>(simpleDataTypes); for (String type : serverDataTypes) { String displayType = createDataTypeDisplayName(type); getMapDataTypeNamesToDisplayNames().put( displayType, type ); mergedList.add(displayType); } dataTypeListBoxValues.addValues(mergedList); return null; }; }

Target:
same here, maybe using Streams may result more readable.
Source:
public boolean equals( final Object o ) { if ( this == o ) { return true; } if ( !( o instanceof DependencyPathSelectedEvent ) ) { return false; } final DependencyPathSelectedEvent that = (DependencyPathSelectedEvent) o; if ( !context.equals( that.context ) ) { return false; } if (!isSelected == that.isSelected) { return false; } return path.equals( that.path ); }

Target:
```suggestion if (isSelected != that.isSelected) { ```
Source:
public void setInitialPositionY(final HTMLElement dragAndDropElement, final List<HTMLElement> children) { Integer parentY = Position.getY(dragAndDropElement); for (final Element element : children) { parentY++; Position.setY(element, parentY); } }

Target:
This is the same as below, but I am fine if you want to keep as it is. ```java for (final Element element : children) { Position.setY(element, ++parentY); } ```
Source:
public void testGetTopLevelDataTypeWithName(){ final String topLevelType = "tType"; final DataType dataType = mock(DataType.class); final Optional<DataType> type = Optional.of(dataType); doReturn(type).when(manager).findTopLevelDataTypeWithName(topLevelType); final DataType actual = manager.getTopLevelDataTypeWithName(topLevelType); assertEquals(dataType, actual); }

Target:
formatting
Source:
public void testLoadDataObjectsWithNullWorkspaceProject() { assertTrue(dataObjectsService.loadDataObjects(null).isEmpty()); }

Target:
Please use assertj assertion. In case of fail it gives error message explaining different list sizes. Current implementation will just print assertion error, expected true but was false with no reference to list size.
Source:
public void testDestroy() { final UberfireDock uberfireDock = mock(UberfireDock.class); dock.setOpened(false); doReturn(uberfireDock).when(dock).getUberfireDock(); dock.destroy(); verify(uberfireDocks).remove(uberfireDock); }

Target:
I do not understand why we need this method, could you please clarify?
Source:
private static JSITDMNElement.JSIExtensionElements getOrCreateExtensionElements(final JSITDRGElement target) { // TODO {gcardosi} add because present in original json JSITDMNElement.JSIExtensionElements toReturn = target.getExtensionElements() == null ? new JSITDMNElement.JSIExtensionElements() : target.getExtensionElements(); if (!Objects.isNull(toReturn) && Objects.isNull(toReturn.getAny())) { toReturn.setAny(new ArrayList<>()); } return toReturn; }

Target:
Can't we use `Collections.emptyList()` just asking, do not knwo if can cause troubles as return no-modifiable list.
Source:
Worker createWorker() { return Worker.create(pathToVerifier); }

Target:
@Rikkola If 'Worker' class can be managed exclusively by this class with no possibility to override its behavior, I suggest to put the 'private' visibility to this method. Anyway, your choice.
Source:
public void setUp() throws Exception { receiver = new Receiver(reporter) { @Override public Object fromJSON(final String json) { return returnObject; } }; receiver.setUp(worker); verify(worker).setOnMessage(messageHandlerArgumentCaptor.capture()); }

Target:
@Rikkola is this "throws' Exception really necessary?
Source:
public void setUp() throws Exception { verifierWebWorkerConnection = spy(new VerifierWebWorkerConnectionImpl(initialize, "verifier/dtableVerifier/dtableVerifier.nocache.js", poster, receiver) { @Override Worker createWorker() { return worker; } }); }

Target:
@Rikkola is this "throws' Exception really necessary?
Source:
public void testSetReadOnly() { boolean arbitraryValue = false; view.setReadOnly(arbitraryValue); verify(slaTimeDuration).setDisabled(arbitraryValue); }

Target:
```suggestion final boolean arbitraryValue = false; ```
Source:
public void search(final String term) { final boolean isNewSearch = Objects.equals(term, currentTerm); final Optional<SearchResult<T>> result; if (isNewSearch) { result = findNextElement(term); } else { result = findFirstElement(term); } currentResult = result.orElse(currentResult); currentTerm = term; triggerOnFoundCommand(); }

Target:
Variable name is misleading.. `isNewSearch` is when `!Objects.equals(term, currentTerm)`
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AdHocActivationCondition that = (AdHocActivationCondition) o; return Objects.equals(value, that.value); }

Target:
It can be like: ```java if (o instanceof AdHocActivationCondition) { AdHocActivationCondition that = (AdHocActivationCondition) o; return Objects.equals(value, that.value); } return false; ``` instanceof operator check null value as well.
Source:
public void onDeleteLinkClick(final ClickEvent clickEvent) { locker.fire(new LockRequiredEvent()); if (!Objects.isNull(getOnDeleted())) { getOnDeleted().accept(externalLink); } }

Target:
Presumably this is to acquire the _lock_ icon on the Editor Title and Project Explorer? Personally, I'd prefer to see this _behaviour_ on the `Presenter` rather than this (dumb) `View`. Perhaps having the "on delete consumer" fire this event is going to be as close to that as we can get (although IIRC that _consumer_ is a `View` too.. at least the physical delete and firing of the event would be in the same place. WDYT?
Source:
public void testGetSlaDueDate() { GenericServiceTaskExecutionSet a = new GenericServiceTaskExecutionSet( new GenericServiceTaskInfo(), new SLADueDate(SLA_DUE_DATE_1)); Assert.assertTrue(a.getSlaDueDate().getValue().equals(SLA_DUE_DATE_1)); }

Target:
You can use assertEquals here to express what is an expected value.
Source:
private Object[] toArray(List<?> messageArguments) { return messageArguments.stream().toArray(Object[]::new); }

Target:
same here messageArguments.toArray();
Source:
public Graph unmarshall(Metadata metadata, InputStream input) throws IOException { MarshallingResponse<Graph> marshallingResponse = unmarshallWithValidation(MarshallingRequest.builder() .metadata(metadata) .input(input) .mode(MarshallingRequest.Mode.ERROR) .build()); return marshallingResponse.getResult().get(); }

Target:
optional without present check access
Source:
public static <T extends FlowElement> MarshallingMessageDecorator<T> flowElementDecorator() { return MarshallingMessageDecorator.of(o -> Optional.ofNullable(o.getName()) .orElseGet(() -> o.getId()), g -> g.getClass().getSimpleName()); }

Target:
method reference can be used instead of o.getId()
Source:
private Property findPropertyById(String id) { return variableScope.lookup(id) .map(VariableScope.Variable::getTypedIdentifier) .orElse(null); }

Target:
yes, I could see that a null is returned. But question is, how can this affect to callers of this method. Since a null es returned, the callers of this method will fail by returning a NPE. But before, an exception was thrown at least saying that the expected variable XXX was not found
Source:
String getFileName(final Diagram diagram) { Metadata metadata = diagram.getMetadata(); final Optional<Path> path = Optional.ofNullable(metadata.getPath()); return path.map(Path::getFileName).orElse(translationService.format(DMNDocumentationFactory_NoFileName)); }

Target:
can be also `final`
Source:
public void testUnmarshallSubprocessLevelEventEmptyProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateErrorEventCatching emptySubprocessEvent = getCatchingIntermediateNodeById(diagram, EMPTY_SUBPROCESS_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_NO_OUTGOING_EDGE); assertGeneralSet(emptySubprocessEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertErrorEventExecutionSet(emptySubprocessEvent.getExecutionSet(), EMPTY_VALUE, CANCELLING, ""); assertDataIOSet(emptySubprocessEvent.getDataIOSet(), EMPTY_VALUE); }

Target:
```suggestion assertErrorEventExecutionSet(emptySubprocessEvent.getExecutionSet(), EMPTY_VALUE, CANCELLING, EMPTY_VALUE); ```
Source:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateTimerEvent emptyTopEvent = getCatchingIntermediateNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_NO_OUTGOING_EDGE); assertGeneralSet(emptyTopEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertTimerEventEmpty(emptyTopEvent.getExecutionSet(), NON_CANCELLING, ""); }

Target:
```suggestion assertTimerEventEmpty(emptyTopEvent.getExecutionSet(), NON_CANCELLING, EMPTY_VALUE); ```
Source:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateConditionalEvent emptyTopEvent = getCatchingIntermediateNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_NO_OUTGOING_EDGE); assertGeneralSet(emptyTopEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertConditionalEventExecutionSet(emptyTopEvent.getExecutionSet(), CONDITION_EXPRESSION_SCRIPT_DEFAULT_VALUE, CONDITION_EXPRESSION_LANGUAGE, CONDITION_ERPRESSION_TYPE, CANCELLING, ""); }

Target:
```suggestion EMPTY_VALUE); ```
Source:
public Collection<FormElementFilter> provideFilters(final String uuid, final Object definition) { final Predicate predicate = o -> isBoundaryEvent(uuid) && isCancelActivityEnabled(uuid); final FormElementFilter isInterruptingFilter = new FormElementFilter("executionSet.cancelActivity", predicate); return Collections.singletonList(isInterruptingFilter); }

Target:
not a must, but predicate.and( o -> isCancelActivityEnabled(uuid)); can also be used
Source:
public void testGetGraphIndex() throws Exception { final Edge edge = mock(Edge.class); when(edge.getTargetNode()).thenReturn(child); when(parent.getOutEdges()).thenReturn(Collections.singletonList(edge)); assertEquals(0, CaseManagementCommandUtil.getChildGraphIndex(parent, child)); }

Target:
The Exception is never thrown.
Source:
public void testIsStageNode() throws Exception { setupForStage(); assertTrue(CaseManagementCommandUtil.isStageNode(child)); }

Target:
The Exception is never thrown. Can you please use more descriptive name of test method?
Source:
public void testChildPredicate() throws Exception { final Predicate<Edge> predicate = CaseManagementCommandUtil.childPredicate(); final Edge edge = mock(Edge.class); when(edge.getContent()).thenReturn(mock(Child.class)); assertTrue(predicate.test(edge)); }

Target:
The Exception is never thrown.
Source:
public void testIsAdHocAutostart_false() throws Exception { String id = UUID.randomUUID().toString(); AdHocSubProcess adHocSubProcess = bpmn2.createAdHocSubProcess(); adHocSubProcess.setId(id); CustomElement.autoStart.of(adHocSubProcess).set(Boolean.FALSE); tested = new AdHocSubProcessPropertyReader(adHocSubProcess, definitionResolverReal.getDiagram(), definitionResolverReal); assertFalse(tested.isAdHocAutostart()); }

Target:
The Exception is never thrown.
Source:
public void testIsDrawable_InvalidUserTask() throws Exception { testIsDrawable(CaseManagementDiagram.class, UserTask.class, false); }

Target:
The Exception is never thrown.
Source:
public void setUp() throws Exception { tested = new CaseManagementSwitchViewServiceImpl(factoryManager, definitionSetServiceInstances); }

Target:
The Exception is never thrown.
Source:
public void testReopenSession() throws Exception { final ProjectDiagram projectDiagram = mock(ProjectDiagram.class); tested.reopenSession(projectDiagram); verify(sessionEditorPresenter, times(1)).destroy(); verify(sessionEditorPresenter, times(1)).open(eq(projectDiagram), any(SessionPresenter.SessionPresenterCallback.class)); }

Target:
The Exception is never thrown.
Source:
public void setUp() throws Exception { tested = new SwitchViewControl("COLUMNS", "Case View", caseViewSwitchHandler, "SITEMAP", "Process View", processViewSwitchHandler); }

Target:
The Exception is never thrown.
Source:
default void logWarning(final ClientRuntimeError error) { warn("[WARNING] DMNClientService could not get the asset list."); warn(error.getMessage()); }

Target:
I think this message comes from`DMNIncludeModelsClient`? As this is general method for logging, I think we can't have it here?
Source:
public void testAcceptWhenIsExpectedClass() { when(rule.getId()).thenReturn(definition.getClass().getName()); boolean actual = check.accepts(rule, context); assertTrue(actual); }

Target:
Just for consistency, please use `final boolean actual`
Source:
public void testAcceptWhenIsNotExpectedClass() { when(rule.getId()).thenReturn("SomeOtherClass"); boolean actual = check.accepts(rule, context); assertFalse(actual); }

Target:
Just for consistency, please use `final boolean actual`
Source:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CONDITIONAL_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartConditionalEvent emptyTop = getStartNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, StartConditionalEvent.class); assertGeneralSet(emptyTop.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertConditionalEventExecutionSet(emptyTop.getExecutionSet(), CONDITION_EXPRESSION_SCRIPT_DEFAULT_VALUE, CONDITION_EXPRESSION_LANGUAGE, CONDITION_ERPRESSION_TYPE, INTERRUPTING, ""); }

Target:
```suggestion EMPTY_VALUE); ```
Source:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartErrorEvent emptyTop = getStartNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, getStartEventType()); assertGeneralSet(emptyTop.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertErrorEventExecutionSet(emptyTop.getExecutionSet(), EMPTY_VALUE, NON_INTERRUPTING, ""); assertDataIOSet(emptyTop.getDataIOSet(), EMPTY_VALUE); }

Target:
```suggestion assertErrorEventExecutionSet(emptyTop.getExecutionSet(), EMPTY_VALUE, NON_INTERRUPTING, EMPTY_VALUE); ```
Source:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartEscalationEvent emptyTop = getStartNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, StartEscalationEvent.class); assertGeneralSet(emptyTop.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertEscalationEventExecutionSet(emptyTop.getExecutionSet(), EMPTY_VALUE, INTERRUPTING, ""); assertDataIOSet(emptyTop.getDataIOSet(), EMPTY_VALUE); }

Target:
```suggestion assertEscalationEventExecutionSet(emptyTop.getExecutionSet(), EMPTY_VALUE, INTERRUPTING, EMPTY_VALUE); ```