auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static boolean isTestModeSet() { String testModeCacheDisabled = System.getProperty(NUXEO_TESTING_PROP_CACHE_DISABLED); START if (Boolean.FALSE.equals(Boolean.parseBoolean(testModeCacheDisabled))) { END if (testModeSet == null) { testModeSet = isBooleanPropertyTrue(NUXEO_TESTING_SYSTEM_PROP); } return testModeSet; } return isBooleanPropertyTrue(NUXEO_TESTING_SYSTEM_PROP); } Note that `parseBoolean` returns a `boolean`, not a `Boolean`. But you can use `Boolean.getBoolean(syspropname)` instead of `System.getProperty` + `Boolean.parseBoolean`

Target:
public static boolean isTestModeSet() { return isBooleanPropertyTrue(NUXEO_TESTING_SYSTEM_PROP); }
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); START } catch (RuntimeException e) { END log.warn("unable to read log entry", e); } } } return entries; } Which exception has been observed here? Please don't catch exceptions when we don't actually know what they are.

Target:
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) { doPublish((LogEntry) logEntry); } } return entries; }
Source:
public CommentSecurityException() { START super(); END this.statusCode = SC_FORBIDDEN; } `super(SC_FORBIDDEN)` and similarly for other constructors

Target:
public CommentSecurityException() { super(SC_FORBIDDEN); }
Source:
protected boolean overlapInstant(Instant aStart, Instant aEnd, Instant bStart, Instant bEnd) { START return (aStart.isBefore(bEnd) && bStart.isBefore(aEnd)); END } Remove extra parentheses

Target:
protected boolean overlapInstant(Instant aStart, Instant aEnd, Instant bStart, Instant bEnd) { return aStart.isBefore(bEnd) && bStart.isBefore(aEnd); }
Source:
START private TransientStore getTransientStore() { END return Framework.getService(TransientStoreService.class).getStore(STATUS_STORE_NAME); } all private methods should be protected

Target:
protected TransientStore getTransientStore() { return Framework.getService(TransientStoreService.class).getStore(STATUS_STORE_NAME); }
Source:
protected DocumentModel attach(DocumentModel doc) { String sid = ctx.getCoreSession().getSessionId(); try { START doc = doc.clone(); END } catch (CloneNotSupportedException e) { // doc models not supporting clone do not rely on session id anyway } doc.attach(sid); return doc; } Why clone the doc?

Target:
protected void attach(DocumentModel doc) { String sid = ctx.getCoreSession().getSessionId(); doc.attach(sid); }
Source:
public boolean hasCompatibleMimeType(List<String> mimeTypes, String mimeType) { String mt = parseMimeType(mimeType); Set<String> expectedMimeTypes = new HashSet<>(); expectedMimeTypes.add(ANY_MIME_TYPE); START if (mimeType != null) { END expectedMimeTypes.add(mt); expectedMimeTypes.add(computeMimeTypeWithWildcardSubType(mt)); } return mimeTypes.stream().anyMatch(expectedMimeTypes::contains); } Shouldn't be `mt != null` for consistency ?

Target:
public boolean hasCompatibleMimeType(List<String> mimeTypes, String mimeType) { String mt = parseMimeType(mimeType); Set<String> expectedMimeTypes = new HashSet<>(); expectedMimeTypes.add(ANY_MIME_TYPE); if (mt != null) { expectedMimeTypes.add(mt); expectedMimeTypes.add(computeMimeTypeWithWildcardSubType(mt)); } return mimeTypes.stream().anyMatch(expectedMimeTypes::contains); }
Source:
START public void setPolicy(ComputationPolicy policy) { END this.policy = policy; } Shouldn't be protected as this method is used only in tests + shouldn't be something editable no ?

Target:
protected void setPolicy(ComputationPolicy policy) { this.policy = policy; }
Source:
protected static Blob readStringBlob(String ctype, String fileName, String content) throws IOException { Blob blob = new StringBlob(fileName, content, ctype); START return blob; END } Can be on one line and doesn't need to throw `IOException`.

Target:
protected static Blob readStringBlob(String ctype, String fileName, String content) { return new StringBlob(fileName, content, ctype); }
Source:
public void start(ComponentContext context) { super.start(context); Collection<MongoDBConnectionConfig> confs = getDescriptors(XP_CONNECTION); confs.forEach(c -> { START log.debug("Initializing MongoClient with id={}", c.getId()); END clients.put(c.getId(), MongoDBConnectionHelper.newMongoClient(c.server)); }); } `c::getId`

Target:
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)); }); }
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 -> { START log.debug("Closing MongoClient with id={}", e.getKey()); END e.getValue().close(); }); clients.clear(); } `e::getKey`

Target:
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(); }
Source:
public DataBucket(String commandId, long count, byte[] data) { START this(commandId, count, data, new byte[]{}, new byte[]{}); END } `new byte[]{}` -> `new byte[0]`

Target:
public DataBucket(String commandId, long count, byte[] data) { this(commandId, count, data, new byte[0], 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))); START if (!COMMENT_DOC_TYPE.equals(parent.getType())) { END return comment; } return getThreadForComment(parent); } Can you reverse condition ? just for clarity.

Target:
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 getThreadForComment(parent); } return comment; }
Source:
protected boolean isImporterAvailable(FileImporter importer, String normalizedMimeType, String mimeType, boolean excludeOneToMany) { START return importer.isEnabled() && (!excludeOneToMany || !importer.isOneToMany()) END && (importer.matches(normalizedMimeType) || importer.matches(mimeType)); } Personally I read this better with `&& !(importer.isOneToMany() && excludeOneToMany)` but up to you.

Target:
protected boolean isImporterAvailable(FileImporter importer, String normalizedMimeType, String mimeType, boolean excludeOneToMany) { return importer.isEnabled() && !(importer.isOneToMany() && excludeOneToMany) && (importer.matches(normalizedMimeType) || importer.matches(mimeType)); }
Source:
public boolean register(String target, String xp, Descriptor descriptor) { START log.trace("Register to {}/{}", descriptor.getId(), target, xp); END return descriptors.computeIfAbsent(target, k -> new HashMap<>()) .computeIfAbsent(xp, k -> new LinkedHashMap<>()) .computeIfAbsent(descriptor.getId(), k -> new ArrayList<>()) .add(descriptor); } 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.

Target:
public boolean register(String target, String xp, Descriptor descriptor) { log.debug("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); }
Source:
START String getKey(String commandId) { END return metadata.name() + commandId; } Missing `protected` keyword ?

Target:
protected String getKey(String commandId) { return metadata.name() + commandId; }
Source:
START protected static Long getLastOffset(String workId) { END String stringOffset = getKeyValueStore().getString(getOffsetKey(workId)); return stringOffset == null ? Long.valueOf(-1) : Long.parseLong(stringOffset); } or long ?

Target:
protected static long getLastOffset(String workId) { String stringOffset = getKeyValueStore().getString(getOffsetKey(workId)); return stringOffset == null ? -1 : Long.parseLong(stringOffset); }
Source:
protected void checkpointIfNecessary() { if (context.requireCheckpoint()) { boolean completed = false; try { checkpoint(); completed = true; inCheckpointRecords = inRecords; } catch (Exception e) { START log.error(e, e); END } finally { if (!completed) { log.error(metadata.name() + ": CHECKPOINT FAILURE: Resume may create duplicates."); } } } } Is this intended ? It could hide problems as the current runner won't be stopped.

Target:
protected void checkpointIfNecessary() { if (context.requireCheckpoint()) { boolean completed = false; try { checkpoint(); completed = true; inCheckpointRecords = inRecords; } finally { if (!completed) { log.error(metadata.name() + ": CHECKPOINT FAILURE: Resume may create duplicates."); } } } }
Source:
public static int partitions(Path basePath) { Path metadataPath = basePath.resolve(METADATA_FILE); if (metadataPath.toFile().exists()) { START return Integer.valueOf(readMetadata(metadataPath).getProperty(PARTITIONS_KEY)); END } // backward compatibility before metadata file return discoverPartitions(basePath); } `valueOf` -> `parseInt`

Target:
public static int partitions(Path basePath) { Path metadataPath = basePath.resolve(METADATA_FILE); if (metadataPath.toFile().exists()) { return Integer.parseInt(readMetadata(metadataPath).getProperty(PARTITIONS_KEY)); } // backward compatibility before metadata file return discoverPartitions(basePath); }
Source:
public List<DocumentModel> getComments(CoreSession session, DocumentModel docModel) { PageProviderService ppService = Framework.getService(PageProviderService.class); Map<String, Serializable> props = Collections.singletonMap( START CoreQueryAndFetchPageProvider.CORE_SESSION_PROPERTY, (Serializable) session); END 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(); } `CORE_SESSION_PROPERTY` as static import.

Target:
public List<DocumentModel> getComments(CoreSession session, DocumentModel docModel) { PageProviderService ppService = Framework.getService(PageProviderService.class); Map<String, Serializable> props = Collections.singletonMap(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(); }
Source:
protected DocumentModel createNuxeoUser(String nuxeoLogin) { DocumentModel userDoc; try { userDoc = Framework.doPrivileged(() -> { UserManager userManager = Framework.getService(UserManager.class); DocumentModel user = userManager.getBareUserModel(); START user.setPropertyValue(userManager.getUserIdField(), nuxeoLogin); END return userManager.createUser(user); }); } catch (NuxeoException e) { log.error("Error while creating user " + nuxeoLogin + "in UserManager", e); return null; } return userDoc; } 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.

Target:
protected DocumentModel createNuxeoUser(String nuxeoLogin) { DocumentModel userDoc; UserManager userManager = Framework.getService(UserManager.class); DocumentModel user = userManager.getBareUserModel(); user.setPropertyValue(userManager.getUserIdField(), nuxeoLogin); try { userDoc = Framework.doPrivileged(() -> { return userManager.createUser(user); }); } catch (NuxeoException e) { log.error("Error while creating user " + nuxeoLogin + "in UserManager", e); return null; } return userDoc; }
Source:
protected void assertValues(TestDescriptor d, String id, String name, String desc) { START Assert.assertEquals(id, d.id); END Assert.assertEquals(name, d.name); Assert.assertEquals(desc, d.desc); } `import static` all `Assert` static methods.

Target:
protected void assertValues(TestDescriptor d, String id, String name, String desc) { assertEquals(id, d.id); assertEquals(name, d.name); assertEquals(desc, d.desc); }
Source:
public RestBinding[] getBindings() { List<RestBinding> descriptors = getDescriptors(XP_BINDINGS); START return descriptors.toArray(new RestBinding[descriptors.size()]); END } Give 0 as size to the new array, it's faster in java.

Target:
public RestBinding[] getBindings() { List<RestBinding> descriptors = getDescriptors(XP_BINDINGS); return descriptors.toArray(new RestBinding[0]); }
Source:
public void stop(ComponentContext context) throws InterruptedException { START super.stop(context); END // interrupt all migration tasks executor.shutdownNow(); executor.awaitTermination(10, TimeUnit.SECONDS); // wait 10s for termination executor = null; } In general you should call `super.stop` last, after all other cleanups.

Target:
public void stop(ComponentContext context) throws InterruptedException { // interrupt all migration tasks executor.shutdownNow(); executor.awaitTermination(10, TimeUnit.SECONDS); // wait 10s for termination executor = null; super.stop(context); }
Source:
public void deactivate(ComponentContext context) { START super.deactivate(context); END subscribers.clear(); provider.close(); provider = null; } Same for `super.deactivate`, you should call it last.

Target:
public void deactivate(ComponentContext context) { subscribers.clear(); provider.close(); provider = null; super.deactivate(context); }
Source:
protected void ensureUserListIsUsed() { START users = users == null ? new ArrayList<>() : new ArrayList<>(users); END 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)); } } 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.

Target:
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(computeTransientUsername(email)); } }
Source:
public void processTimer(ComputationContext context, String key, long timestamp) { if (!TIMER_BATCH.equals(key) || batchRecords.isEmpty()) { START return; END } processBatch(context); context.setTimer(TIMER_BATCH, System.currentTimeMillis() + thresholdMillis); } Don't we need to set timer back if `batchRecords` is empty ?

Target:
public void processTimer(ComputationContext context, String key, long timestamp) { if (!TIMER_BATCH.equals(key)) { return; } if (! batchRecords.isEmpty()) { processBatch(context); } context.setTimer(TIMER_BATCH, System.currentTimeMillis() + thresholdMillis); }
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()); START System.out.println(config); END embeddedNode = new ElasticSearchEmbeddedNode(config); embeddedNode.start(); } Maybe use a logger ?

Target:
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()); embeddedNode = new ElasticSearchEmbeddedNode(config); embeddedNode.start(); }
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(); START if (aliases.get(indexName).isEmpty()) { END continue; } return indexName; } return null; } What about using stream api and directly have a return from the first line?

Target:
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()) { return indexName; } } return null; }
Source:
public BulkServiceImpl(BulkServiceDescriptor descriptor) { this.descriptor = descriptor; kvStore = Framework.getService(KeyValueService.class).getKeyValueStore(descriptor.kvStore); START logManager = Framework.getService(StreamService.class).getLogManager(descriptor.logConfig); END } 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.

Target:
public BulkServiceImpl(BulkServiceDescriptor descriptor) { this.descriptor = descriptor; }
Source:
protected void recomputeClassFilters() { START Set<String> classNames = new HashSet<>(); END 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); } 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.

Target:
protected void recomputeClassFilters() { Set<String> allowedClassNames = new HashSet<>(); for (ClassFilterDescriptor desc : classFilterDescriptors) { if (desc.deny.contains("*")) { allowedClassNames.clear(); allowedClassNames.addAll(desc.allow); } else { allowedClassNames.addAll(desc.allow); allowedClassNames.removeAll(desc.deny); } } // we don't care about update atomicity, as nothing executes concurrently with XML config service.allowedClassNames.clear(); service.allowedClassNames.addAll(allowedClassNames); }
Source:
private static void assertDocumentPropertiesChanges(DocumentModel doc, Map<String, Object> originalProperties, Set<String> expectedChangedPropertyNames) { START originalProperties.keySet().forEach(property -> { END Object currentValue = doc.getProperty("dublincore", property); if (expectedChangedPropertyNames.contains(property)) { assertNotEquals(originalProperties.get(property), currentValue); } else { assertEquals(currentValue, originalProperties.get(property)); } }); } Here you can use `forEach` directly on the map.

Target:
protected static void assertDocumentPropertiesChanges(DocumentModel doc, Map<String, Object> originalProperties, Set<String> expectedChangedPropertyNames) { originalProperties.forEach((key, value) -> { Object currentValue = doc.getProperty("dublincore", key); if (expectedChangedPropertyNames.contains(key)) { assertNotEquals(value, currentValue); } else { assertEquals(currentValue, value); } }); }
Source:
public boolean isFulltextSearchDisabled() { START return (isFulltextDisabled() || fulltextConfiguration.fulltextSearchDisabled); END } Remove extra parentheses.

Target:
public boolean isFulltextSearchDisabled() { return isFulltextDisabled() || fulltextConfiguration.fulltextSearchDisabled; }
Source:
public DocumentModel updateUserInfo(DocumentModel user, OpenIDUserInfo userInfo) { try { UserManager userManager = Framework.getService(UserManager.class); user.setPropertyValue(userManager.getUserEmailField(), userInfo.getEmail()); START Framework.doPrivileged(() -> { END userManager.updateUser(user); }); } catch (NuxeoException e) { log.error("Error while search user in UserManager using email " + userInfo.getEmail(), e); return null; } return user; } You can remove braces.

Target:
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; }
Source:
START private ScheduleImpl buildTestSchedule() { END ScheduleImpl schedule = new ScheduleImpl(); schedule.id = "testing"; schedule.username = "Administrator"; schedule.eventId = "testEvent"; schedule.eventCategory = "default"; return schedule; } `private` -> `protected`

Target:
protected ScheduleImpl buildTestSchedule() { ScheduleImpl schedule = new ScheduleImpl(); schedule.id = "testing"; schedule.username = "Administrator"; schedule.eventId = "testEvent"; schedule.eventCategory = "default"; return schedule; }
Source:
public List<Document> getProxies(Document doc) { State state = transaction.getStateForRead(doc.getUUID()); Object[] proxyIds = (Object[]) state.get(KEY_PROXY_IDS); if (proxyIds != null) { START List<String> ids = Arrays.stream(proxyIds).map(Object::toString).collect(Collectors.toList()); END return getDocuments(ids); } return Collections.emptyList(); } Maybe `map(String::valueOf)` to make sur we never NPE on this?

Target:
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(String::valueOf).collect(Collectors.toList()); return getDocuments(ids); } return Collections.emptyList(); }
Source:
START private List<Node> getNodes(List<Serializable> ids) { END 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; } `protected`

Target:
protected 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; }
Source:
public <D, M> M toAvro(Schema schema, D input) { START return ((AvroMapper<D, M>) getMapper(input.getClass())).toAvro(schema, input); END } What about making `getMapper` generic and move the cast into it ?

Target:
public <D, M> M toAvro(Schema schema, D input) { return (M) getMapper((Class<D>) input.getClass()).toAvro(schema, input); }
Source:
public void testSchemaRetrieval() throws IOException { START InputStream stream = getClass().getClassLoader().getResourceAsStream("data/avro-schema-example.json"); END Schema schema = new Schema.Parser().parse(stream); long fingerprint = SchemaNormalization.parsingFingerprint64(schema); Schema retrieved = service.findByFingerprint(fingerprint); assertEquals(schema, retrieved); } Close the stream.

Target:
public void testSchemaRetrieval() throws IOException { try (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); } }
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) { START log.error(String.format("Could not open session for directory %s. Error message: %s", dir.getName(), END e.getMessage())); } } // commit the transaction so that tables are committed if (TransactionHelper.isTransactionActiveOrMarkedRollback()) { TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); } } Could you remove Error message from log message and give to logger the exception ?

Target:
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(e); } } // commit the transaction so that tables are committed if (TransactionHelper.isTransactionActiveOrMarkedRollback()) { TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); } }
Source:
protected boolean hasPermission(String nxuser) { NuxeoPrincipal principal = ((NuxeoPrincipal) getContext().getCoreSession().getPrincipal()); START return principal.isAdministrator() || (nxuser == null ? false : principal.getName().equals(nxuser)); END } Can you change by `nxuser.equals(principal.getName())`, as we know `nxuser` is not `null`.

Target:
protected boolean hasPermission(String nxuser) { NuxeoPrincipal principal = ((NuxeoPrincipal) getContext().getCoreSession().getPrincipal()); return principal.isAdministrator() || (nxuser == null ? false : nxuser.equals(principal.getName())); }
Source:
public Response getClientToken(@PathParam("clientId") String clientId, @PathParam("nxuser") String nxuser, @Context HttpServletRequest request) { checkPermission(nxuser); START OAuth2Client client = Framework.getService(OAuth2ClientService.class).getClient(clientId); END return Response.ok(getToken(client, nxuser)).build(); } 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.

Target:
public Response getClientToken(@PathParam("clientId") String clientId, @PathParam("nxuser") String nxuser, @Context HttpServletRequest request) { checkPermission(nxuser); OAuth2Client client = getClient(clientId); return Response.ok(getToken(client, nxuser)).build(); }
Source:
public void testService() { START CodecService service = Framework.getService(CodecService.class); END assertNotNull(service); } Please use `@Inject` nevertheless, it's declarative and allows to see all services used at the top of the test class.

Target:
public void testService() { assertNotNull(service); }
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); START } finally { END try { if (in != null) { in.close(); } } catch (IOException ex) { // ignore close exception } } } I guess all this (and the finally/close) can be simplified with try-with-resources.

Target:
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(); } bis.close(); } catch (IOException ex) { // we want to ignore close exception so no try-with-resources squid:S2093 } } }
Source:
START private void visitExpressionIsTrashedOnLifeCycle(Expression node) { END 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); } `private` -> `protected`

Target:
protected 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); }
Source:
public boolean equals(Object o) { if (this == o) START return true; END 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); } Always use `{` and `}` for `if` statements.

Target:
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); }
Source:
START private URL toURL(Path p) { END try { return p.toUri().toURL(); } catch (MalformedURLException e) { throw new IllegalStateException(e); } } `private` -> `protected`

Target:
protected URL toURL(Path p) { try { return p.toUri().toURL(); } catch (MalformedURLException e) { throw new IllegalStateException(e); } }
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); START URL location = file.getEntry(contrib); END if (location == null) { throw new AssertionError("Cannot locate " + contrib + " in " + name); } context.deploy(location); return; } context.deploy(contrib); } Could add an `INFO` log to tell the bundle wasn't install ?

Target:
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); } else { context.deploy(contrib); } }
Source:
public Map<String, Serializable> getParameters(String key) { StorageEntry entry = getStorageEntry(key); if (entry == null) { return null; } START END 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; } Don't add extra empty lines.

Target:
public Map<String, Serializable> getParameters(String key) { StorageEntry entry = getStorageEntry(key); if (entry == null) { return null; } Map<String, Serializable> res = new HashMap<>(entry.getParams()); if (log.isDebugEnabled()) { log.debug(String.format("Fetched parameters from StorageEntry stored at key %s: %s", key, res)); } return res; }
Source:
@Override public void deactivate(ComponentContext context) { START handlers = null; END super.deactivate(context); } Remove extra empty line

Target:
public void deactivate(ComponentContext context) { handlers = null; super.deactivate(context); }
Source:
@Override public void unregisterContribution(Object contribution, String extensionPoint, ComponentInstance contributor) { START if (EP_BATCH_HANDLER.equalsIgnoreCase(extensionPoint)) { END if (BatchHandlerDescriptor.class.isAssignableFrom(contribution.getClass())) { BatchHandlerDescriptor contributionDescriptor = (BatchHandlerDescriptor) contribution; handlers.remove(contributionDescriptor.getName()); } } } `else` throw an error about invalid class.

Target:
public void unregisterContribution(Object contribution, String extensionPoint, ComponentInstance contributor) { if (EP_BATCH_HANDLER.equals(extensionPoint)) { if (BatchHandlerDescriptor.class.isAssignableFrom(contribution.getClass())) { BatchHandlerDescriptor contributionDescriptor = (BatchHandlerDescriptor) contribution; String name = contributionDescriptor.getName(); handlers.remove(name); } } }
Source:
public void iCanBulkDownloadASingleFile() throws IOException, OperationException, InterruptedException { START System.setProperty(RandomBug.MODE_PROPERTY, RandomBug.Mode.STRICT.toString()); END testWithNbFiles(1); } I don't think you need that anymore (or the import), do you?

Target:
public void iCanBulkDownloadASingleFile() throws IOException, OperationException, InterruptedException { testWithNbFiles(1); }
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(); START return new DocumentModelListImpl(results.subList(safeOffset, toIndex)); END } You can reassign to `offset`, we don't forbid assignment to method parameters and in this case it's more readable.

Target:
protected DocumentModelList applyQueryLimits(DocumentModelList results, int limit, int offset) { offset = Math.max(0, offset); int toIndex = limit >= 1 ? Math.min(results.size(), offset + limit) : results.size(); return new DocumentModelListImpl(results.subList(offset, toIndex)); }
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) { START fail(); END } } You can remove the `catch (Exception e) { fail(); }`, it'll give a clearer error when failing.

Target:
public void shouldNotHaveTheRemoteCause() throws IOException { 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()); } }
Source:
START public void stop(ComponentContext context) throws InterruptedException { END setFailure(); } `throws InterruptedException` not needed

Target:
public void stop(ComponentContext context) { setFailure(); }
Source:
START public static <T> T operation(String operationId, Map<String, Object> parameters) { END return CLIENT.operation(operationId).parameters(parameters).execute(); } Same here, this method return void because we don't want to have nuxeo-java-client outside this class.

Target:
public static void operation(String operationId, Map<String, Object> parameters) { CLIENT.operation(operationId).parameters(parameters).execute(); }
Source:
public DocumentModelList run(DocumentModelList docs) { return docs.stream().map(doc -> { START return run(doc); END }).collect(Collectors.toCollection(DocumentModelListImpl::new)); } `.map(doc -> run(doc))`

Target:
public DocumentModelList run(DocumentModelList docs) { return docs.stream().map(doc -> run(doc)).collect(Collectors.toCollection(DocumentModelListImpl::new)); }
Source:
public String processText(InputStream in) throws IOException { START String text = IOUtils.toString(in, StandardCharsets.UTF_8); END return processText(text); } You can `import static` `StandardCharsets.UTF_8` for more concise code.

Target:
public String processText(InputStream in) throws IOException { String text = IOUtils.toString(in, UTF_8); return processText(text); }
Source:
public String getPartitionKey() { if (docId != null) { return docId; START } else if (docIds != null && docIds.size() > 0) { END return docIds.get(0); } return getId(); } `docIds.size() > 0` -> `!docIds.isEmpty()`

Target:
public String getPartitionKey() { if (docId != null) { return docId; } else if (docIds != null && !docIds.isEmpty()) { return docIds.get(0); } return getId(); }
Source:
public static <O> ScrollResult<O> emptyResult() { START return EMPTY_RESULT; END } `return (<O>) EMPTY_RESULT;` I guess

Target:
public static <O> ScrollResult<O> emptyResult() { return (ScrollResult<O>) EMPTY_RESULT; }
Source:
public void initSequence(String key, long id) { START while ((getNextLong(key)) < id) { END continue; } } As you edited this line, could you remove extra parenthesis too please ?

Target:
public void initSequence(String key, long id) { while (getNextLong(key) < id) { continue; } }
Source:
public static boolean isValid(InputStream stream) { try { ZipInputStream zip = new ZipInputStream(stream); START ZipEntry entry = zip.getNextEntry(); END return entry != null; } catch (IOException e) { return false; } } Please close the input stream after having used it (maybe using the try-with-resources statement) ```java try (ZipInputStream zip = new ZipInputStream(stream)) { ... } ```

Target:
public static boolean isValid(InputStream stream) { try (ZipInputStream zip = new ZipInputStream(stream)) { return zip.getNextEntry() != null; } catch (IOException e) { return false; } }
Source:
public void invalidate() { START this.targetDomainName = null; END } `this.` is not needed. Also make the `targetDomainName` field `volatile` because it's checked and modified and invalidated from different threads.

Target:
public void invalidate() { targetDomainName = null; }
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) { START fail(); END } } 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.

Target:
public void shouldFailedIfToTypeNotMatch() throws Exception { operation.value = Boolean.FALSE; try { operation.xpath = "lists:integer"; operation.run(doc); fail(); } catch (Exception e) { assertEquals("Given type \"false\" value is not a long type", e.getMessage()); } }
Source:
public CompositeCommand combine(CompositeCommand cc) { cc.commands.forEach(commands::add); return this; START } END missing since

Target:
public CompositeCommand combine(CompositeCommand cc) { commands.addAll(cc.commands); return this; }
Source:
protected static String getStackTraceString(Throwable t) { StringWriter sw = new StringWriter(); START PrintWriter pw = new PrintWriter(sw); END t.printStackTrace(pw); pw.close(); return sw.toString(); } Use a try-catch block to handle closable resources.

Target:
protected static String getStackTraceString(Throwable t) throws IOException { try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) { t.printStackTrace(pw); return sw.toString(); } }
Source:
public String getFirstIndexForAlias(String aliasName) { START ImmutableOpenMap<String, List<AliasMetaData>> aliases = aliases = client.admin().indices().prepareGetAliases(aliasName).get().getAliases(); END if (aliases.isEmpty()) { return null; } return aliases.keysIt().next(); } Fix `aliases = aliases = ...`

Target:
public String getFirstIndexForAlias(String aliasName) { ImmutableOpenMap<String, List<AliasMetaData>> aliases = client.admin().indices().prepareGetAliases(aliasName).get().getAliases(); if (aliases.isEmpty()) { return null; } return aliases.keysIt().next(); }
Source:
public String getNextIndexName(String aliasName, String oldIndexName) { START if (oldIndexName == null || oldIndexName.isEmpty()) { END 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); } Why check `isEmpty()`? I guess empty index names have been eliminated before getting here.

Target:
public String getNextIndexName(String aliasName, String oldIndexName) { if (StringUtils.isEmpty(oldIndexName)) { 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); }
Source:
public void registerCache(String name, int maxSize, int timeout) { START registerCache(name, maxSize, timeout, new CacheDescriptor()); END } Why not retrieving the default descriptor ?

Target:
public void registerCache(String name, int maxSize, int timeout) { registerCache(name); }
Source:
START static public Record of(String key, byte[] data) { END return new Record(key, data, 0, DEFAULT_FLAG); } Correct keyword order

Target:
public static Record of(String key, byte[] data) { return new Record(key, data, 0, DEFAULT_FLAG); }
Source:
START static public boolean exists(File basePath) { END //noinspection ConstantConditions return basePath.isDirectory() && basePath.list().length > 0; } Correct keyword order

Target:
protected static boolean exists(File basePath) { // noinspection ConstantConditions return basePath.isDirectory() && basePath.list().length > 0; }
Source:
START static public <M extends Externalizable> KafkaLogAppender<M> open(String topic, String name, Properties producerProperties, Properties consumerProperties) { END return new KafkaLogAppender<>(topic, name, producerProperties, consumerProperties); } Correct keyword order

Target:
public static <M extends Externalizable> KafkaLogAppender<M> open(String topic, String name, Properties producerProperties, Properties consumerProperties) { return new KafkaLogAppender<>(topic, name, producerProperties, consumerProperties); }
Source:
protected void closeTailer() { if (tailer != null && !tailer.closed()) { try { tailer.close(); START } catch (Exception e) { END log.debug(metadata.name() + ": Exception while closing tailer", e); } } } Don't catch `Exception`, use something more specific.

Target:
protected void closeTailer() { if (tailer != null && !tailer.closed()) { tailer.close(); } }
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)); START return failures == 0L; END } No need for `0L`, `0` is enough.

Target:
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 == 0; }
Source:
public RebalanceException(String message) { START super(message); END } If you never need the stack trace, consider calling `super(message, null, false, false)` to avoid some overhead.

Target:
public RebalanceException(String message) { // we don't need the stack trace super(message, null, false, false); }
Source:
START public static boolean exists(File basePath) { END //noinspection ConstantConditions return basePath.isDirectory() && basePath.list().length > 0; } Should probably be `protected`, not `public`.

Target:
protected static boolean exists(File basePath) { // noinspection ConstantConditions return basePath.isDirectory() && basePath.list().length > 0; }
Source:
protected int findQueueIndex(File queueFile) { String queueDirName = queueFile.getParentFile().getName(); START return Integer.valueOf(queueDirName.substring(queueDirName.length() - 2)); END } `Integer.parseInt`

Target:
protected int findQueueIndex(File queueFile) { String queueDirName = queueFile.getParentFile().getName(); return Integer.parseInt(queueDirName.substring(queueDirName.length() - 2)); }
Source:
public List<String> listTopics() { Seq<String> topics = zkUtils.getAllTopics(); START return scala.collection.JavaConversions.seqAsJavaList(topics); END } `scala.collection.JavaConversions` -> `JavaConversions`

Target:
public List<String> listTopics() { Seq<String> topics = zkUtils.getAllTopics(); return JavaConversions.seqAsJavaList(topics); }
Source:
public void work() { START System.out.println("Work start"); END FileEvent.onFile(this, file, this).send(); SequenceTracer.mark("send event"); System.out.println("Work done"); } Remove `System.out.println`

Target:
public void work() { FileEvent.onFile(this, file, this).send(); SequenceTracer.mark("send event"); }
Source:
public void transientFilesWorkAreCleaned() throws Exception { final File file = feature.resolveAndCreate(new File("pfouh")); START Thread.sleep(100); END service.schedule(new CreateFile(file)); service.awaitCompletion(5, TimeUnit.SECONDS); } Is this needed?

Target:
public void transientFilesWorkAreCleaned() throws Exception { final File file = feature.resolveAndCreate(new File("pfouh")); service.schedule(new CreateFile(file)); service.awaitCompletion(5, TimeUnit.SECONDS); }
Source:
public TransientStore getTransientStore() { TransientStoreService tss = Framework.getService(TransientStoreService.class); START return tss.getStore(StringUtils.isNotBlank(this.storeName) ? storeName : CACHE_NAME); END } Don't use `isNotBlank` as this doesn't come from user input or config file. Just use `storeName != null`

Target:
public TransientStore getTransientStore() { TransientStoreService tss = Framework.getService(TransientStoreService.class); return tss.getStore(storeName != null ? storeName : CACHE_NAME); }
Source:
protected void writeProperty(JsonGenerator jg, Property prop) throws IOException { if (prop.isScalar()) { writeScalarProperty(jg, prop); } else if (prop.isList()) { START writeListProperty(jg, prop); END } else if (prop.isComplex()) { writeComplexProperty(jg, prop); } else if (prop instanceof BlobProperty) { // a blob writeBlobProperty(jg, prop); } else if (prop.isPhantom()) { jg.writeNull(); } } Because a `BlobProperty` is also a complex property, this check should come before `prop.isComplex()`. In my local tests I got a `NuxeoException` with `Trying to access a member of a null object: mime-type` when trying to write a blob property, which was treated as a complex.

Target:
protected void writeProperty(JsonGenerator jg, Property prop) throws IOException { if (prop.isScalar()) { writeScalarProperty(jg, prop); } else if (prop.isList()) { writeListProperty(jg, prop); } else if (prop instanceof BlobProperty) { // a blob writeBlobProperty(jg, prop); } else if (prop.isComplex()) { writeComplexProperty(jg, prop); } else if (prop.isPhantom()) { jg.writeNull(); } }
Source:
public ProbeStatus run() { START if (Framework.getRuntime().isStarted()) { END return ProbeStatus.newSuccess("Runtime started"); } return ProbeStatus.newFailure("Runtime not started"); } You should also check first `Framework.getRuntime() != null` just in case.

Target:
public ProbeStatus run() { if (Framework.getRuntime() != null && Framework.getRuntime().isStarted()) { return ProbeStatus.newSuccess("Runtime started"); } else { return ProbeStatus.newFailure("Runtime not started"); } }