auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static String accessToString(int access) { StringBuffer ret = new StringBuffer(); ret.append(((access & READ) > 0) ? "r" : "-"); ret.append(((access & WRITE) > 0) ? "w" : "-"); ret.append(((access & ADMIN) > 0) ? "a" : "-"); return ret.toString(); }

Target:
private static String accessToString(int access) { StringBuilder ret = new StringBuilder(); ret.append(((access & READ) > 0) ? "r" : "-"); ret.append(((access & WRITE) > 0) ? "w" : "-"); ret.append(((access & ADMIN) > 0) ? "a" : "-"); return ret.toString(); }
Source:
public boolean checkForValidUsers(Subject who, int mask) { if (isNimbus(who) || isAdmin(who) || isSupervisor(who,mask)) { return true; } return false; }

Target:
public boolean checkForValidUsers(Subject who, int mask) { return isNimbus(who) || isAdmin(who) || isSupervisor(who,mask); }
Source:
private String namedPerms(int mask) { StringBuffer b = new StringBuffer(); b.append("["); if ((mask & READ) > 0) { b.append("READ "); } if ((mask & WRITE) > 0) { b.append("WRITE "); } if ((mask & ADMIN) > 0) { b.append("ADMIN "); } b.append("]"); return b.toString(); }

Target:
private String namedPerms(int mask) { StringBuilder b = new StringBuilder(); b.append("["); if ((mask & READ) > 0) { b.append("READ "); } if ((mask & WRITE) > 0) { b.append("WRITE "); } if ((mask & ADMIN) > 0) { b.append("ADMIN "); } b.append("]"); return b.toString(); }
Source:
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { if(server != null) server.closeChannel(e.getChannel()); }

Target:
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { if(server != null) { server.closeChannel(e.getChannel()); } }
Source:
public ChannelBuffer buffer() throws IOException { ChannelBufferOutputStream bout = new ChannelBufferOutputStream( ChannelBuffers.directBuffer(encodeLength())); int payload_len = 0; if (token != null) payload_len = token.length; bout.writeShort(IDENTIFIER); bout.writeInt((int) payload_len); if (payload_len > 0) { bout.write(token); } bout.close(); return bout.buffer(); }

Target:
public ChannelBuffer buffer() throws IOException { ChannelBufferOutputStream bout = new ChannelBufferOutputStream( ChannelBuffers.directBuffer(encodeLength())); int payload_len = 0; if (token != null) payload_len = token.length; bout.writeShort(IDENTIFIER); bout.writeInt(payload_len); if (payload_len > 0) { bout.write(token); } bout.close(); return bout.buffer(); }
Source:
public void add(HashMap<Integer, ArrayList<TaskMessage>> taskTupleSetMap) { for (Map.Entry<Integer, ArrayList<TaskMessage>> entry : taskTupleSetMap.entrySet()) { Integer task = entry.getKey(); addListRefToMap(this.bundles, task, entry.getValue()); } }

Target:
public void add(HashMap<Integer, ArrayList<TaskMessage>> taskTupleSetMap) { for (Map.Entry<Integer, ArrayList<TaskMessage>> entry : taskTupleSetMap.entrySet()) { addListRefToMap(this.bundles, entry.getKey(), entry.getValue()); } }
Source:
private void markBatchGroups(String component, Map<String, String> batchGroups) { for(Map.Entry<String, String> entry: batchGroups.entrySet()) { String stream = entry.getKey(); _batchIds.put(new GlobalStreamId(component, stream), entry.getValue()); } }

Target:
private void markBatchGroups(String component, Map<String, String> batchGroups) { for(Map.Entry<String, String> entry: batchGroups.entrySet()) { _batchIds.put(new GlobalStreamId(component, entry.getKey()), entry.getValue()); } }
Source:
public void validateField(String name, boolean includeZero, Object o) { if (o == null) { return; } if (o instanceof Number) { if(includeZero == true) { if (((Number) o).doubleValue() >= 0.0) { return; } } else { if (((Number) o).doubleValue() > 0.0) { return; } } } throw new IllegalArgumentException("Field " + name + " must be a Positive Number"); }

Target:
public static void validateField(String name, boolean includeZero, Object o) { if (o == null) { return; } if (o instanceof Number) { if(includeZero) { if (((Number) o).doubleValue() >= 0.0) { return; } } else { if (((Number) o).doubleValue() > 0.0) { return; } } } throw new IllegalArgumentException("Field " + name + " must be a Positive Number"); }
Source:
public void validateField(String name, Object o) { if (o == null) { return; } if (o instanceof String) { return; } //check if iterable try { SimpleTypeValidator.validateField(name, Iterable.class, o); } catch (Exception ex) { } this.fv.validateField(name, o); }

Target:
public void validateField(String name, Object o) { if (o == null || o instanceof String) { // A null value or a String value is acceptable return; } this.fv.validateField(name, o); }
Source:
private static void validateConfs(Map stormConf, StormTopology topology) throws IllegalArgumentException { LOG.info("Validating storm Confs..."); double largestMemReq = getMaxExecutorMemoryUsageForTopo(topology, stormConf); Double topologyWorkerMaxHeapSize = Utils.getDouble(stormConf.get(Config.TOPOLOGY_WORKER_MAX_HEAP_SIZE_MB)); if(topologyWorkerMaxHeapSize < largestMemReq) { throw new IllegalArgumentException("Topology will not be able to be successfully scheduled: Config TOPOLOGY_WORKER_MAX_HEAP_SIZE_MB=" +Utils.getDouble(stormConf.get(Config.TOPOLOGY_WORKER_MAX_HEAP_SIZE_MB)) + " < " + largestMemReq + " (Largest memory requirement of a component in the topology). Perhaps set TOPOLOGY_WORKER_MAX_HEAP_SIZE_MB to a larger amount"); } }

Target:
private static void validateConfs(Map stormConf, StormTopology topology) throws IllegalArgumentException { double largestMemReq = getMaxExecutorMemoryUsageForTopo(topology, stormConf); Double topologyWorkerMaxHeapSize = Utils.getDouble(stormConf.get(Config.TOPOLOGY_WORKER_MAX_HEAP_SIZE_MB)); if(topologyWorkerMaxHeapSize < largestMemReq) { throw new IllegalArgumentException("Topology will not be able to be successfully scheduled: Config TOPOLOGY_WORKER_MAX_HEAP_SIZE_MB=" +Utils.getDouble(stormConf.get(Config.TOPOLOGY_WORKER_MAX_HEAP_SIZE_MB)) + " < " + largestMemReq + " (Largest memory requirement of a component in the topology). Perhaps set TOPOLOGY_WORKER_MAX_HEAP_SIZE_MB to a larger amount"); } }
Source:
public Double getTotalMemReqTask(ExecutorDetails exec) { if (hasExecInTopo(exec)) { return getOffHeapMemoryRequirement(exec) + getOnHeapMemoryRequirement(exec); } LOG.info("cannot find {}", exec); return null; }

Target:
public Double getTotalMemReqTask(ExecutorDetails exec) { if (hasExecInTopo(exec)) { return getOffHeapMemoryRequirement(exec) + getOnHeapMemoryRequirement(exec); } return null; }
Source:
public GraphGrouper(DirectedGraph<Node, IndexedEdge> graph, Collection<Group> initialGroups) { this.graph = graph; this.currGroups = new LinkedHashSet(initialGroups); reindex(); }

Target:
public GraphGrouper(DirectedGraph<Node, IndexedEdge> graph, Collection<Group> initialGroups) { this.graph = graph; this.currGroups = new LinkedHashSet<>(initialGroups); reindex(); }
Source:
private void ack(Tuple tuple) throws SolrServerException, IOException { if (commitStgy == null) { collector.ack(tuple); } else { synchronized(ackFailLock) { toCommitTuples.add(tuple); commitStgy.update(); } if (commitStgy.commit()) { solrClient.commit(solrMapper.getCollection()); ackCommittedTuples(); } } }

Target:
private void ack(Tuple tuple) throws SolrServerException, IOException { if (commitStgy == null) { collector.ack(tuple); } else { toCommitTuples.add(tuple); commitStgy.update(); if (commitStgy.commit()) { solrClient.commit(solrMapper.getCollection()); ackCommittedTuples(); } } }
Source:
private static Config getConfig(String brokerConnectionString) { Config conf = new Config(); Map config = new HashMap(); Properties props = new Properties(); props.put("metadata.broker.list", brokerConnectionString); props.put("request.required.acks", "1"); props.put("serializer.class", "kafka.serializer.StringEncoder"); conf.put(TridentKafkaState.KAFKA_BROKER_PROPERTIES, props); conf.put(TridentKafkaState.TOPIC, "test"); return conf; }

Target:
private static Config getConfig(String brokerConnectionString) { Config conf = new Config(); Map config = new HashMap(); Properties props = new Properties(); props.put("metadata.broker.list", brokerConnectionString); props.put("request.required.acks", "1"); props.put("serializer.class", "kafka.serializer.StringEncoder"); conf.put(TridentKafkaState.KAFKA_BROKER_PROPERTIES, props); return conf; }
Source:
void closeOutputFile() throws IOException { this.writer.hsync(); this.writer.close(); }

Target:
void closeOutputFile() throws IOException { this.writer.close(); }
Source:
public long nextPoll() { long now = System.currentTimeMillis(); long cycle = (now - startTime) / pollMs; long wakeupTime = startTime + (pollMs * (cycle + 1)); long sleepTime = wakeupTime - now; if (sleepTime > 0) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } } now = System.currentTimeMillis(); return now; }

Target:
public long nextPoll() throws InterruptedException { long now = System.currentTimeMillis(); long cycle = (now - startTime) / pollMs; long wakeupTime = startTime + (pollMs * (cycle + 1)); long sleepTime = wakeupTime - now; if (sleepTime > 0) { Thread.sleep(sleepTime); } now = System.currentTimeMillis(); return now; }
Source:
private void umount(String localRootPath) { if (!mountExists(localRootPath)) { return; } Script command = new Script(true, "umount", timeout, s_logger); command.add(localRootPath); String result = command.execute(); if (result != null) { // Fedora Core 12 errors out with any -o option executed from java String errMsg = "Unable to umount " + localRootPath + " due to " + result; s_logger.error(errMsg); throw new CloudRuntimeException(errMsg); } deleteMountPath(localRootPath); s_logger.debug("Successfully umounted " + localRootPath); }

Target:
private void umount(String localRootPath) { if (!mountExists(localRootPath)) { return; } Script command = new Script(true, "umount", timeout, s_logger); command.add(localRootPath); String result = command.execute(); if (result != null) { // Fedora Core 12 errors out with any -o option executed from java String errMsg = "Unable to umount " + localRootPath + " due to " + result; s_logger.error(errMsg); throw new CloudRuntimeException(errMsg); } deleteMountPath(localRootPath); s_logger.info("Successfully umounted " + localRootPath); }
Source:
public List<VlanVO> listVlansForPod(long podId) { //FIXME: use a join statement to improve the performance (should be minor since we expect only one or two List<PodVlanMapVO> vlanMaps = _podVlanMapDao.listPodVlanMapsByPod(podId); List<VlanVO> result = new ArrayList<VlanVO>(); for (PodVlanMapVO pvmvo : vlanMaps) { VlanVO vlanByPodId = findById(pvmvo.getVlanDbId()); if (vlanByPodId != null && vlanByPodId.getRemoved() == null) { result.add(vlanByPodId); } } return result; }

Target:
public List<VlanVO> listVlansForPod(long podId) { //FIXME: use a join statement to improve the performance (should be minor since we expect only one or two List<PodVlanMapVO> vlanMaps = _podVlanMapDao.listPodVlanMapsByPod(podId); List<VlanVO> result = new ArrayList<VlanVO>(); for (PodVlanMapVO pvmvo : vlanMaps) { VlanVO vlanByPodId = findById(pvmvo.getVlanDbId()); if (vlanByPodId != null) { result.add(vlanByPodId); } } return result; }
Source:
private Long getDefaultNetwork(long vmId) { NicVO defaultNic = _nicDao.findDefaultNicForVM(vmId); if (defaultNic != null) return defaultNic.getNetworkId(); return null; }

Target:
private Long getDefaultNetwork(long vmId) { NicVO defaultNic = _nicDao.findDefaultNicForVM(vmId); if (defaultNic != null) { return defaultNic.getNetworkId(); } return null; }
Source:
public boolean configDnsSupportForSubnet(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { // Ignore if virtual router is already dhcp provider if (_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Dhcp, getProvider())) { return true; } else { return configureDhcpSupport(network, nic, vm, dest, Service.Dns); } }

Target:
public boolean configDnsSupportForSubnet(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { // Ignore if virtual router is already dhcp provider if (_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Dhcp, getProvider())) { return true; } return configureDhcpSupport(network, nic, vm, dest, Service.Dns); }
Source:
public void connect() throws Exception { super.connect(); if (properties.getSchema() != null && properties.getSchema().length() > 0 && !properties.getUsername().equals(properties.getSchema())) { // Set connection schema if one is defined and not the same as the user name final Statement stmt = conn.createStatement(); stmt.execute("ALTER SESSION SET CURRENT_SCHEMA=" + properties.getSchema()); stmt.close(); } }

Target:
public void connect() throws Exception { super.connect(); if (properties.getSchema() != null && properties.getSchema().length() > 0 && !properties.getUsername().equals(properties.getSchema())) { // Set connection schema if one is defined and not the same as the user name try (final Statement stmt = conn.createStatement()) { stmt.execute("ALTER SESSION SET CURRENT_SCHEMA=" + properties.getSchema()); } } }
Source:
private static void handleConsoleMessage(TaskListener listener, boolean isValidCommand, String path) { boolean isValidPath = false; isValidPath = (path != null && (path.isEmpty() || path.equals("accurev"))); if (isValidCommand && isValidPath) { listener.getLogger().println(String.format("No AccuRev tool configured, using default")); } }

Target:
private static void handleConsoleMessage(TaskListener listener, boolean isValidCommand, String path) { boolean isValidPath = false; isValidPath = (path != null && (path.isEmpty() || path.equals("accurev"))); if (isValidCommand && isValidPath) { listener.getLogger().println("No AccuRev tool configured, using default"); } }
Source:
public void testFailingBulkAction() throws Exception { String result = async.newRequest(BulkRunAction.ID) // .set("action", AutomationBulkAction.ACTION_NAME) .set("query", "SELECT * FROM Folder") .set("bucketSize", "10") .set("batchSize", "5") .set("parameters", MAPPER.writeValueAsString("{}")) .executeReturningExceptionEntity(SC_INTERNAL_SERVER_ERROR); assertTrue( result.startsWith("Unknown operation id null in command: org.nuxeo.ecm.core.bulk.message.BulkCommand")); }

Target:
public void testFailingBulkAction() throws Exception { String result = async.newRequest(BulkRunAction.ID) // .set("action", AutomationBulkAction.ACTION_NAME) .set("query", "SELECT * FROM Folder") .set("bucketSize", "10") .set("batchSize", "5") .set("parameters", "{}") .executeReturningExceptionEntity(SC_INTERNAL_SERVER_ERROR); assertTrue( result.startsWith("Unknown operation id null in command: org.nuxeo.ecm.core.bulk.message.BulkCommand")); }
Source:
public 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:
public List<BundleInfo> getBundles() { List<BundleInfo> res = new ArrayList<>(bundles.values()); // order by name for deterministic processing res.sort(Comparator.comparing(BundleInfo::getId)); return res; }
Source:
public static void assumeKafkaEnabled() { if ("true".equals(System.getProperty("kafka"))// deprecated since 10.3 || STREAM_KAFKA.equals(System.getProperty(STREAM_PROPERTY))) { if (!KafkaUtils.kafkaDetected()) { fail("Kafka is enabled, but no Kafka server found."); } } else { Assume.assumeTrue("Kafka not enabled", false); } }

Target:
public static void assumeKafkaEnabled() { if ("true".equals(System.getProperty("kafka"))// deprecated since 10.3 || STREAM_KAFKA.equals(System.getProperty(STREAM_PROPERTY))) { if (!KafkaUtils.kafkaDetected()) { fail("Kafka is enabled, but no Kafka server found."); } } else { assumeTrue("Kafka not enabled", false); } }
Source:
public void 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:
public void createUser(String userName) { try { DocumentModel userModel = userManager.getBareUserModel(); userModel.setProperty("user", "username", userName); userManager.createUser(userModel); } catch (UserAlreadyExistsException e) { // Avoid failure in tests if the user already exists log.trace("User already exists", e); } }
Source:
public void shouldNotifyEventWhenCreateAnnotation() { // We subscribe to the creation document to check that we will not be notified about the annotation creation as // document (see CommentCreationVeto), only the annotation added, and the 'File' document creation captureAndVerifyAnnotationEventNotification(() -> { Annotation createdAnnotation = createAnnotationAndAddSubscription("CommentAdded", "Creation"); return session.getDocument(new IdRef(createdAnnotation.getId())); }, COMMENT_ADDED, DOCUMENT_CREATED, 2); }

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

Target:
public void shouldNotifyEventWhenUpdateAnnotation() { // We subscribe to the update document to check that we will not be notified about the annotation updated as // document (see CommentModificationVeto), only the annotation updated. Annotation annotation = createAnnotationAndAddSubscription("CommentUpdated", "Modification"); captureAndVerifyAnnotationEventNotification(() -> { annotation.setText("I update the annotation"); annotationService.updateAnnotation(session, annotation.getId(), annotation); return session.getDocument(new IdRef(annotation.getId())); }, COMMENT_UPDATED, DOCUMENT_UPDATED); }
Source:
public 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:
public boolean accept(Event event) { if (!(event.getContext() instanceof DocumentEventContext)) { return false; } DocumentEventContext docCtx = (DocumentEventContext) event.getContext(); String docType = docCtx.getSourceDocument().getType(); return !(EXCLUDED_EVENT_TYPES.contains(event.getName()) && ACCEPTED_COMMENT_TYPE.contains(docType)); }
Source:
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:
public void shouldNotifyEventWhenCreateComment() { // We subscribe to the creation document to check that we will not be notified about the comment creation as // document (see CommentCreationVeto), only the comment added, and the 'File' document creation captureAndVerifyCommentEventNotification(() -> { Comment createdComment = createCommentAndAddSubscription("CommentAdded", "Creation"); return session.getDocument(new IdRef(createdComment.getId())); }, COMMENT_ADDED, DOCUMENT_CREATED); }
Source:
protected 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:
protected List<String> getPropertiesToFetch() { Set<String> fetched = ctx.getFetched(ENTITY_TYPE); List<String> propertiesToFetch = DEFAULT_PROPERTIES.stream() .filter(fetched::contains) .collect(Collectors.toList()); // if no particular property to fetch, fetch all default properties return propertiesToFetch.isEmpty() ? DEFAULT_PROPERTIES : propertiesToFetch; }
Source:
public void deleteComment(CoreSession s, String commentId) { DocumentModel commentDocumentModel = CoreInstance.doPrivileged(s, session -> { return getCommentDocumentModel(session, new IdRef(commentId)); }); removeComment(s, commentDocumentModel.getRef()); }

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

Target:
protected String copyRecurse(String sourceId, String parentId, LinkedList<String> ancestorIds, String name, boolean excludeSpecialChildren, boolean excludeRegularChildren) { String copyId = copy(sourceId, parentId, ancestorIds, name); ancestorIds.addLast(copyId); for (String childId : getChildrenIds(sourceId, excludeSpecialChildren, excludeRegularChildren)) { // don't exclude regular children when recursing copyRecurse(childId, copyId, ancestorIds, null, excludeSpecialChildren, false); } ancestorIds.removeLast(); return copyId; }
Source:
protected 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:
protected DocumentModel createHiddenFolder(CoreSession session, String parentPath, String name) { DocumentModel dm = session.createDocumentModel(parentPath, name, "HiddenFolder"); dm.setProperty("dublincore", "title", name); dm.setProperty("dublincore", "description", ""); Framework.doPrivileged(() -> dm.setProperty("dublincore", "created", Calendar.getInstance())); DocumentModel parent = session.createDocument(dm); // change variable name to be effectively final setFolderPermissions(session, parent); return parent; }
Source:
protected static <R> R runAndCleanupTransactionContext(Supplier<R> supplier) { try { return supplier.get(); } finally { if (!TransactionHelper.isNoTransaction()) { // restore the no-transaction context of this thread try { TransactionHelper.commitOrRollbackTransaction(); } catch (TransactionRuntimeException e) { log.error("Failed to commit/rollback", e); } } } }

Target:
protected static <R> R runAndCleanupTransactionContext(Supplier<R> supplier) { try { return supplier.get(); } finally { if (!isNoTransaction()) { // restore the no-transaction context of this thread try { commitOrRollbackTransaction(); } catch (TransactionRuntimeException e) { log.error("Failed to commit/rollback", e); } } } }
Source:
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:
public <T extends Annotation> T getConfig(FrameworkMethod method, Class<T> type) { T config = method.getAnnotation(type); if (config != null) { return config; } // if not define, try to get the config of the class return getConfig(type); }
Source:
public ESHintQueryBuilder newInstance() { try { return getKlass().getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException e) { throw new NuxeoException(String.format("Cannot instantiate esHintQueryBuilder from %s", getKlass()), e); } }

Target:
public ESHintQueryBuilder newInstance() { try { return getKlass().getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException e) { throw new NuxeoException(e); } }
Source:
public QueryBuilder make(EsHint hint, String fieldName, Object value) { 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:
public QueryBuilder make(EsHint hint, String fieldName, Object value) { String valueString = (String) value; if (valueString.endsWith("*") && valueString.length() > 2) { // remove useless trailing *, this is not mandatory but cleaner value = valueString.substring(0, valueString.length() - 1); } return QueryBuilders.matchPhrasePrefixQuery(fieldName, value).analyzer(hint.analyzer); }
Source:
public void 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:
public void initOAuthClient() { // Clients to make the requests like a "Client" as the OAuth2 RFC describes it // Authenticated client for the /oauth2/authorize and /oauth2/authorize_submit endpoints authenticatedClient = JerseyClientHelper.clientBuilder() .setRedirectsEnabled(false) .setCredentials("Administrator", "Administrator") .build(); // Unauthenticated client for the /oauth2/token endpoint client = JerseyClientHelper.clientBuilder().setRedirectsEnabled(false).build(); transientStore = (TransientStoreProvider) transientStoreService.getStore(AuthorizationRequest.STORE_NAME); tokenStore = new OAuth2TokenStore(TOKEN_SERVICE); }
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:
protected void attach(DocumentModel doc) { String sid = ctx.getCoreSession().getSessionId(); doc.attach(sid); }
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:
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:
String getKey(String commandId) { return metadata.name() + commandId; }

Target:
protected String getKey(String commandId) { return metadata.name() + commandId; }
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:
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( 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:
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:
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:
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:
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:
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:
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:
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 ScheduleImpl buildTestSchedule() { ScheduleImpl schedule = new ScheduleImpl(); schedule.id = "testing"; schedule.username = "Administrator"; schedule.eventId = "testEvent"; schedule.eventCategory = "default"; return schedule; }

Target:
protected ScheduleImpl buildTestSchedule() { ScheduleImpl schedule = new ScheduleImpl(); schedule.id = "testing"; schedule.username = "Administrator"; schedule.eventId = "testEvent"; schedule.eventCategory = "default"; return schedule; }
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 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 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:
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:
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:
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:
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:
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:
private URL toURL(Path p) { try { return p.toUri().toURL(); } catch (MalformedURLException e) { throw new IllegalStateException(e); } }

Target:
protected URL toURL(Path p) { try { return p.toUri().toURL(); } catch (MalformedURLException e) { throw new IllegalStateException(e); } }
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:
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:
static public boolean exists(File basePath) { //noinspection ConstantConditions return basePath.isDirectory() && basePath.list().length > 0; }

Target:
protected static boolean exists(File basePath) { // noinspection ConstantConditions return basePath.isDirectory() && basePath.list().length > 0; }
Source:
public RebalanceException(String message) { super(message); }

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

Target:
protected static boolean exists(File basePath) { // noinspection ConstantConditions return basePath.isDirectory() && basePath.list().length > 0; }
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:
public void work() { FileEvent.onFile(this, file, this).send(); SequenceTracer.mark("send event"); }
Source:
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.isComplex()) { writeComplexProperty(jg, prop); } else if (prop instanceof BlobProperty) { // a blob writeBlobProperty(jg, prop); } else if (prop.isPhantom()) { jg.writeNull(); } }

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() { if (Framework.getRuntime() != null && Framework.getRuntime().isStarted()) { return ProbeStatus.newSuccess("Runtime started"); } return ProbeStatus.newFailure("Runtime not started"); }

Target:
public ProbeStatus run() { if (Framework.getRuntime() != null && Framework.getRuntime().isStarted()) { return ProbeStatus.newSuccess("Runtime started"); } else { return ProbeStatus.newFailure("Runtime not started"); } }
Source:
protected HealthCheckResult getOrRunHealthCheck(String probe) { ProbeManager pm = Framework.getService(ProbeManager.class); if (StringUtils.isEmpty(probe)) { // run all healthCheck probes return pm.getOrRunHealthChecks(); } return pm.getOrRunHealthCheck(probe); }

Target:
protected HealthCheckResult getOrRunHealthCheck(String probe) { ProbeManager pm = Framework.getService(ProbeManager.class); if (StringUtils.isEmpty(probe)) { // run all healthCheck probes return pm.getOrRunHealthChecks(); } else { return pm.getOrRunHealthCheck(probe); } }
Source:
public void testRetryPostEnabled() throws Exception { // Enable POST retry enableSunHttpClientRetryPostProp(); sendInitialGetRequest(); // POST retry is enabled, the call should succeed ClientResponse response = webResource.post(ClientResponse.class); assertEquals(200, response.getStatus()); response.close(); }

Target:
public void testRetryPostEnabled() throws Exception { // Enable POST retry enableSunHttpClientRetryPostProp(); sendInitialGetRequest(); // POST retry is enabled, the call should succeed ClientResponse response = null; try { response = webResource.post(ClientResponse.class); assertEquals(200, response.getStatus()); } finally { if (response != null) { response.close(); } } }
Source:
public DocumentModel run(DocumentModel doc) throws ConcurrentUpdateException, IOException { if (changeToken != null) { // Check for dirty update save = true; doc.putContextData(CoreSession.CHANGE_TOKEN, changeToken); } DocumentHelper.setProperties(session, doc, properties); if (save) { doc = session.saveDocument(doc); // may throw ConcurrentUpdateException if bad change token } return doc; }

Target:
public DocumentModel run(DocumentModel doc) throws ConcurrentUpdateException, IOException { if (changeToken != null) { // Check for dirty update doc.putContextData(CoreSession.CHANGE_TOKEN, changeToken); } DocumentHelper.setProperties(session, doc, properties); if (save) { doc = session.saveDocument(doc); // may throw ConcurrentUpdateException if bad change token } return doc; }
Source:
public boolean shouldIgnore() { return coreFeature.getStorageConfiguration().isVCS() // MySQL fulltext is funky with respect to what words it finds in small databases // so don't bother testing on MySQL, this is mostly a configuration test anyway || coreFeature.getStorageConfiguration().isVCSMySQL(); }

Target:
public boolean shouldIgnore() { return !coreFeature.getStorageConfiguration().isVCS() // MySQL fulltext is funky with respect to what words it finds in small databases // so don't bother testing on MySQL, this is mostly a configuration test anyway || coreFeature.getStorageConfiguration().isVCSMySQL(); }
Source:
private void checkUserExistence(String username) { UserManager userManager = Framework.getService(UserManager.class); if (userManager.getUserModel(username) == null && userManager.getGroupModel(username) == null) { String errorMsg = "User or group name '" + username + "' does not exist. Please provide a valid name."; throw new NuxeoException(errorMsg); } }

Target:
protected void checkUserExistence(String username) { UserManager userManager = Framework.getService(UserManager.class); if (userManager.getUserModel(username) == null && userManager.getGroupModel(username) == null) { String errorMsg = "User or group name '" + username + "' does not exist. Please provide a valid name."; throw new NuxeoException(errorMsg); } }
Source:
public static String getEntryContentAsString(File file, String entryName) throws IOException { InputStream resultStream = getEntryContentAsStream(file, entryName); // resultStream has been closed by FileUtils call return IOUtils.toString(resultStream, Charsets.UTF_8); }

Target:
public static String getEntryContentAsString(File file, String entryName) throws IOException { try (InputStream resultStream = getEntryContentAsStream(file, entryName)) { return IOUtils.toString(resultStream, Charsets.UTF_8); } }
Source:
public Type getType(String id) { Type type = types.get(id); if (type == null) { return null; } else { Map<String, SubType> allowedSubTypes = getCoreAllowedSubtypes(type); Type newType = type.clone(); newType.setAllowedSubTypes(allowedSubTypes); // do not need to add denied subtypes because allowed subtypes already come filtered from core newType.setDeniedSubTypes(new String[0]); return newType; } }

Target:
public Type getType(String id) { return types.get(id); }
Source:
public String getVocabularyLabel(String voc, String key) { try (Session session = getDirService().open(voc)) { if (!session.hasEntry(key)) { log.warn("Unable to find the key '" + key + "' in the vocabulary '" + voc + "'."); return key; } DocumentModel doc = session.getEntry(key); // TODO: which is the best method to get "label" property when not // knowing vocabulary schema? // AT: the best is to accept it as a parameter of the method, and // fallback on "label" when not given DataModel dm = doc.getDataModels().values().iterator().next(); return (String) dm.getData("label"); } }

Target:
public String getVocabularyLabel(String voc, String key) { try (Session session = getDirService().open(voc)) { if (!session.hasEntry(key)) { log.debug("Unable to find the key '" + key + "' in the vocabulary '" + voc + "'."); return key; } DocumentModel doc = session.getEntry(key); // TODO: which is the best method to get "label" property when not // knowing vocabulary schema? // AT: the best is to accept it as a parameter of the method, and // fallback on "label" when not given DataModel dm = doc.getDataModels().values().iterator().next(); return (String) dm.getData("label"); } }
Source:
public DocumentModel toFields(DocumentModel inDoc, HashMap<String, String> inMapping, boolean inSave, CoreSession inSession) { // Parse if needed run(); HashMap<String, String> values = toHashMap(); for (String inXPath : inMapping.keySet()) { String value = values.get(inMapping.get(inXPath)); inDoc.setPropertyValue(inXPath, value); } if (inSave) { inDoc = inSession.saveDocument(inDoc); } return inDoc; }

Target:
public DocumentModel toFields(DocumentModel inDoc, HashMap<String, String> inMapping, boolean inSave, CoreSession inSession) { // Parse if needed run(); Map<String, String> values = toHashMap(); for (String inXPath : inMapping.keySet()) { String value = values.get(inMapping.get(inXPath)); inDoc.setPropertyValue(inXPath, value); } if (inSave) { inDoc = inSession.saveDocument(inDoc); } return inDoc; }
Source:
public boolean documentExists(CoreSession session, String idOrPath) { DocumentRef documentRef; if (idOrPath.startsWith("/")) { documentRef = new PathRef(idOrPath); } else { documentRef = new IdRef(idOrPath); } try { // we do not need the variable, just check if the document exists /*DocumentModel doc = */session.getDocument(documentRef); } catch (DocumentNotFoundException exception) { return false; } return true; }

Target:
public boolean documentExists(CoreSession session, String idOrPath) { DocumentRef documentRef = idOrPath.startsWith("/") ? new PathRef(idOrPath) : new IdRef(idOrPath); return session.exists(documentRef); }
Source:
public DocumentModel run(DocumentModel input) { // we ignore the result /*boolean result = */ input.addFacet(facet); session.saveDocument(input); return input; }

Target:
public DocumentModel run(DocumentModel input) { input.addFacet(facet); input = session.saveDocument(input); return input; }