auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void writeEntries() { if (entries.get().isEmpty()) { return; } StreamManager streamManager = getStreamManager(); for (LogEntry entry : entries.get()) { Record record = recordOf(entry); if (entry != null) { streamManager.append(STREAM_NAME, record); } } }

Target:
Should `recordOf` call be inside the if?
Source:
public boolean match(Name name) { if (patterns.stream().anyMatch(pattern -> name.getUrn().startsWith(pattern))) { return true; } return false; }

Target:
Why not just returning the result of `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; } if (match(name)) { return true; } return false; }

Target:
Not needed.
Source:
public List<BundleInfo> getBundles() { List<BundleInfo> res = new ArrayList<>(bundles.values()); // order by name for deterministic processing Collections.sort(res, Comparator.comparing(BundleInfo::getId)); return res; }

Target:
`List#sort` usage.
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 { Assume.assumeTrue("Kafka not enabled", false); } }

Target:
It could be imported statically.
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()); assertSame(0, children.size()); }

Target:
assertEquals everytime you compare two numbers that fit in a long
Source:
private 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); } }

Target:
we don't use `private` accessor
Source:
public CSVLoaderConsumer(String dataLoadingPolicy, Session session, String schema) { this.dataLoadingPolicy = Objects.requireNonNull(dataLoadingPolicy, "duplicatePolicy must not be null"); 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"); }

Target:
`duplicatePolicy` -> `dataLoadingPolicy`
Source:
public String getInput() { Serializable input = getProperty(RetentionConstants.INPUT_PROPERTY_KEY); if (input instanceof String) { return (String) input; } return null; }

Target:
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
Source:
public void createUser(String userName) { try { DocumentModel userModel = userManager.getBareUserModel(); userModel.setProperty("user", "username", userName); userModel.setProperty("user", "password", userName); userManager.createUser(userModel); } catch (UserAlreadyExistsException e) { // Avoid failure in tests if the user already exists log.trace("User already exists", e); } }

Target:
Not sure you need the `password` as you don't use it.
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())); }, COMMENT_ADDED, DOCUMENT_CREATED, 2); }

Target:
Useless blank line.
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())); }, COMMENT_UPDATED, DOCUMENT_UPDATED, 1); }

Target:
Useless blank line.
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; }, COMMENT_REMOVED, DOCUMENT_REMOVED, 0); }

Target:
Useless blank line.
Source:
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))); }

Target:
```suggestion return !(EXCLUDED_EVENT_TYPES.contains(event.getName()) && ACCEPTED_COMMENT_TYPE.contains(docType)); ```
Source:
protected void initialize(Object... args) { super.initialize(args); final HttpServletRequest request = ctx.getRequest(); userId = request.getParameter("userId"); workflowInstanceId = request.getParameter("workflowInstanceId"); workflowModelName = request.getParameter("workflowModelName"); }

Target:
Why `final`?
Source:
public Builder(String nxqlQuery) { Objects.requireNonNull(nxqlQuery, "NXQL query cannot be null"); this.query = nxqlQuery; }

Target:
You can one-lined the two lines if wanted.
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 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"); return session.getDocument(new IdRef(createdComment.getId())); }, COMMENT_ADDED, DOCUMENT_CREATED); }

Target:
~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
Source:
protected void setEscalationRules(DocumentModel node, Map<String, Serializable>... rules) { node.setPropertyValue(GraphNode.PROP_ESCALATION_RULES, (Serializable) Arrays.asList(rules)); }

Target:
what's about using `List.of` in your `Cleanup / Format` commit.
Source:
protected void writeHeader(List<LogEntry> entity, CSVPrinter printer) throws IOException { LogEntryCSVWriter writer = (LogEntryCSVWriter) registry.getWriter(ctx, LogEntry.class, TEXT_CSV_TYPE); writer.writeHeader(printer); }

Target:
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); ```
Source:
private void assertXMLEquals(String expected, String actual) { if (expected == null || expected.trim().isEmpty()) { assertEquals(XML_INTRO, actual); } else { assertEquals(XML_INTRO_OPEN + expected + XML_INTRO_CLOSE, actual); } }

Target:
This is in a test and we know what we argument we pass (never `null`) so `if (expected.isEmpty())` is enough.
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; return propertiesToFetch; }

Target:
Could be: ```suggestion return propertiesToFetch.isEmpty() ? DEFAULT_PROPERTIES : propertiesToFetch; ```
Source:
public SimpleDocumentModel(String... schemas) { this(Arrays.asList(schemas)); }

Target:
can be replaced by `List.of`
Source:
protected DocumentTypeDescriptor mergeDocumentTypeDescriptors(DocumentTypeDescriptor src, DocumentTypeDescriptor dst) { return (DocumentTypeDescriptor) dst.clone().merge(src); }

Target:
No need to add a cast
Source:
public void deleteComment(CoreSession s, String commentId) { DocumentModel commentDocumentModel = CoreInstance.doPrivileged(s, session -> { return getCommentDocumentModel(session, new IdRef(commentId)); }); removeComment(s, commentDocumentModel.getRef()); }

Target:
But `removeComment` is a protected method right? it doesn't need to follow the public method contract.
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 copyRecurse(childId, copyId, ancestorIds, null, true, false); } ancestorIds.removeLast(); return copyId; }

Target:
Let's keep passing `excludeSpecialChildren` instead of `true` to be consistent with VCS.
Source:
protected File getTargetFile(String suffix) { String filename = String.format("test%s.properties", suffix == null ? "" : suffix); return new File(Environment.getDefault().getConfig(), filename); }

Target:
The case where `suffix == null` isn't used, so this can be simplified.
Source:
public void shouldCallHtmlEscape() throws OperationException { Map<String, Object> params = new HashMap<>(); params.put("script", "Context.htmlEscape = Fn.htmlEscape(\" cou&cou \");"); try (OperationContext ctx = new OperationContext()) { automationService.run(ctx, "RunScript", params); assertEquals(" cou&amp;cou ", ctx.get("htmlEscape")); } }

Target:
Could you use `Map.of` method to build the map?
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 setFolderPermissions(session, dm); return parent; }

Target:
Why do we need this change?
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 { TransactionHelper.commitOrRollbackTransaction(); } catch (TransactionRuntimeException e) { log.error("Failed to commit/rollback", e); } } } }

Target:
You can call directly the method without `TransactionHelper` right?
Source:
protected void addBlobToDocument(String docId, String xpath, String fileName, String extension) throws IOException { File file = Files.createTempFile(fileName, ".".concat(extension)).toFile(); RestHelper.operation("Blob.AttachOnDocument", file, Map.of(), Map.of("document", docId, "xpath", xpath)); }

Target:
Here just use simple concatenation: ```suggestion File file = Files.createTempFile(fileName, "." + extension).toFile(); ```
Source:
private Blob buildResult() throws IOException { Map<String, Object> result = new HashMap<>(); result.put("total", countTotal); result.put("success", countSuccess); return Blobs.createJSONBlobFromValue(Collections.singletonList(result)); }

Target:
Why a list?
Source:
public <T extends Annotation> T getConfig(FrameworkMethod method, Class<T> type) { if (method != null) { T config = method.getAnnotation(type); if (config != null) { return config; } } // if not define, try to get the config of the class return getConfig(type); }

Target:
In which cases does it happen?
Source:
public static void afterAll() { System.setProperty(Framework.NUXEO_TESTING_SYSTEM_PROP, ORIGINAL_TESTING_PROPERTY_VALUE); }

Target:
Useless `Framework.`
Source:
protected static 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])); }

Target:
Why static?
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); return documents.stream().distinct().map(NuxeoOAuth2Token::new).collect(Collectors.toList()); } }); }

Target:
Why `distinct()`?
Source:
public ESHintQueryBuilder newInstance() { try { return getKlass().getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException e) { log.error("Cannot instantiate esHintQueryBuilder from " + getKlass()); throw new NuxeoException(e); } }

Target:
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.
Source:
public ESHintQueryBuilder newInstance() { try { return getKlass().getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException e) { throw new NuxeoException(String.format("Cannot instantiate esHintQueryBuilder from %s", getKlass()), e); } }

Target:
No need to add details, the base exception message already contains the name of the problematic class. Just do `throw new NuxeoException(e)`.
Source:
public QueryBuilder make(EsHint hint, String fieldName, Object value) { CommonTermsQueryBuilder commonQuery = QueryBuilders.commonTermsQuery(fieldName, value); if (hint.analyzer != null) { commonQuery.analyzer(hint.analyzer); } return commonQuery; }

Target:
You don't need the null check, the `analyzer` method accepts a `null` without issue.
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) { matchPhrasePrefixQuery.analyzer(hint.analyzer); } return matchPhrasePrefixQuery; }

Target:
No need for `null` check.
Source:
public void shouldRetrievePermissionWithoutFailure() { assertNotNull(uiPermissionService); String[] permissions = uiPermissionService.getUIPermissions("unExistingType"); assertNotNull(permissions); assertTrue(permissions.length == 0); }

Target:
`assertEquals(0, permissions.length)`
Source:
public <T> T getAdapter(Class<T> adapter) { if (adapter == UserWorkspaceServiceImplComponent.class) { return (T) this; } if (adapter == UserWorkspaceService.class) { return adapter.cast(getUserWorkspaceService()); } if (adapter == CollectionLocationService.class) { return adapter.cast(getUserWorkspaceService()); } return null; }

Target:
`getClass()` ?
Source:
public void shouldRegisterActionContribution() { assertNotNull(directoryTreeService); assertTrue(directoryTreeService.getDirectoryTrees().contains("anyNavigation")); ActionService actionService = (ActionService) Framework.getService(ActionManager.class); assertNotNull(actionService); Action action = actionService.getAction(DirectoryTreeDescriptor.ACTION_ID_PREFIX + "anyNavigation"); assertNotNull(action); }

Target:
Why not injecting `ActionService` directly?
Source:
public void shouldBeRotatableByTheCreator() { boolean canRotatePicture = actionService.checkFilter(ROTATE_PICTURE_FILTER_NAME, getActionContext(coreSession)); assertTrue(canRotatePicture); }

Target:
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))); ```
Source:
protected ACE getACE(String username, String permission) { return new ACE(username, permission, Boolean.TRUE); }

Target:
```suggestion return new ACE(username, permission, true); ```
Source:
public Record beforeAppend(Record record) { if (filters.isEmpty()) { return record; } for (RecordFilter filter : filters) { if (record != null) { record = filter.beforeAppend(record); } } return record; }

Target:
You don't need to have this condition as there's just a loop doing nothing if `filters` is empty.
Source:
public void work() { log.warn(getTitle() + " is running"); if (veryLongString.length() != size) { throw new IllegalStateException("Invalid string size: " + veryLongString.length() + " instead of: " + size); } }

Target:
`debug`, we don't want to pollute test output
Source:
private LibrarySelector getLibrarySelectorService() { LibrarySelector librarySelector = Framework.getRuntime().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; }

Target:
Could be `Framework.getService(LibrarySelector.class);`
Source:
protected boolean isUnicityCheckEnabled() { return Framework.getRuntime().getService(FileManager.class).isUnicityEnabled(); }

Target:
```suggestion 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()); doc.setPropertyValue(xpath, list.toArray(new Serializable[0])); } else { doc.setPropertyValue(xpath, null); } }

Target:
Could you check just with `doc.setPropertyValue(xpath, list)`? I think the low level code does the conversion automatically to the expected type.
Source:
protected void waitForAsyncCompletion() { nextTransaction(); transactionalFeature.nextTransaction(); eventService.waitForAsyncCompletion(); }

Target:
You can remove this line, this is done in `transactionalFeature.nextTransaction()`
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); checkPDFDocument(result); }

Target:
My bad, not needed :)
Source:
public boolean validate(Object value, Object context) { if (validation) { MutableBoolean validated = new MutableBoolean(); resolve(value, context, (session, docRef) -> { if (session.exists(docRef)) { validated.setTrue(); } }); return validated.isTrue(); } return true; }

Target:
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.
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) .setConnectTimeout(500000) .build(); transientStore = (TransientStoreProvider) transientStoreService.getStore(AuthorizationRequest.STORE_NAME); tokenStore = new OAuth2TokenStore(TOKEN_SERVICE); }

Target:
I don't think setting the timeouts are required in this test, especially since the default is already 60 seconds.
Source:
public static boolean isTestModeSet() { String testModeCacheDisabled = System.getProperty(NUXEO_TESTING_PROP_CACHE_DISABLED); if (Boolean.FALSE.equals(Boolean.parseBoolean(testModeCacheDisabled))) { if (testModeSet == null) { testModeSet = isBooleanPropertyTrue(NUXEO_TESTING_SYSTEM_PROP); } return testModeSet; } return isBooleanPropertyTrue(NUXEO_TESTING_SYSTEM_PROP); }

Target:
Note that `parseBoolean` returns a `boolean`, not a `Boolean`. But you can use `Boolean.getBoolean(syspropname)` instead of `System.getProperty` + `Boolean.parseBoolean`
Source:
protected List<?> doPublishIfEntries(List<?> entries) { if (entries == null || entries.size() == 0) { return entries; } Object entry = entries.get(0); if (entry instanceof LogEntry) { for (Object logEntry : entries) { try { doPublish((LogEntry) logEntry); } catch (RuntimeException e) { log.warn("unable to read log entry", e); } } } return entries; }

Target:
Which exception has been observed here? Please don't catch exceptions when we don't actually know what they are.
Source:
public CommentSecurityException() { super(); this.statusCode = SC_FORBIDDEN; }

Target:
`super(SC_FORBIDDEN)` and similarly for other constructors
Source:
protected boolean overlapInstant(Instant aStart, Instant aEnd, Instant bStart, Instant bEnd) { return (aStart.isBefore(bEnd) && bStart.isBefore(aEnd)); }

Target:
Remove extra parentheses
Source:
private TransientStore getTransientStore() { return Framework.getService(TransientStoreService.class).getStore(STATUS_STORE_NAME); }

Target:
all private methods should be protected
Source:
protected DocumentModel attach(DocumentModel doc) { String sid = ctx.getCoreSession().getSessionId(); try { doc = doc.clone(); } catch (CloneNotSupportedException e) { // doc models not supporting clone do not rely on session id anyway } doc.attach(sid); return doc; }

Target:
Why clone the doc?
Source:
public boolean hasCompatibleMimeType(List<String> mimeTypes, String mimeType) { String mt = parseMimeType(mimeType); Set<String> expectedMimeTypes = new HashSet<>(); expectedMimeTypes.add(ANY_MIME_TYPE); if (mimeType != null) { expectedMimeTypes.add(mt); expectedMimeTypes.add(computeMimeTypeWithWildcardSubType(mt)); } return mimeTypes.stream().anyMatch(expectedMimeTypes::contains); }

Target:
Shouldn't be `mt != null` for consistency ?
Source:
public void setPolicy(ComputationPolicy policy) { this.policy = policy; }

Target:
Shouldn't be protected as this method is used only in tests + shouldn't be something editable no ?
Source:
protected static Blob readStringBlob(String ctype, String fileName, String content) throws IOException { Blob blob = new StringBlob(fileName, content, ctype); return blob; }

Target:
Can be on one line and doesn't need to throw `IOException`.
Source:
public void start(ComponentContext context) { super.start(context); Collection<MongoDBConnectionConfig> confs = getDescriptors(XP_CONNECTION); confs.forEach(c -> { log.debug("Initializing MongoClient with id={}", c.getId()); clients.put(c.getId(), MongoDBConnectionHelper.newMongoClient(c.server)); }); }

Target:
`c::getId`
Source:
public void stop(ComponentContext context) throws InterruptedException { super.stop(context); // don't remove entrySet otherwise java will try to load mongo client classes even in a non mongo setup clients.entrySet().forEach(e -> { log.debug("Closing MongoClient with id={}", e.getKey()); e.getValue().close(); }); clients.clear(); }

Target:
`e::getKey`
Source:
public DataBucket(String commandId, long count, byte[] data) { this(commandId, count, data, new byte[]{}, new byte[]{}); }

Target:
`new byte[]{}` -> `new byte[0]`
Source:
public DocumentModel getThreadForComment(DocumentModel comment) { CoreSession session = comment.getCoreSession(); DocumentModel parent = session.getDocument(new IdRef((String) comment.getPropertyValue(COMMENT_PARENT_ID))); if (!COMMENT_DOC_TYPE.equals(parent.getType())) { return comment; } return getThreadForComment(parent); }

Target:
Can you reverse condition ? just for clarity.
Source:
protected boolean isImporterAvailable(FileImporter importer, String normalizedMimeType, String mimeType, boolean excludeOneToMany) { return importer.isEnabled() && (!excludeOneToMany || !importer.isOneToMany()) && (importer.matches(normalizedMimeType) || importer.matches(mimeType)); }

Target:
Personally I read this better with `&& !(importer.isOneToMany() && excludeOneToMany)` but up to you.
Source:
public boolean register(String target, String xp, Descriptor descriptor) { log.trace("Register to {}/{}", descriptor.getId(), target, xp); return descriptors.computeIfAbsent(target, k -> new HashMap<>()) .computeIfAbsent(xp, k -> new LinkedHashMap<>()) .computeIfAbsent(descriptor.getId(), k -> new ArrayList<>()) .add(descriptor); }

Target:
I'd prefer `debug` for all these. We reserve `trace` to logging really low-level and expensive stuff, like all traffic to/from a database or huge outputs.
Source:
String getKey(String commandId) { return metadata.name() + commandId; }

Target:
Missing `protected` keyword ?
Source:
protected static Long getLastOffset(String workId) { String stringOffset = getKeyValueStore().getString(getOffsetKey(workId)); return stringOffset == null ? Long.valueOf(-1) : Long.parseLong(stringOffset); }

Target:
or long ?
Source:
protected void checkpointIfNecessary() { if (context.requireCheckpoint()) { boolean completed = false; try { checkpoint(); completed = true; inCheckpointRecords = inRecords; } catch (Exception e) { log.error(e, e); } finally { if (!completed) { log.error(metadata.name() + ": CHECKPOINT FAILURE: Resume may create duplicates."); } } } }

Target:
Is this intended ? It could hide problems as the current runner won't be stopped.
Source:
public static int partitions(Path basePath) { Path metadataPath = basePath.resolve(METADATA_FILE); if (metadataPath.toFile().exists()) { return Integer.valueOf(readMetadata(metadataPath).getProperty(PARTITIONS_KEY)); } // backward compatibility before metadata file return discoverPartitions(basePath); }

Target:
`valueOf` -> `parseInt`
Source:
public List<DocumentModel> getComments(CoreSession session, DocumentModel docModel) { PageProviderService ppService = Framework.getService(PageProviderService.class); Map<String, Serializable> props = Collections.singletonMap( CoreQueryAndFetchPageProvider.CORE_SESSION_PROPERTY, (Serializable) session); PageProvider<DocumentModel> pageProvider = (PageProvider<DocumentModel>) ppService.getPageProvider( GET_COMMENTS_FOR_DOC_PAGEPROVIDER_NAME, singletonList(new SortInfo("dc:created", true)), null, null, props, docModel.getId()); return pageProvider.getCurrentPage(); }

Target:
`CORE_SESSION_PROPERTY` as static import.
Source:
protected DocumentModel createNuxeoUser(String nuxeoLogin) { DocumentModel userDoc; try { userDoc = Framework.doPrivileged(() -> { UserManager userManager = Framework.getService(UserManager.class); DocumentModel user = userManager.getBareUserModel(); user.setPropertyValue(userManager.getUserIdField(), nuxeoLogin); return userManager.createUser(user); }); } catch (NuxeoException e) { log.error("Error while creating user " + nuxeoLogin + "in UserManager", e); return null; } return userDoc; }

Target:
We try to limit the scope of what goes inside a `doPrivileged` block, for better auditability. Here I think only this last line needs to be inside the privileged block.
Source:
protected void assertValues(TestDescriptor d, String id, String name, String desc) { Assert.assertEquals(id, d.id); Assert.assertEquals(name, d.name); Assert.assertEquals(desc, d.desc); }

Target:
`import static` all `Assert` static methods.
Source:
public RestBinding[] getBindings() { List<RestBinding> descriptors = getDescriptors(XP_BINDINGS); return descriptors.toArray(new RestBinding[descriptors.size()]); }

Target:
Give 0 as size to the new array, it's faster in java.
Source:
public void stop(ComponentContext context) throws InterruptedException { super.stop(context); // interrupt all migration tasks executor.shutdownNow(); executor.awaitTermination(10, TimeUnit.SECONDS); // wait 10s for termination executor = null; }

Target:
In general you should call `super.stop` last, after all other cleanups.
Source:
public void deactivate(ComponentContext context) { super.deactivate(context); subscribers.clear(); provider.close(); provider = null; }

Target:
Same for `super.deactivate`, you should call it last.
Source:
protected void ensureUserListIsUsed() { users = users == null ? new ArrayList<>() : new ArrayList<>(users); if (user != null && !users.contains(user)) { users.add(user); } else if (email != null && users.isEmpty()) { // share a document with someone not registered in Nuxeo, by using only an email users.add(NuxeoPrincipal.computeTransientUsername(email)); } }

Target:
Hm you're right of course. I thought these params were always reconstructed from scratch by the Automation framework but there's no reason for this to be the case.
Source:
public void processTimer(ComputationContext context, String key, long timestamp) { if (!TIMER_BATCH.equals(key) || batchRecords.isEmpty()) { return; } processBatch(context); context.setTimer(TIMER_BATCH, System.currentTimeMillis() + thresholdMillis); }

Target:
Don't we need to set timer back if `batchRecords` is empty ?
Source:
protected static void createEmbeddedNode() throws IOException { ElasticSearchEmbeddedServerConfig config = new ElasticSearchEmbeddedServerConfig(); config.setHttpEnabled(true); config.setClusterName("nuxeoESClientCluster"); config.setIndexStorageType("mmapfs"); config.setNodeName("nuxeoESClientTestNode"); config.setDataPath(folder.newFolder().getAbsolutePath()); config.setHomePath(folder.newFolder().getAbsolutePath()); System.out.println(config); embeddedNode = new ElasticSearchEmbeddedNode(config); embeddedNode.start(); }

Target:
Maybe use a logger ?
Source:
public String getFirstIndexForAlias(String aliasName) { ImmutableOpenMap<String, List<AliasMetaData>> aliases = client.admin().indices().prepareGetAliases(aliasName).get().getAliases(); for(Iterator<String> it = aliases.keysIt(); it.hasNext(); ) { String indexName = it.next(); if (aliases.get(indexName).isEmpty()) { continue; } return indexName; } return null; }

Target:
What about using stream api and directly have a return from the first line?
Source:
public BulkServiceImpl(BulkServiceDescriptor descriptor) { this.descriptor = descriptor; kvStore = Framework.getService(KeyValueService.class).getKeyValueStore(descriptor.kvStore); logManager = Framework.getService(StreamService.class).getLogManager(descriptor.logConfig); }

Target:
Please don't store these, look them up every time they are needed. We don't want to store service-derived information in long-running components.
Source:
protected void recomputeClassFilters() { Set<String> classNames = new HashSet<>(); for (ClassFilterDescriptor desc : classFilterDescriptors) { if (desc.deny.contains("*")) { classNames.clear(); classNames.addAll(desc.allow); } else { classNames.addAll(desc.allow); classNames.removeAll(desc.deny); } } // we don't care about update atomicity, as nothing executes concurrently with XML config service.allowedClassNames.clear(); service.allowedClassNames.addAll(classNames); }

Target:
Its probably clearer to call this variable `allowedClassNames`, I had a long look at the if/else logic because `classNames.addAll(desc.allow)` is in both the if and else. I understand now because its building a list of allowed class names.
Source:
private static void assertDocumentPropertiesChanges(DocumentModel doc, Map<String, Object> originalProperties, Set<String> expectedChangedPropertyNames) { originalProperties.keySet().forEach(property -> { Object currentValue = doc.getProperty("dublincore", property); if (expectedChangedPropertyNames.contains(property)) { assertNotEquals(originalProperties.get(property), currentValue); } else { assertEquals(currentValue, originalProperties.get(property)); } }); }

Target:
Here you can use `forEach` directly on the map.
Source:
public boolean isFulltextSearchDisabled() { return (isFulltextDisabled() || fulltextConfiguration.fulltextSearchDisabled); }

Target:
Remove extra parentheses.
Source:
public DocumentModel updateUserInfo(DocumentModel user, OpenIDUserInfo userInfo) { try { UserManager userManager = Framework.getService(UserManager.class); user.setPropertyValue(userManager.getUserEmailField(), userInfo.getEmail()); Framework.doPrivileged(() -> { userManager.updateUser(user); }); } catch (NuxeoException e) { log.error("Error while search user in UserManager using email " + userInfo.getEmail(), e); return null; } return user; }

Target:
You can remove braces.
Source:
private ScheduleImpl buildTestSchedule() { ScheduleImpl schedule = new ScheduleImpl(); schedule.id = "testing"; schedule.username = "Administrator"; schedule.eventId = "testEvent"; schedule.eventCategory = "default"; return schedule; }

Target:
`private` -> `protected`
Source:
public List<Document> getProxies(Document doc) { State state = transaction.getStateForRead(doc.getUUID()); Object[] proxyIds = (Object[]) state.get(KEY_PROXY_IDS); if (proxyIds != null) { List<String> ids = Arrays.stream(proxyIds).map(Object::toString).collect(Collectors.toList()); return getDocuments(ids); } return Collections.emptyList(); }

Target:
Maybe `map(String::valueOf)` to make sur we never NPE on this?
Source:
private List<Node> getNodes(List<Serializable> ids) { List<Node> nodes = new LinkedList<>(); for (Serializable id : ids) { Node node = getNodeById(id); if (node != null || Boolean.TRUE.booleanValue()) { // XXX // null if deleted, which means selection wasn't correctly // updated nodes.add(node); } } return nodes; }

Target:
`protected`
Source:
public <D, M> M toAvro(Schema schema, D input) { return ((AvroMapper<D, M>) getMapper(input.getClass())).toAvro(schema, input); }

Target:
What about making `getMapper` generic and move the cast into it ?
Source:
public void testSchemaRetrieval() throws IOException { InputStream stream = getClass().getClassLoader().getResourceAsStream("data/avro-schema-example.json"); Schema schema = new Schema.Parser().parse(stream); long fingerprint = SchemaNormalization.parsingFingerprint64(schema); Schema retrieved = service.findByFingerprint(fingerprint); assertEquals(schema, retrieved); }

Target:
Close the stream.
Source:
public void start(ComponentContext context) { if (Framework.isTestModeSet()) { // when testing, DatabaseHelper init hasn't occurred yet, // so keep to lazy initialization return; } // open all directories at application startup, so that // their tables are created (outside a transaction) if needed for (Directory dir : getDirectories()) { // open directory to init its resources (tables for SQLDirectory) try { dir.getSession().close(); } catch (Exception e) { log.error(String.format("Could not open session for directory %s. Error message: %s", dir.getName(), e.getMessage())); } } // commit the transaction so that tables are committed if (TransactionHelper.isTransactionActiveOrMarkedRollback()) { TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); } }

Target:
Could you remove Error message from log message and give to logger the exception ?
Source:
protected boolean hasPermission(String nxuser) { NuxeoPrincipal principal = ((NuxeoPrincipal) getContext().getCoreSession().getPrincipal()); return principal.isAdministrator() || (nxuser == null ? false : principal.getName().equals(nxuser)); }

Target:
Can you change by `nxuser.equals(principal.getName())`, as we know `nxuser` is not `null`.
Source:
public Response getClientToken(@PathParam("clientId") String clientId, @PathParam("nxuser") String nxuser, @Context HttpServletRequest request) { checkPermission(nxuser); OAuth2Client client = Framework.getService(OAuth2ClientService.class).getClient(clientId); return Response.ok(getToken(client, nxuser)).build(); }

Target:
WDYT about returning a `404` for a non-existing client as it's done for providers? If that happens, we will end up with a `5xx` but that's not a server issue at all.
Source:
public void testService() { CodecService service = Framework.getService(CodecService.class); assertNotNull(service); }

Target:
Please use `@Inject` nevertheless, it's declarative and allows to see all services used at the top of the test class.
Source:
public T decode(byte[] data) { // TODO: check if it worth to switch to commons-lang3 SerializationUtils ByteArrayInputStream bis = new ByteArrayInputStream(data); ObjectInput in = null; try { in = new ObjectInputStream(bis); return (T) in.readObject(); } catch (IOException | ClassNotFoundException e) { throw new IllegalArgumentException(e); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { // ignore close exception } } }

Target:
I guess all this (and the finally/close) can be simplified with try-with-resources.
Source:
private void visitExpressionIsTrashedOnLifeCycle(Expression node) { String name = ((Reference) node.lvalue).name; boolean bool = getBooleanRValue(name, node); Operator op = bool ? Operator.EQ : Operator.NOTEQ; visitReference(new Reference(NXQL.ECM_LIFECYCLESTATE)); visitOperator(op); visitStringLiteral(LifeCycleConstants.DELETED_STATE); }

Target:
`private` -> `protected`
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; return watermark == record.watermark && Objects.equals(flags, record.flags) && Objects.equals(key, record.key) && Arrays.equals(data, record.data); }

Target:
Always use `{` and `}` for `if` statements.
Source:
private URL toURL(Path p) { try { return p.toUri().toURL(); } catch (MalformedURLException e) { throw new IllegalStateException(e); } }

Target:
`private` -> `protected`
Source:
public void deployContrib(String name, String contrib) throws Exception { RuntimeContext context = runtime.getContext(name); if (context == null) { context = runtime.getContext(); BundleFile file = lookupBundle(name); URL location = file.getEntry(contrib); if (location == null) { throw new AssertionError("Cannot locate " + contrib + " in " + name); } context.deploy(location); return; } context.deploy(contrib); }

Target:
Could add an `INFO` log to tell the bundle wasn't install ?
Source:
public Map<String, Serializable> getParameters(String key) { StorageEntry entry = getStorageEntry(key); if (entry == null) { return null; } Map<String, Serializable> res = new LinkedHashMap<>(entry.getParams()); if (log.isDebugEnabled()) { log.debug(String.format("Fetched parameters from StorageEntry stored at key %s: %s", key, res)); } return res; }

Target:
Don't add extra empty lines.
Source:
@Override public void deactivate(ComponentContext context) { handlers = null; super.deactivate(context); }

Target:
Remove extra empty line
Source:
@Override public void unregisterContribution(Object contribution, String extensionPoint, ComponentInstance contributor) { if (EP_BATCH_HANDLER.equalsIgnoreCase(extensionPoint)) { if (BatchHandlerDescriptor.class.isAssignableFrom(contribution.getClass())) { BatchHandlerDescriptor contributionDescriptor = (BatchHandlerDescriptor) contribution; handlers.remove(contributionDescriptor.getName()); } } }

Target:
`else` throw an error about invalid class.
Source:
public void iCanBulkDownloadASingleFile() throws IOException, OperationException, InterruptedException { System.setProperty(RandomBug.MODE_PROPERTY, RandomBug.Mode.STRICT.toString()); testWithNbFiles(1); }

Target:
I don't think you need that anymore (or the import), do you?
Source:
protected DocumentModelList applyQueryLimits(DocumentModelList results, int limit, int offset) { int safeOffset = Math.max(0, offset); int toIndex = limit >= 1 ? Math.min(results.size(), safeOffset + limit) : results.size(); return new DocumentModelListImpl(results.subList(safeOffset, toIndex)); }

Target:
You can reassign to `offset`, we don't forbid assignment to method parameters and in this case it's more readable.
Source:
public void shouldNotHaveTheRemoteCause() { try { // get a wrong doc Document wrongDoc = (Document) session.newRequest(FetchDocument.ID).set("value", "/test").execute(); fail("Unexpected " + wrongDoc); } catch (RemoteException e) { assertNotNull(e); assertNull(e.getRemoteCause()); } catch (Exception e) { fail(); } }

Target:
You can remove the `catch (Exception e) { fail(); }`, it'll give a clearer error when failing.
Source:
public void stop(ComponentContext context) throws InterruptedException { setFailure(); }

Target:
`throws InterruptedException` not needed
Source:
public static <T> T operation(String operationId, Map<String, Object> parameters) { return CLIENT.operation(operationId).parameters(parameters).execute(); }

Target:
Same here, this method return void because we don't want to have nuxeo-java-client outside this class.
Source:
public DocumentModelList run(DocumentModelList docs) { return docs.stream().map(doc -> { return run(doc); }).collect(Collectors.toCollection(DocumentModelListImpl::new)); }

Target:
`.map(doc -> run(doc))`
Source:
public String processText(InputStream in) throws IOException { String text = IOUtils.toString(in, StandardCharsets.UTF_8); return processText(text); }

Target:
You can `import static` `StandardCharsets.UTF_8` for more concise code.
Source:
public String getPartitionKey() { if (docId != null) { return docId; } else if (docIds != null && docIds.size() > 0) { return docIds.get(0); } return getId(); }

Target:
`docIds.size() > 0` -> `!docIds.isEmpty()`
Source:
public static <O> ScrollResult<O> emptyResult() { return EMPTY_RESULT; }

Target:
`return (<O>) EMPTY_RESULT;` I guess
Source:
public void initSequence(String key, long id) { while ((getNextLong(key)) < id) { continue; } }

Target:
As you edited this line, could you remove extra parenthesis too please ?
Source:
public static boolean isValid(InputStream stream) { try { ZipInputStream zip = new ZipInputStream(stream); ZipEntry entry = zip.getNextEntry(); return entry != null; } catch (IOException e) { return false; } }

Target:
Please close the input stream after having used it (maybe using the try-with-resources statement) ```java try (ZipInputStream zip = new ZipInputStream(stream)) { ... } ```
Source:
public void invalidate() { this.targetDomainName = null; }

Target:
`this.` is not needed. Also make the `targetDomainName` field `volatile` because it's checked and modified and invalidated from different threads.
Source:
public void shouldFailedIfToTypeNotMatch() throws Exception { operation.value = Boolean.FALSE; try { operation.xpath = "lists:integer"; operation.run(doc); fail(); } catch (OperationException | UnsupportedOperationException e) { assertEquals("Given type \"false\" value is not a long type", e.getMessage()); } catch (Exception e) { fail(); } }

Target:
It know it's part of the original code but it's better to clean it up. Remove these two lines, just let the Exception be thrown, it'll give clearer test error messages if there's a failure.
Source:
public CompositeCommand combine(CompositeCommand cc) { cc.commands.forEach(commands::add); return this; }

Target:
missing since
Source:
protected static String getStackTraceString(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.close(); return sw.toString(); }

Target:
Use a try-catch block to handle closable resources.
Source:
public String getFirstIndexForAlias(String aliasName) { ImmutableOpenMap<String, List<AliasMetaData>> aliases = aliases = client.admin().indices().prepareGetAliases(aliasName).get().getAliases(); if (aliases.isEmpty()) { return null; } return aliases.keysIt().next(); }

Target:
Fix `aliases = aliases = ...`
Source:
public String getNextIndexName(String aliasName, String oldIndexName) { if (oldIndexName == null || oldIndexName.isEmpty()) { return aliasName + SEP + "0000"; } int i = oldIndexName.lastIndexOf(SEP); if (i < 0) { throw new IllegalArgumentException("Invalid index name: " + oldIndexName); } int index = Integer.parseInt(oldIndexName.substring(i + 1)) + 1; return String.format("%s%s%04d", aliasName, SEP, index); }

Target:
Why check `isEmpty()`? I guess empty index names have been eliminated before getting here.
Source:
public void registerCache(String name, int maxSize, int timeout) { registerCache(name, maxSize, timeout, new CacheDescriptor()); }

Target:
Why not retrieving the default descriptor ?
Source:
static public Record of(String key, byte[] data) { return new Record(key, data, 0, DEFAULT_FLAG); }

Target:
Correct keyword order
Source:
static public boolean exists(File basePath) { //noinspection ConstantConditions return basePath.isDirectory() && basePath.list().length > 0; }

Target:
Correct keyword order
Source:
static public <M extends Externalizable> KafkaLogAppender<M> open(String topic, String name, Properties producerProperties, Properties consumerProperties) { return new KafkaLogAppender<>(topic, name, producerProperties, consumerProperties); }

Target:
Correct keyword order
Source:
protected void closeTailer() { if (tailer != null && !tailer.closed()) { try { tailer.close(); } catch (Exception e) { log.debug(metadata.name() + ": Exception while closing tailer", e); } } }

Target:
Don't catch `Exception`, use something more specific.
Source:
public boolean stop(Duration timeout) { log.debug("Stopping ..."); if (pools == null) { return true; } long failures = pools.parallelStream().filter(comp -> !comp.stop(timeout)).count(); log.debug(String.format("Stopped %d failure", failures)); return failures == 0L; }

Target:
No need for `0L`, `0` is enough.
Source:
public RebalanceException(String message) { super(message); }

Target:
If you never need the stack trace, consider calling `super(message, null, false, false)` to avoid some overhead.
Source:
public static boolean exists(File basePath) { //noinspection ConstantConditions return basePath.isDirectory() && basePath.list().length > 0; }

Target:
Should probably be `protected`, not `public`.
Source:
protected int findQueueIndex(File queueFile) { String queueDirName = queueFile.getParentFile().getName(); return Integer.valueOf(queueDirName.substring(queueDirName.length() - 2)); }

Target:
`Integer.parseInt`
Source:
public List<String> listTopics() { Seq<String> topics = zkUtils.getAllTopics(); return scala.collection.JavaConversions.seqAsJavaList(topics); }

Target:
`scala.collection.JavaConversions` -> `JavaConversions`
Source:
public void work() { System.out.println("Work start"); FileEvent.onFile(this, file, this).send(); SequenceTracer.mark("send event"); System.out.println("Work done"); }

Target:
Remove `System.out.println`
Source:
public void transientFilesWorkAreCleaned() throws Exception { final File file = feature.resolveAndCreate(new File("pfouh")); Thread.sleep(100); service.schedule(new CreateFile(file)); service.awaitCompletion(5, TimeUnit.SECONDS); }

Target:
Is this needed?
Source:
public TransientStore getTransientStore() { TransientStoreService tss = Framework.getService(TransientStoreService.class); return tss.getStore(StringUtils.isNotBlank(this.storeName) ? storeName : CACHE_NAME); }

Target:
Don't use `isNotBlank` as this doesn't come from user input or config file. Just use `storeName != null`