auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START public boolean equals(Object o) { END if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PingNuageVspCommand that = (PingNuageVspCommand) o; if (shouldAudit != that.shouldAudit) return false; return true; } This `equals` implementation should include attributes from the `PingCommand` super class.

Target:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof PingNuageVspCommand)) return false; if (!super.equals(o)) return false; PingNuageVspCommand that = (PingNuageVspCommand) o; if (shouldAudit != that.shouldAudit) return false; return true; }
Source:
START public QuotaTypes(Integer quotaType, String name, String unit, String description) { END this.quotaType = quotaType; this.description = description; this.quotaName = name; this.quotaUnit = unit; this.discriminator = "None"; } Should any user of this class be able to instantiate it? It seems like this constructor should be `private`.

Target:
private QuotaTypes(Integer quotaType, String name, String unit, String description) { this.quotaType = quotaType; this.description = description; this.quotaName = name; this.quotaUnit = unit; this.discriminator = "None"; }
Source:
public long getEntityOwnerId() { Long accountId = _accountService.getActiveAccountByName(accountName, domainId).getAccountId(); if (accountId == null) { return CallContext.current().getCallingAccount().getId(); } START return Account.ACCOUNT_ID_SYSTEM; END } This doesn't seem right. What are you trying to do here?

Target:
public long getEntityOwnerId() { return _accountService.getActiveAccountByName(accountName, domainId).getAccountId(); }
Source:
public ServiceOfferingVO findById(Long vmId, long serviceOfferingId) { ServiceOfferingVO offering = super.findById(serviceOfferingId); if (offering.isDynamic()) { offering.setDynamicFlag(true); if (vmId == null) { throw new CloudRuntimeException("missing argument vmId"); START } END Map<String, String> dynamicOffering = userVmDetailsDao.listDetailsKeyPairs(vmId); return getcomputeOffering(offering, dynamicOffering); } return offering; } Move to the top of the method and consider using `com.google.common.base.Preconditions#checkArgument` to check the argument.

Target:
public ServiceOfferingVO findById(Long vmId, long serviceOfferingId) { ServiceOfferingVO offering = super.findById(serviceOfferingId); if (offering.isDynamic()) { if (vmId == null) { throw new CloudRuntimeException("missing argument vmId"); } offering.setDynamicFlag(true); Map<String, String> dynamicOffering = userVmDetailsDao.listDetailsKeyPairs(vmId); return getcomputeOffering(offering, dynamicOffering); } return offering; }
Source:
public UsageReporter() { START s_instance = this; END } A public (instance) constructor writes to a static variable. I think you can make the constructor private and assign the static from getInstance(). First check for null and then assign if needed or return the existing object. public static UsageReporter getInstance(Map<String, String> configs) { if (s_instance == null) { s_instance = new UsageReporter(); //make sure it is private so it can only be called from here s_instance.init(configs); } return s_instance; }

Target:
private UsageReporter() { s_instance = this; }
Source:
protected void setSchema(final String schema) throws DatabaseEngineException { try { this.conn.setSchema(schema); } catch (Exception e) { throw new DatabaseEngineException(String.format("Could not set current schema to '%s'", schema), e); START } END } final missing. Same for the other ones.

Target:
protected void setSchema(final String schema) throws DatabaseEngineException { try { this.conn.setSchema(schema); } catch (final Exception e) { throw new DatabaseEngineException(String.format("Could not set current schema to '%s'", schema), e); } }
Source:
private Object ensureNoUnderflow(Object val) { START if (val instanceof Double) { END if (Math.abs((Double) val) <= 1.0e-131) { return ZERO; } } return val; } Why not: ```java if (val instanceof Double && Math.abs((Double) val) <= 1.0e-131) { return ZERO; } return val; ```

Target:
private Object ensureNoUnderflow(Object val) { if (val instanceof Double && Math.abs((Double) val) <= 1.0e-131) { return ZERO; } return val; }
Source:
public void connect() throws Exception { super.connect(); if (properties.getSchema() != null && properties.getSchema().length() > 0 && !properties.getUsername().equals(properties.getSchema())) { // Set connection schema if one is defined and not the same as the user name START final Statement stmt = conn.createStatement(); END stmt.execute("ALTER SESSION SET CURRENT_SCHEMA=" + properties.getSchema()); stmt.close(); } } how about a try-with-resources, and drop the _stmt.close();_ below?

Target:
public void connect() throws Exception { super.connect(); if (properties.getSchema() != null && properties.getSchema().length() > 0 && !properties.getUsername().equals(properties.getSchema())) { // Set connection schema if one is defined and not the same as the user name try (final Statement stmt = conn.createStatement()) { stmt.execute("ALTER SESSION SET CURRENT_SCHEMA=" + properties.getSchema()); } } }
Source:
private void dropAllEntities() { START for (MappedEntity mappedEntity : ImmutableList.copyOf(entities.values())) { END try { dropEntity(mappedEntity.getEntity()); } catch (final DatabaseEngineException ex) { logger.debug(String.format("Failed to drop entity '%s'", mappedEntity.getEntity().getName()), ex); } } } `mappedEntity` can be final, and you have a few blank lines in this method that don't really improve legibility.

Target:
private void dropAllEntities() { for (final MappedEntity mappedEntity : ImmutableList.copyOf(entities.values())) { try { dropEntity(mappedEntity.getEntity()); } catch (final DatabaseEngineException ex) { logger.debug(String.format("Failed to drop entity '%s'", mappedEntity.getEntity().getName()), ex); } } }
Source:
protected Object processObject(Object o) { START if (o != null && o instanceof PGobject && END ((PGobject)o).getType().equals("jsonb")) { return ((PGobject) o).getValue(); } return super.processObject(o); } null check is not needed, instanceof will return false if the left operand is null.

Target:
protected Object processObject(Object o) { if (o instanceof PGobject && ((PGobject)o).getType().equals("jsonb")) { return ((PGobject) o).getValue(); } return super.processObject(o); }
Source:
private void updateThreadParent() throws NodeStoreException { START if (null == inReplyTo) return; END channelManager.updateThreadParent(node, inReplyTo); } Should we avoid blocks with no braces?

Target:
private void updateThreadParent() throws NodeStoreException { if (null == inReplyTo) { return; } channelManager.updateThreadParent(node, inReplyTo); }
Source:
public AccurevSCM(String serverName, String depot, String stream) { this.depot = depot; this.stream = stream; AccurevServer server = getDescriptor().getServer(serverName); if (server != null) { setServerName(server.getName()); setServerUUID(server.getUuid()); } START updateMode(); END } Why is this change needed? if so should the deprecated method not call this one.

Target:
public AccurevSCM(String serverName, String depot, String stream) { this(serverName, null, depot, stream); }
Source:
private static void handleConsoleMessage(TaskListener listener, boolean isValidCommand, String path) { boolean isValidPath = false; isValidPath = path!=null && (path.isEmpty() || path.equals("accurev")); START if(isValidCommand && isValidPath) END { listener.getLogger().println( String.format( "No AccuRev tool configured, using default" ) ); } } This has several formatting issues

Target:
private static void handleConsoleMessage(TaskListener listener, boolean isValidCommand, String path) { boolean isValidPath = false; isValidPath = (path != null && (path.isEmpty() || path.equals("accurev"))); if (isValidCommand && isValidPath) { listener.getLogger().println("No AccuRev tool configured, using default"); } }
Source:
private static void handleConsoleMessage(TaskListener listener, boolean isValidCommand, String path) { boolean isValidPath = false; isValidPath = (path != null && (path.isEmpty() || path.equals("accurev"))); if (isValidCommand && isValidPath) { START listener.getLogger().println(String.format("No AccuRev tool configured, using default")); END } } Think we can skip the String.format here

Target:
private static void handleConsoleMessage(TaskListener listener, boolean isValidCommand, String path) { boolean isValidPath = false; isValidPath = (path != null && (path.isEmpty() || path.equals("accurev"))); if (isValidCommand && isValidPath) { listener.getLogger().println("No AccuRev tool configured, using default"); } }
Source:
public BundleGroupExtractor(Map<String, BundleInfo> bundles, String version) { this.bundles = bundles; this.version = version; START for (BundleInfo bundle : bundles.values()) { registerBundle(bundle); } END generateGroups(version); } Could be `bundles.values().forEach(this::registerBundle)`

Target:
public BundleGroupExtractor(Map<String, BundleInfo> bundles, String version) { this.bundles = bundles; this.version = version; bundles.values().forEach(this::registerBundle); generateGroups(version); }
Source:
public void checkHeader(String distribId) { if (distribId != null) { START assertEquals(String.format("Browsing Distribution '%s'", distribId), header.getText()); END } else { assertTrue(header.getText(), header.getText().startsWith("Browsing Distribution")); } } Could put `header.getText()` (used 3 times) in a local variable

Target:
public void checkHeader(String distribId) { String text = header.getText(); if (distribId != null) { assertEquals(String.format("Browsing Distribution '%s'", distribId), text); } else { assertTrue(text, text.startsWith("Browsing Distribution")); } }
Source:
START public void run(String step, MigrationContext migrationContext) { END TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); state = "after"; } Missing `@Override`.

Target:
public void run(String step, MigrationContext migrationContext) { state = "after"; }
Source:
public String toString() { return new ToStringBuilder(this).append("id", getId()) .append("author", getAuthor()) .append("text", getText()) START .toString(); END } I am wondering if we should add the `author` and `text` to `toString` method in the case where we log a sensitive data I mean. what each person says :)

Target:
public String toString() { return new ToStringBuilder(this).append("id", getId()).toString(); }
Source:
public void testFailingBulkAction() throws Exception { String result = async.newRequest(BulkRunAction.ID) // .set("action", AutomationBulkAction.ACTION_NAME) .set("query", "SELECT * FROM Folder") .set("bucketSize", "10") .set("batchSize", "5") START .set("parameters", MAPPER.writeValueAsString("{}")) END .executeReturningExceptionEntity(SC_INTERNAL_SERVER_ERROR); assertTrue( result.startsWith("Unknown operation id null in command: org.nuxeo.ecm.core.bulk.message.BulkCommand")); } Can we just put `"{}"` without calling the MAPPER? `writeValueAsString` is used to serialize an object to JSON (or other), here you're giving to it a String. My first thought is: writing a string as string will return the input string. If it's not the case, having the final value in the test will help us to understand what makes it fail and what we want to control/catch.

Target:
public void testFailingBulkAction() throws Exception { String result = async.newRequest(BulkRunAction.ID) // .set("action", AutomationBulkAction.ACTION_NAME) .set("query", "SELECT * FROM Folder") .set("bucketSize", "10") .set("batchSize", "5") .set("parameters", "{}") .executeReturningExceptionEntity(SC_INTERNAL_SERVER_ERROR); assertTrue( result.startsWith("Unknown operation id null in command: org.nuxeo.ecm.core.bulk.message.BulkCommand")); }
Source:
public void setMaxWait(int num) { blockingTimeoutMillis = num; log.warn( START "maxWait deprecated dbcp pool attribute usage, should use blockingTimeoutMillis geronimo pool attribute instead"); END } Wrong log message stating about geronimo which is removed in this PR.

Target:
public void setMaxWait(int num) { blockingTimeoutMillis = num; }
Source:
protected void writeEntries() { if (entries.get().isEmpty()) { return; } StreamManager streamManager = getStreamManager(); for (LogEntry entry : entries.get()) { START Record record = recordOf(entry); if (entry != null) { streamManager.append(STREAM_NAME, record); } END } } Should `recordOf` call be inside the if?

Target:
protected void writeEntries() { if (entries.get().isEmpty()) { return; } StreamManager streamManager = getStreamManager(); for (LogEntry entry : entries.get()) { if (entry != null) { Record record = recordOf(entry); streamManager.append(STREAM_NAME, record); } } }
Source:
public boolean match(Name name) { START if (patterns.stream().anyMatch(pattern -> name.getUrn().startsWith(pattern))) { return true; END } return false; } Why not just returning the result of `patterns.stream().anyMatch(pattern -> name.getUrn().startsWith(pattern))`.

Target:
public boolean match(Name name) { return patterns.stream().anyMatch(pattern -> name.getUrn().startsWith(pattern)); }
Source:
public boolean match(Name name, Name group) { if (patterns.stream().anyMatch(pattern -> group.getUrn().startsWith(pattern))) { return true; START } END if (match(name)) { return true; } return false; } Not needed.

Target:
public boolean match(Name name, Name group) { if (patterns.stream().anyMatch(pattern -> group.getUrn().startsWith(pattern))) { return true; } return match(name); }
Source:
public List<BundleInfo> getBundles() { List<BundleInfo> res = new ArrayList<>(bundles.values()); // order by name for deterministic processing START Collections.sort(res, Comparator.comparing(BundleInfo::getId)); END return res; } `List#sort` usage.

Target:
public List<BundleInfo> getBundles() { List<BundleInfo> res = new ArrayList<>(bundles.values()); // order by name for deterministic processing res.sort(Comparator.comparing(BundleInfo::getId)); return res; }
Source:
public static void assumeKafkaEnabled() { if ("true".equals(System.getProperty("kafka"))// deprecated since 10.3 || STREAM_KAFKA.equals(System.getProperty(STREAM_PROPERTY))) { if (!KafkaUtils.kafkaDetected()) { fail("Kafka is enabled, but no Kafka server found."); } } else { START Assume.assumeTrue("Kafka not enabled", false); END } } It could be imported statically.

Target:
public static void assumeKafkaEnabled() { if ("true".equals(System.getProperty("kafka"))// deprecated since 10.3 || STREAM_KAFKA.equals(System.getProperty(STREAM_PROPERTY))) { if (!KafkaUtils.kafkaDetected()) { fail("Kafka is enabled, but no Kafka server found."); } } else { assumeTrue("Kafka not enabled", false); } }
Source:
public void testDocumentCreationFailureWithNoName() throws Exception { File archive = getArchiveFile("test-data/testNoNameCSVArchive.zip"); FileManager fm = Framework.getService(FileManager.class); Blob blob = Blobs.createBlob(archive); FileImporterContext context = FileImporterContext.builder(coreSession, blob, workspace2.getPathAsString()) .overwrite(true) .build(); fm.createOrUpdateDocument(context); DocumentModelList children = coreSession.getChildren(workspace2.getRef()); START assertSame(0, children.size()); END } assertEquals everytime you compare two numbers that fit in a long

Target:
public void testDocumentCreationFailureWithNoName() throws Exception { File archive = getArchiveFile("test-data/testNoNameCSVArchive.zip"); FileManager fm = Framework.getService(FileManager.class); Blob blob = Blobs.createBlob(archive); FileImporterContext context = FileImporterContext.builder(coreSession, blob, workspace2.getPathAsString()) .overwrite(true) .build(); fm.createOrUpdateDocument(context); DocumentModelList children = coreSession.getChildren(workspace2.getRef()); assertEquals(0, children.size()); }
Source:
START private void addSubscriptions(String... notifications) { END NuxeoPrincipal principal = session.getPrincipal(); String subscriber = NotificationConstants.USER_PREFIX + principal.getName(); for (String notif : notifications) { notificationService.addSubscription(subscriber, notif, commentedDocumentModel, false, principal, notif); } } we don't use `private` accessor

Target:
protected void addSubscriptions(String... notifications) { NuxeoPrincipal principal = session.getPrincipal(); String subscriber = NotificationConstants.USER_PREFIX + principal.getName(); for (String notif : notifications) { notificationService.addSubscription(subscriber, notif, commentedDocumentModel, false, principal, notif); } }
Source:
public CSVLoaderConsumer(String dataLoadingPolicy, Session session, String schema) { START this.dataLoadingPolicy = Objects.requireNonNull(dataLoadingPolicy, "duplicatePolicy must not be null"); END if (!DATA_LOADING_POLICIES.contains(dataLoadingPolicy)) { throw new DirectoryException("Invalid dataLoadingPolicy: " + dataLoadingPolicy + ", it should be one of: " + DATA_LOADING_POLICIES); } this.session = Objects.requireNonNull(session, "session is null"); this.schema = Objects.requireNonNull(schema, "schema is null"); } `duplicatePolicy` -> `dataLoadingPolicy`

Target:
public CSVLoaderConsumer(String dataLoadingPolicy, Session session, String schema) { this.dataLoadingPolicy = dataLoadingPolicy; this.session = session; this.schema = schema; }
Source:
public String getInput() { Serializable input = getProperty(RetentionConstants.INPUT_PROPERTY_KEY); if (input instanceof String) { START return (String) input; END } return null; } i am wondering what if we cast directly instead of the check because ( return `(String)getProperty(RetentionConstants.INPUT_PROPERTY_KEY)`)if the type is not a string, i think we can find ourself with a non consistent data and this code will returns `null` and we have the `setInput ` which will do the insertion correctly

Target:
public String getInput() { return (String) getProperty(RetentionConstants.INPUT_PROPERTY_KEY); }
Source:
public void createUser(String userName) { try { DocumentModel userModel = userManager.getBareUserModel(); userModel.setProperty("user", "username", userName); START userModel.setProperty("user", "password", userName); END userManager.createUser(userModel); } catch (UserAlreadyExistsException e) { // Avoid failure in tests if the user already exists log.trace("User already exists", e); } } Not sure you need the `password` as you don't use it.

Target:
public void createUser(String userName) { try { DocumentModel userModel = userManager.getBareUserModel(); userModel.setProperty("user", "username", userName); userManager.createUser(userModel); } catch (UserAlreadyExistsException e) { // Avoid failure in tests if the user already exists log.trace("User already exists", e); } }
Source:
public void shouldNotifyEventWhenCreateAnnotation() { // We subscribe to the creation document to check that we will not be notified about the annotation creation as // document (see CommentCreationVeto), only the annotation added, and the 'File' document creation captureAndVerifyAnnotationEventNotification(() -> { Annotation createdAnnotation = createAnnotationAndAddSubscription("CommentAdded", "Creation"); return session.getDocument(new IdRef(createdAnnotation.getId())); START END }, COMMENT_ADDED, DOCUMENT_CREATED, 2); } Useless blank line.

Target:
public void shouldNotifyEventWhenCreateAnnotation() { // We subscribe to the creation document to check that we will not be notified about the annotation creation as // document (see CommentCreationVeto), only the annotation added, and the 'File' document creation captureAndVerifyAnnotationEventNotification(() -> { Annotation createdAnnotation = createAnnotationAndAddSubscription("CommentAdded", "Creation"); return session.getDocument(new IdRef(createdAnnotation.getId())); }, COMMENT_ADDED, DOCUMENT_CREATED); }
Source:
public void shouldNotifyEventWhenUpdateAnnotation() { // We subscribe to the update document to check that we will not be notified about the annotation updated as // document (see CommentModificationVeto), only the annotation updated. Annotation annotation = createAnnotationAndAddSubscription("CommentUpdated", "Modification"); captureAndVerifyAnnotationEventNotification(() -> { annotation.setText("I update the annotation"); annotationService.updateAnnotation(session, annotation.getId(), annotation); return session.getDocument(new IdRef(annotation.getId())); START END }, COMMENT_UPDATED, DOCUMENT_UPDATED, 1); } Useless blank line.

Target:
public void shouldNotifyEventWhenUpdateAnnotation() { // We subscribe to the update document to check that we will not be notified about the annotation updated as // document (see CommentModificationVeto), only the annotation updated. Annotation annotation = createAnnotationAndAddSubscription("CommentUpdated", "Modification"); captureAndVerifyAnnotationEventNotification(() -> { annotation.setText("I update the annotation"); annotationService.updateAnnotation(session, annotation.getId(), annotation); return session.getDocument(new IdRef(annotation.getId())); }, COMMENT_UPDATED, DOCUMENT_UPDATED); }
Source:
public void shouldNotifyEventWhenRemoveAnnotation() { Annotation createdAnnotation = createAnnotationAndAddSubscription("CommentRemoved"); DocumentModel annotationDocModel = session.getDocument(new IdRef(createdAnnotation.getId())); annotationDocModel.detach(true); captureAndVerifyAnnotationEventNotification(() -> { annotationService.deleteAnnotation(session, createdAnnotation.getId()); return annotationDocModel; START END }, COMMENT_REMOVED, DOCUMENT_REMOVED, 0); } Useless blank line.

Target:
public void shouldNotifyEventWhenRemoveAnnotation() { Annotation createdAnnotation = createAnnotationAndAddSubscription("CommentRemoved"); DocumentModel annotationDocModel = session.getDocument(new IdRef(createdAnnotation.getId())); annotationDocModel.detach(true); captureAndVerifyAnnotationEventNotification(() -> { annotationService.deleteAnnotation(session, createdAnnotation.getId()); return annotationDocModel; }, COMMENT_REMOVED, DOCUMENT_REMOVED); }
Source:
public boolean accept(Event event) { if (!(event.getContext() instanceof DocumentEventContext)) { return false; } DocumentEventContext docCtx = (DocumentEventContext) event.getContext(); String docType = docCtx.getSourceDocument().getType(); START return !(EXCLUDED_EVENT_TYPES.contains(event.getName()) && (ACCEPTED_COMMENT_TYPE.contains(docType))); END } ```suggestion return !(EXCLUDED_EVENT_TYPES.contains(event.getName()) && ACCEPTED_COMMENT_TYPE.contains(docType)); ```

Target:
public boolean accept(Event event) { if (!(event.getContext() instanceof DocumentEventContext)) { return false; } DocumentEventContext docCtx = (DocumentEventContext) event.getContext(); String docType = docCtx.getSourceDocument().getType(); return !(EXCLUDED_EVENT_TYPES.contains(event.getName()) && ACCEPTED_COMMENT_TYPE.contains(docType)); }
Source:
protected void initialize(Object... args) { super.initialize(args); START final HttpServletRequest request = ctx.getRequest(); END userId = request.getParameter("userId"); workflowInstanceId = request.getParameter("workflowInstanceId"); workflowModelName = request.getParameter("workflowModelName"); } Why `final`?

Target:
protected void initialize(Object... args) { super.initialize(args); HttpServletRequest request = ctx.getRequest(); userId = request.getParameter("userId"); workflowInstanceId = request.getParameter("workflowInstanceId"); workflowModelName = request.getParameter("workflowModelName"); }
Source:
public Builder(String nxqlQuery) { START Objects.requireNonNull(nxqlQuery, "NXQL query cannot be null"); this.query = nxqlQuery; END } You can one-lined the two lines if wanted.

Target:
protected Builder(String nxqlQuery) { this.query = Objects.requireNonNull(nxqlQuery, "NXQL query cannot be null"); }
Source:
public void shouldNotifyEventWhenCreateComment() { // We subscribe to the creation document to check that we will not be notified about the comment creation as // document (see CommentCreationVeto), only the comment added, and the 'File' document creation START DocumentModel comment = captureAndVerifyCommentEventNotification(() -> { Comment createdComment = createCommentAndAddSubscription(commentedDocumentModel, "CommentAdded", "Creation"); return session.getDocument(new IdRef(createdComment.getId())); }, COMMENT_ADDED, DOCUMENT_CREATED); commentedCommentDocumentModel = comment; captureAndVerifyCommentEventNotification(() -> { Comment createdComment = createCommentAndAddSubscription(comment, "CommentAdded", "Creation"); END return session.getDocument(new IdRef(createdComment.getId())); }, COMMENT_ADDED, DOCUMENT_CREATED); } ~I did so, but this duplicates a lot of code. I would rather have kept the extra argument.~ Edit: By filtering new mails from the others it has been possible to reuse code and not run into that issue Edit: Mail filtering has been dropped, Subscription is done when needed

Target:
public void shouldNotifyEventWhenCreateComment() { // We subscribe to the creation document to check that we will not be notified about the comment creation as // document (see CommentCreationVeto), only the comment added, and the 'File' document creation captureAndVerifyCommentEventNotification(() -> { Comment createdComment = createCommentAndAddSubscription("CommentAdded", "Creation"); return session.getDocument(new IdRef(createdComment.getId())); }, COMMENT_ADDED, DOCUMENT_CREATED); }
Source:
protected void setEscalationRules(DocumentModel node, Map<String, Serializable>... rules) { START node.setPropertyValue(GraphNode.PROP_ESCALATION_RULES, (Serializable) Arrays.asList(rules)); END } what's about using `List.of` in your `Cleanup / Format` commit.

Target:
protected void setEscalationRules(DocumentModel node, Map<String, Serializable>... rules) { node.setPropertyValue(GraphNode.PROP_ESCALATION_RULES, (Serializable) List.of(rules)); }
Source:
protected void writeHeader(List<LogEntry> entity, CSVPrinter printer) throws IOException { START LogEntryCSVWriter writer = (LogEntryCSVWriter) registry.getWriter(ctx, LogEntry.class, TEXT_CSV_TYPE); END writer.writeHeader(printer); } I think I would prefer a static method on `LogEntryCSVWriter` writing the header than getting a writer through the registry... ```java LogEntryCSVWriter.writeHeader(ctx, printer); ```

Target:
protected void writeHeader(List<LogEntry> entity, CSVPrinter printer) throws IOException { LogEntryCSVWriter.writeHeader(printer, ctx); }
Source:
private void assertXMLEquals(String expected, String actual) { START if (expected == null || expected.trim().isEmpty()) { END assertEquals(XML_INTRO, actual); } else { assertEquals(XML_INTRO_OPEN + expected + XML_INTRO_CLOSE, actual); } } This is in a test and we know what we argument we pass (never `null`) so `if (expected.isEmpty())` is enough.

Target:
private void assertXMLEquals(String expected, String actual) { if (expected.isEmpty()) { assertEquals(XML_INTRO, actual); } else { assertEquals(XML_INTRO_OPEN + expected + XML_INTRO_CLOSE, actual); } }
Source:
protected List<String> getPropertiesToFetch() { Set<String> fetched = ctx.getFetched(ENTITY_TYPE); List<String> propertiesToFetch = DEFAULT_PROPERTIES.stream() .filter(fetched::contains) .collect(Collectors.toList()); // if no particular property to fetch, fetch all default properties propertiesToFetch = propertiesToFetch.isEmpty() ? DEFAULT_PROPERTIES : propertiesToFetch; START return propertiesToFetch; END } Could be: ```suggestion return propertiesToFetch.isEmpty() ? DEFAULT_PROPERTIES : propertiesToFetch; ```

Target:
protected List<String> getPropertiesToFetch() { Set<String> fetched = ctx.getFetched(ENTITY_TYPE); List<String> propertiesToFetch = DEFAULT_PROPERTIES.stream() .filter(fetched::contains) .collect(Collectors.toList()); // if no particular property to fetch, fetch all default properties return propertiesToFetch.isEmpty() ? DEFAULT_PROPERTIES : propertiesToFetch; }
Source:
public SimpleDocumentModel(String... schemas) { START this(Arrays.asList(schemas)); END } can be replaced by `List.of`

Target:
public SimpleDocumentModel(String... schemas) { this(List.of(schemas)); }
Source:
protected DocumentTypeDescriptor mergeDocumentTypeDescriptors(DocumentTypeDescriptor src, DocumentTypeDescriptor dst) { START return (DocumentTypeDescriptor) dst.clone().merge(src); END } No need to add a cast

Target:
protected DocumentTypeDescriptor mergeDocumentTypeDescriptors(DocumentTypeDescriptor src, DocumentTypeDescriptor dst) { return dst.clone().merge(src); }
Source:
public void deleteComment(CoreSession s, String commentId) { DocumentModel commentDocumentModel = CoreInstance.doPrivileged(s, session -> { return getCommentDocumentModel(session, new IdRef(commentId)); }); START removeComment(s, commentDocumentModel.getRef()); END } But `removeComment` is a protected method right? it doesn't need to follow the public method contract.

Target:
public void deleteComment(CoreSession s, String commentId) { removeComment(s, new IdRef(commentId)); }
Source:
protected String copyRecurse(String sourceId, String parentId, LinkedList<String> ancestorIds, String name, boolean excludeSpecialChildren, boolean excludeRegularChildren) { String copyId = copy(sourceId, parentId, ancestorIds, name); ancestorIds.addLast(copyId); for (String childId : getChildrenIds(sourceId, excludeSpecialChildren, excludeRegularChildren)) { // don't exclude regular children when recursing START copyRecurse(childId, copyId, ancestorIds, null, true, false); END } ancestorIds.removeLast(); return copyId; } Let's keep passing `excludeSpecialChildren` instead of `true` to be consistent with VCS.

Target:
protected String copyRecurse(String sourceId, String parentId, LinkedList<String> ancestorIds, String name, boolean excludeSpecialChildren, boolean excludeRegularChildren) { String copyId = copy(sourceId, parentId, ancestorIds, name); ancestorIds.addLast(copyId); for (String childId : getChildrenIds(sourceId, excludeSpecialChildren, excludeRegularChildren)) { // don't exclude regular children when recursing copyRecurse(childId, copyId, ancestorIds, null, excludeSpecialChildren, false); } ancestorIds.removeLast(); return copyId; }
Source:
protected File getTargetFile(String suffix) { START String filename = String.format("test%s.properties", suffix == null ? "" : suffix); END return new File(Environment.getDefault().getConfig(), filename); } The case where `suffix == null` isn't used, so this can be simplified.

Target:
protected File getTargetFile(String suffix) { String filename = String.format("test%s.properties", suffix); return new File(Environment.getDefault().getConfig(), filename); }
Source:
public void shouldCallHtmlEscape() throws OperationException { Map<String, Object> params = new HashMap<>(); START params.put("script", "Context.htmlEscape = Fn.htmlEscape(\" cou&cou \");"); END try (OperationContext ctx = new OperationContext()) { automationService.run(ctx, "RunScript", params); assertEquals(" cou&amp;cou ", ctx.get("htmlEscape")); } } Could you use `Map.of` method to build the map?

Target:
public void shouldCallHtmlEscape() throws OperationException { Map<String, Object> params = Map.of("script", "Context.htmlEscape = Fn.htmlEscape(\" cou&cou \");"); try (OperationContext ctx = new OperationContext()) { automationService.run(ctx, "RunScript", params); assertEquals(" cou&amp;cou ", ctx.get("htmlEscape")); } }
Source:
protected DocumentModel createHiddenFolder(CoreSession session, String parentPath, String name) { DocumentModel dm = session.createDocumentModel(parentPath, name, "HiddenFolder"); dm.setProperty("dublincore", "title", name); dm.setProperty("dublincore", "description", ""); Framework.doPrivileged(() -> dm.setProperty("dublincore", "created", Calendar.getInstance())); DocumentModel parent = session.createDocument(dm); // change variable name to be effectively final START setFolderPermissions(session, dm); END return parent; } Why do we need this change?

Target:
protected DocumentModel createHiddenFolder(CoreSession session, String parentPath, String name) { DocumentModel dm = session.createDocumentModel(parentPath, name, "HiddenFolder"); dm.setProperty("dublincore", "title", name); dm.setProperty("dublincore", "description", ""); Framework.doPrivileged(() -> dm.setProperty("dublincore", "created", Calendar.getInstance())); DocumentModel parent = session.createDocument(dm); // change variable name to be effectively final setFolderPermissions(session, parent); return parent; }
Source:
protected static <R> R runAndCleanupTransactionContext(Supplier<R> supplier) { try { return supplier.get(); } finally { if (!TransactionHelper.isNoTransaction()) { // restore the no-transaction context of this thread try { START TransactionHelper.commitOrRollbackTransaction(); END } catch (TransactionRuntimeException e) { log.error("Failed to commit/rollback", e); } } } } You can call directly the method without `TransactionHelper` right?

Target:
protected static <R> R runAndCleanupTransactionContext(Supplier<R> supplier) { try { return supplier.get(); } finally { if (!isNoTransaction()) { // restore the no-transaction context of this thread try { commitOrRollbackTransaction(); } catch (TransactionRuntimeException e) { log.error("Failed to commit/rollback", e); } } } }
Source:
protected void addBlobToDocument(String docId, String xpath, String fileName, String extension) throws IOException { START File file = Files.createTempFile(fileName, ".".concat(extension)).toFile(); END RestHelper.operation("Blob.AttachOnDocument", file, Map.of(), Map.of("document", docId, "xpath", xpath)); } Here just use simple concatenation: ```suggestion File file = Files.createTempFile(fileName, "." + extension).toFile(); ```

Target:
protected void addBlobToDocument(String docId, String xpath, String fileName, String extension) throws IOException { File file = Files.createTempFile(fileName, "." + extension).toFile(); RestHelper.operation("Blob.AttachOnDocument", file, Map.of(), Map.of("document", docId, "xpath", xpath)); }
Source:
private Blob buildResult() throws IOException { Map<String, Object> result = new HashMap<>(); result.put("total", countTotal); result.put("success", countSuccess); START return Blobs.createJSONBlobFromValue(Collections.singletonList(result)); END } Why a list?

Target:
private Blob buildResult() throws IOException { Map<String, Object> result = new HashMap<>(); result.put("total", countTotal); result.put("success", countSuccess); return Blobs.createJSONBlobFromValue(result); }
Source:
public <T extends Annotation> T getConfig(FrameworkMethod method, Class<T> type) { START if (method != null) { END T config = method.getAnnotation(type); if (config != null) { return config; } } // if not define, try to get the config of the class return getConfig(type); } In which cases does it happen?

Target:
public <T extends Annotation> T getConfig(FrameworkMethod method, Class<T> type) { T config = method.getAnnotation(type); if (config != null) { return config; } // if not define, try to get the config of the class return getConfig(type); }
Source:
public static void afterAll() { START System.setProperty(Framework.NUXEO_TESTING_SYSTEM_PROP, ORIGINAL_TESTING_PROPERTY_VALUE); END } Useless `Framework.`

Target:
public static void afterAll() { System.setProperty(NUXEO_TESTING_SYSTEM_PROP, ORIGINAL_TESTING_PROPERTY_VALUE); }
Source:
START protected static void batchRemoveDocuments(CoreSession adminSession, List<DocumentRef> ids) { END List<DocumentRef> deferredIds = new ArrayList<>(); for (DocumentRef id : ids) { if (!adminSession.exists(id)) { continue; } if (adminSession.canRemoveDocument(id)) { adminSession.removeDocument(id); } else { deferredIds.add(id); } } adminSession.removeDocuments(deferredIds.toArray(new DocumentRef[0])); } Why static?

Target:
protected void batchRemoveDocuments(CoreSession adminSession, List<DocumentRef> ids) { List<DocumentRef> deferredIds = new ArrayList<>(); for (DocumentRef id : ids) { if (!adminSession.exists(id)) { continue; } if (adminSession.canRemoveDocument(id)) { adminSession.removeDocument(id); } else { deferredIds.add(id); } } adminSession.removeDocuments(deferredIds.toArray(new DocumentRef[0])); }
Source:
protected List<NuxeoOAuth2Token> findTokens(QueryBuilder queryBuilder) { return Framework.doPrivileged(() -> { DirectoryService ds = Framework.getService(DirectoryService.class); try (Session session = ds.open(TOKEN_DIR)) { List<DocumentModel> documents = session.query(queryBuilder, false); START return documents.stream().distinct().map(NuxeoOAuth2Token::new).collect(Collectors.toList()); END } }); } Why `distinct()`?

Target:
protected List<NuxeoOAuth2Token> findTokens(QueryBuilder queryBuilder) { return findTokens(queryBuilder, null); }
Source:
public ESHintQueryBuilder newInstance() { try { START return getKlass().getDeclaredConstructor().newInstance(); END } catch (ReflectiveOperationException e) { log.error("Cannot instantiate esHintQueryBuilder from " + getKlass()); throw new NuxeoException(e); } } Except for specific use cases, you should either log or either throw the caught exception. In this case throwing the exception with the message you put in the log is enough.

Target:
public ESHintQueryBuilder newInstance() { try { return getKlass().getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException e) { throw new NuxeoException(e); } }
Source:
public ESHintQueryBuilder newInstance() { try { return getKlass().getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException e) { START throw new NuxeoException(String.format("Cannot instantiate esHintQueryBuilder from %s", getKlass()), e); END } } No need to add details, the base exception message already contains the name of the problematic class. Just do `throw new NuxeoException(e)`.

Target:
public ESHintQueryBuilder newInstance() { try { return getKlass().getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException e) { throw new NuxeoException(e); } }
Source:
public QueryBuilder make(EsHint hint, String fieldName, Object value) { CommonTermsQueryBuilder commonQuery = QueryBuilders.commonTermsQuery(fieldName, value); if (hint.analyzer != null) { START commonQuery.analyzer(hint.analyzer); END } return commonQuery; } You don't need the null check, the `analyzer` method accepts a `null` without issue.

Target:
public QueryBuilder make(EsHint hint, String fieldName, Object value) { return QueryBuilders.commonTermsQuery(fieldName, value).analyzer(hint.analyzer); }
Source:
public QueryBuilder make(EsHint hint, String fieldName, Object value) { String valueString = (String) value; if (valueString.endsWith("*") && valueString.length() > 2) { // remove useless trailing *, this is not mandatory but cleaner value = valueString.substring(0, valueString.length() - 1); } MatchPhrasePrefixQueryBuilder matchPhrasePrefixQuery = QueryBuilders.matchPhrasePrefixQuery(fieldName, value); if (hint.analyzer != null) { START matchPhrasePrefixQuery.analyzer(hint.analyzer); END } return matchPhrasePrefixQuery; } No need for `null` check.

Target:
public QueryBuilder make(EsHint hint, String fieldName, Object value) { String valueString = (String) value; if (valueString.endsWith("*") && valueString.length() > 2) { // remove useless trailing *, this is not mandatory but cleaner value = valueString.substring(0, valueString.length() - 1); } return QueryBuilders.matchPhrasePrefixQuery(fieldName, value).analyzer(hint.analyzer); }
Source:
public void shouldRetrievePermissionWithoutFailure() { assertNotNull(uiPermissionService); String[] permissions = uiPermissionService.getUIPermissions("unExistingType"); assertNotNull(permissions); START assertTrue(permissions.length == 0); END } `assertEquals(0, permissions.length)`

Target:
public void shouldRetrievePermissionWithoutFailure() { assertNotNull(uiPermissionService); String[] permissions = uiPermissionService.getUIPermissions("unExistingType"); assertNotNull(permissions); assertEquals(0, permissions.length); }
Source:
public <T> T getAdapter(Class<T> adapter) { START if (adapter == UserWorkspaceServiceImplComponent.class) { END return (T) this; } if (adapter == UserWorkspaceService.class) { return adapter.cast(getUserWorkspaceService()); } if (adapter == CollectionLocationService.class) { return adapter.cast(getUserWorkspaceService()); } return null; } `getClass()` ?

Target:
public <T> T getAdapter(Class<T> adapter) { if (adapter == UserWorkspaceServiceImplComponent.class) { return adapter.cast(this); } else if (adapter == UserWorkspaceService.class) { return adapter.cast(getUserWorkspaceService()); } else if (adapter == CollectionLocationService.class) { return adapter.cast(getUserWorkspaceService()); } return null; }
Source:
public void shouldRegisterActionContribution() { assertNotNull(directoryTreeService); assertTrue(directoryTreeService.getDirectoryTrees().contains("anyNavigation")); START ActionService actionService = (ActionService) Framework.getService(ActionManager.class); END assertNotNull(actionService); Action action = actionService.getAction(DirectoryTreeDescriptor.ACTION_ID_PREFIX + "anyNavigation"); assertNotNull(action); } Why not injecting `ActionService` directly?

Target:
public void shouldRegisterActionContribution() { assertNotNull(directoryTreeService); assertNotNull(actionService); assertTrue(directoryTreeService.getDirectoryTrees().contains("anyNavigation")); Action action = actionService.getAction(DirectoryTreeDescriptor.ACTION_ID_PREFIX + "anyNavigation"); assertNotNull(action); }
Source:
public void shouldBeRotatableByTheCreator() { START boolean canRotatePicture = actionService.checkFilter(ROTATE_PICTURE_FILTER_NAME, getActionContext(coreSession)); END assertTrue(canRotatePicture); } I'm not sure we need that boolean variable, it would be enough to do: ```suggestion assertTrue(actionService.checkFilter(ROTATE_PICTURE_FILTER_NAME, getActionContext(coreSession))); ```

Target:
public void shouldBeRotatableByTheCreator() { assertTrue(actionService.checkFilter(ROTATE_PICTURE_FILTER_NAME, getActionContext(coreSession))); }
Source:
protected ACE getACE(String username, String permission) { START return new ACE(username, permission, Boolean.TRUE); END } ```suggestion return new ACE(username, permission, true); ```

Target:
protected ACE getACE(String username, String permission) { return new ACE(username, permission, true); }
Source:
public Record beforeAppend(Record record) { START if (filters.isEmpty()) { END return record; } for (RecordFilter filter : filters) { if (record != null) { record = filter.beforeAppend(record); } } return record; } You don't need to have this condition as there's just a loop doing nothing if `filters` is empty.

Target:
public Record beforeAppend(Record record) { for (Iterator iterator = filters.iterator(); record != null && iterator.hasNext();) { RecordFilter filter = (RecordFilter) iterator.next(); record = filter.beforeAppend(record); } return record; }
Source:
public void work() { START log.warn(getTitle() + " is running"); END if (veryLongString.length() != size) { throw new IllegalStateException("Invalid string size: " + veryLongString.length() + " instead of: " + size); } } `debug`, we don't want to pollute test output

Target:
public void work() { log.debug(getTitle() + " is running"); if (veryLongString.length() != size) { throw new IllegalStateException("Invalid string size: " + veryLongString.length() + " instead of: " + size); } }
Source:
private LibrarySelector getLibrarySelectorService() { START LibrarySelector librarySelector = Framework.getRuntime().getService(LibrarySelector.class); END if (librarySelector == null) { log.error("Unable to get LibrarySelector runtime service"); throw new NuxeoException("Unable to get LibrarySelector runtime service"); } return librarySelector; } Could be `Framework.getService(LibrarySelector.class);`

Target:
private LibrarySelector getLibrarySelectorService() { LibrarySelector librarySelector = Framework.getService(LibrarySelector.class); if (librarySelector == null) { log.error("Unable to get LibrarySelector runtime service"); throw new NuxeoException("Unable to get LibrarySelector runtime service"); } return librarySelector; }
Source:
protected boolean isUnicityCheckEnabled() { START return Framework.getRuntime().getService(FileManager.class).isUnicityEnabled(); END } ```suggestion return Framework.getService(FileManager.class).isUnicityEnabled(); ```

Target:
protected boolean isUnicityCheckEnabled() { return Framework.getService(FileManager.class).isUnicityEnabled(); }
Source:
protected void removeItemFromArrayProperty(DocumentModel doc, Property property) { if (index != null) { Serializable[] value = (Serializable[]) property.getValue(); List<Serializable> list = new ArrayList<>(Arrays.asList(value)); list.remove(index.intValue()); START doc.setPropertyValue(xpath, list.toArray(new Serializable[0])); END } else { doc.setPropertyValue(xpath, null); } } Could you check just with `doc.setPropertyValue(xpath, list)`? I think the low level code does the conversion automatically to the expected type.

Target:
protected void removeItemFromArrayProperty(DocumentModel doc, Property property) { if (index != null) { Serializable[] value = (Serializable[]) property.getValue(); List<Serializable> list = new ArrayList<>(Arrays.asList(value)); list.remove(index.intValue()); doc.setPropertyValue(xpath, (Serializable) list); } else { doc.setPropertyValue(xpath, null); } }
Source:
protected void waitForAsyncCompletion() { START nextTransaction(); END transactionalFeature.nextTransaction(); eventService.waitForAsyncCompletion(); } You can remove this line, this is done in `transactionalFeature.nextTransaction()`

Target:
protected void waitForAsyncCompletion() { transactionalFeature.nextTransaction(); eventService.waitForAsyncCompletion(); }
Source:
public void testConverter() throws Exception { String converterName = cs.getConverterName("text/plain", "application/pdf"); assertEquals("any2pdf", converterName); checkConverterAvailability(converterName); checkCommandAvailability("soffice"); BlobHolder result = convertTextBlob(converterName); checkPDFDocument(result); START checkPDFDocument(result); END } My bad, not needed :)

Target:
public void testConverter() throws Exception { String converterName = cs.getConverterName("text/plain", "application/pdf"); assertEquals("any2pdf", converterName); checkConverterAvailability(converterName); checkCommandAvailability("soffice"); BlobHolder result = convertTextBlob(converterName); checkPDFDocument(result); }
Source:
public boolean validate(Object value, Object context) { if (validation) { START MutableBoolean validated = new MutableBoolean(); END resolve(value, context, (session, docRef) -> { if (session.exists(docRef)) { validated.setTrue(); } }); return validated.isTrue(); } return true; } Please don't introduce extra indentation when you can just do early exit: if (!validation) { return true; } // original code here This also makes the diff easier to read.

Target:
public boolean validate(Object value, Object context) { if (!validation) { return true; } MutableBoolean validated = new MutableBoolean(); resolve(value, context, (session, docRef) -> { if (session.exists(docRef)) { validated.setTrue(); } }); return validated.isTrue(); }
Source:
public void initOAuthClient() { // Clients to make the requests like a "Client" as the OAuth2 RFC describes it // Authenticated client for the /oauth2/authorize and /oauth2/authorize_submit endpoints authenticatedClient = JerseyClientHelper.clientBuilder() .setRedirectsEnabled(false) .setCredentials("Administrator", "Administrator") .build(); // Unauthenticated client for the /oauth2/token endpoint client = JerseyClientHelper.clientBuilder() .setRedirectsEnabled(false) .setConnectionRequestTimeout(500000) .setSocketTimeout(500000) START .setConnectTimeout(500000) END .build(); transientStore = (TransientStoreProvider) transientStoreService.getStore(AuthorizationRequest.STORE_NAME); tokenStore = new OAuth2TokenStore(TOKEN_SERVICE); } I don't think setting the timeouts are required in this test, especially since the default is already 60 seconds.

Target:
public void initOAuthClient() { // Clients to make the requests like a "Client" as the OAuth2 RFC describes it // Authenticated client for the /oauth2/authorize and /oauth2/authorize_submit endpoints authenticatedClient = JerseyClientHelper.clientBuilder() .setRedirectsEnabled(false) .setCredentials("Administrator", "Administrator") .build(); // Unauthenticated client for the /oauth2/token endpoint client = JerseyClientHelper.clientBuilder().setRedirectsEnabled(false).build(); transientStore = (TransientStoreProvider) transientStoreService.getStore(AuthorizationRequest.STORE_NAME); tokenStore = new OAuth2TokenStore(TOKEN_SERVICE); }