auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Statement apply(Statement base, Description description) { return rule.apply(base, createFrameworkMethod(description), description.getTestClass()); }

Target:
public Statement apply(Statement base, Description description) { try { String methodName = description.getMethodName(); Method method = testObject.getClass().getDeclaredMethod(methodName); return rule.apply(base, new FrameworkMethod(method), testObject); } catch (final NoSuchMethodException e) { return new Statement() { @Override public void evaluate() throws Throwable { throw e; } }; } }
Source:
@Test public void testTableFunctionInSelectWithUnion() { sql("select * from (" + "select a.deptno, table_func(a.deptno) as (f0, f1)" + " from (select * from dept) a " + " union all " + " select 1, table_func(b.deptno) as (f0, f1) from dept b" + ")") .conformance(SqlConformance.HIVE) .ok(); }

Target:
@Test public void testTableFunctionInSelectWithUnion() { sql("select * from (" + "select a.deptno, table_func(a.deptno) as (f0, f1)" + " from (select * from dept) a " + " union all " + " select 1, table_func(b.deptno) as (f0, f1) from dept b" + ")") .conformance(SqlConformanceEnum.HIVE) .ok(); }
Source:
public StaticSelector(Optional<Pattern> userRegex, Optional<Pattern> sourceRegex, Optional<List<String>> clientTags, Optional<String> queryType, ResourceGroupIdTemplate group) { this.userRegex = requireNonNull(userRegex, "userRegex is null"); this.sourceRegex = requireNonNull(sourceRegex, "sourceRegex is null"); this.clientTags = requireNonNull(clientTags, "clientTags is null").map(ImmutableSet::copyOf).orElse(ImmutableSet.of()); this.queryType = requireNonNull(queryType, "queryType is null"); this.group = requireNonNull(group, "group is null"); }

Target:
public StaticSelector(Optional<Pattern> userRegex, Optional<Pattern> sourceRegex, Optional<List<String>> clientTags, Optional<String> queryType, ResourceGroupIdTemplate group) { this.userRegex = requireNonNull(userRegex, "userRegex is null"); this.sourceRegex = requireNonNull(sourceRegex, "sourceRegex is null"); requireNonNull(clientTags, "clientTags is null"); this.clientTags = ImmutableSet.copyOf(clientTags.orElse(ImmutableList.of())); this.queryType = requireNonNull(queryType, "queryType is null"); this.group = requireNonNull(group, "group is null"); }
Source:
public static void check( final HaxeTypeCheckExpr expr, final AnnotationHolder holder ) { final PsiElement[] children = expr.getChildren(); if (children.length == 2) { final HaxeGenericResolver resolver = HaxeGenericResolverUtil.generateResolverFromScopeParents(expr); final ResultHolder statementResult = HaxeTypeResolver.getPsiElementType(children[0], expr, resolver); ResultHolder assertionResult = SpecificTypeReference.getUnknown(expr).createHolder(); if (children[1] instanceof HaxeTypeOrAnonymous) { assertionResult = HaxeTypeResolver.getTypeFromTypeOrAnonymous((HaxeTypeOrAnonymous)children[1]); ResultHolder resolveResult = resolver.resolve(assertionResult.getType().toStringWithoutConstant()); if (null != resolveResult) { assertionResult = resolveResult; } } if (!assertionResult.canAssign(statementResult)) { final HaxeDocumentModel document = HaxeDocumentModel.fromElement(expr); Annotation annotation = holder.createErrorAnnotation(children[0], "Statement of type '" + statementResult.getType().toStringWithoutConstant() + "' does not unify with asserted type '" + assertionResult.getType().toStringWithoutConstant() + ".'"); annotation.registerFix(new HaxeFixer("Remove type check") { @Override public void run() { document.replaceElementText(expr, children[0].getText()); } }); annotation.registerFix(new HaxeFixer("Change type check to " + statementResult.toStringWithoutConstant()) { @Override public void run( ) { document.replaceElementText(children[1], statementResult.toStringWithoutConstant()); } }); } } }

Target:
public static void check( final HaxeTypeCheckExpr expr, final AnnotationHolder holder ) { final PsiElement[] children = expr.getChildren(); if (children.length == 2) { final HaxeGenericResolver resolver = HaxeGenericResolverUtil.generateResolverFromScopeParents(expr); final ResultHolder statementResult = HaxeTypeResolver.getPsiElementType(children[0], expr, resolver); ResultHolder assertionResult = SpecificTypeReference.getUnknown(expr).createHolder(); if (children[1] instanceof HaxeTypeOrAnonymous) { assertionResult = HaxeTypeResolver.getTypeFromTypeOrAnonymous((HaxeTypeOrAnonymous)children[1]); ResultHolder resolveResult = resolver.resolve(assertionResult.getType().toStringWithoutConstant()); if (null != resolveResult) { assertionResult = resolveResult; } } if (!assertionResult.canAssign(statementResult)) { final HaxeDocumentModel document = HaxeDocumentModel.fromElement(expr); Annotation annotation = holder.createErrorAnnotation(children[0], HaxeBundle.message("haxe.semantic.statement.does.not.unify.with.asserted.type", statementResult.getType().toStringWithoutConstant(), assertionResult.getType().toStringWithoutConstant())); annotation.registerFix(new HaxeFixer(HaxeBundle.message("remove.type.check")) { @Override public void run() { document.replaceElementText(expr, children[0].getText()); } }); annotation.registerFix(new HaxeFixer(HaxeBundle.message("change.type.check.to.0", statementResult.toStringWithoutConstant())) { @Override public void run( ) { document.replaceElementText(children[1], statementResult.toStringWithoutConstant()); } }); } } }
Source:
public OAuth2TokenValidatorResult validate(Jwt jwt) { Assert.notNull(jwt, "jwt cannot be null"); Instant expiry = jwt.getExpiresAt(); if (expiry != null) { if (Instant.now(this.clock).minus(clockSkew).isAfter(expiry)) { if (logger.isDebugEnabled()){ logger.debug("Failed to validate OAuth2 token claim. Token has expired"); } OAuth2Error error = new OAuth2Error( OAuth2ErrorCodes.INVALID_REQUEST, String.format("Jwt expired at %s", jwt.getExpiresAt()), "<LINK_0>"); return OAuth2TokenValidatorResult.failure(error); } } Instant notBefore = jwt.getNotBefore(); if (notBefore != null) { if (Instant.now(this.clock).plus(clockSkew).isBefore(notBefore)) { if (logger.isDebugEnabled()){ logger.debug("Failed to validate OAuth2 token claim. Token should not be used before: " + isoDateTime(notBefore)); } OAuth2Error error = new OAuth2Error( OAuth2ErrorCodes.INVALID_REQUEST, String.format("Jwt used before %s", jwt.getNotBefore()), "<LINK_0>"); return OAuth2TokenValidatorResult.failure(error); } } return OAuth2TokenValidatorResult.success(); }

Target:
public OAuth2TokenValidatorResult validate(Jwt jwt) { Assert.notNull(jwt, "jwt cannot be null"); Instant expiry = jwt.getExpiresAt(); if (expiry != null) { if (Instant.now(this.clock).minus(clockSkew).isAfter(expiry)) { final OAuth2Error oAuth2Error = createOAuth2Error(String.format("Jwt expired at %s", jwt.getExpiresAt())); return OAuth2TokenValidatorResult.failure(oAuth2Error); } } Instant notBefore = jwt.getNotBefore(); if (notBefore != null) { if (Instant.now(this.clock).plus(clockSkew).isBefore(notBefore)) { final OAuth2Error oAuth2Error = createOAuth2Error(String.format("Jwt used before %s", jwt.getNotBefore())); return OAuth2TokenValidatorResult.failure(oAuth2Error); } } return OAuth2TokenValidatorResult.success(); }
Source:
public static void main(String[] args){ try { createTestSAM(); } catch(IOException e) { ; } }

Target:
public static void main(String[] args) { try { createTestSAM("TestSam"); } catch(IOException e) { ; } }
Source:
String process(int requestCode, int resultCode, Intent i) { trace(this, "process() :: requestCode=%s", requestCode); switch(requestCode) { case GRAB_MRDT_PHOTO: { try { byte[] data = i.getByteArrayExtra("data"); String base64data = Base64.encodeToString(data, Base64.NO_WRAP); long timeTaken = i.getLongExtra("timeTaken", 0); return safeFormat("angular.element(document.body).injector().get('AndroidApi').v1.mrdtResponse('\"%s|%s\"')", String.valueOf(timeTaken), base64data); } catch(Exception ex) { warn(ex, "Problem serialising mrdt image."); return safeFormat("console.log('Problem serialising mrdt image: %s')", ex); } } default: throw new RuntimeException("Bad request type: " + requestCode); } }

Target:
String process(int requestCode, int resultCode, Intent i) { trace(this, "process() :: requestCode=%s", requestCode); switch(requestCode) { case GRAB_MRDT_PHOTO: { try { byte[] data = i.getByteArrayExtra("data"); String base64data = Base64.encodeToString(data, Base64.NO_WRAP); long timeTaken = i.getLongExtra("timeTaken", 0); String javaScript = "var api = angular.element(document.body).injector().get('AndroidApi');" + "if (api.v1.mrdtTimeTakenResponse) {" + " api.v1.mrdtTimeTakenResponse('\"%s\"');" + "}" + "api.v1.mrdtResponse('\"%s\"');"; return safeFormat(javaScript, String.valueOf(timeTaken), base64data); } catch(Exception ex) { warn(ex, "Problem serialising mrdt image."); return safeFormat("console.log('Problem serialising mrdt image: %s')", ex); } } default: throw new RuntimeException("Bad request type: " + requestCode); } }
Source:
public static String mongoGetRegistrationKey(final Authenticator authenticator, final DB database, final String authId, final String bankProblemId) throws AuthenticationException, DatabaseAccessException { final DBCollection collection = database.getCollection(getCollectionFromType(School.ItemType.BANK_PROBLEM)); final DBObject cursor = collection.findOne(convertStringToObjectId(bankProblemId)); if (cursor == null) { throw new DatabaseAccessException("BankProblem was not found with the following ID " + bankProblemId); } final Authentication.AuthType authType = Authentication.AuthType.newBuilder() .setCheckIsRegistrationRequired(true) .setCheckingAdmin(true) .setCheckIsPublished(true) .build(); final AuthenticationResponder responder = authenticator .checkAuthentication(School.ItemType.BANK_PROBLEM, bankProblemId.trim(), authId, 0, authType); if ((!responder.isRegistrationRequired() && responder.isItemPublished()) || responder.hasTeacherPermission()) { return (String) cursor.get(DatabaseStringConstants.REGISTRATION_KEY); } return null; }

Target:
public static String mongoGetRegistrationKey(final Authenticator authenticator, final DB database, final String authId, final String bankProblemId) throws AuthenticationException, DatabaseAccessException { final DBCollection bankProblemCollection = database.getCollection(getCollectionFromType(School.ItemType.BANK_PROBLEM)); final DBObject cursor = bankProblemCollection.findOne(convertStringToObjectId(bankProblemId)); if (cursor == null) { throw new DatabaseAccessException("BankProblem was not found with the following ID " + bankProblemId); } final Authentication.AuthType authType = Authentication.AuthType.newBuilder() .setCheckIsRegistrationRequired(true) .setCheckingAdmin(true) .setCheckIsPublished(true) .build(); final AuthenticationResponder responder = authenticator .checkAuthentication(School.ItemType.BANK_PROBLEM, bankProblemId.trim(), authId, 0, authType); if ((!responder.isRegistrationRequired() && responder.isItemPublished()) || responder.hasTeacherPermission()) { return (String) cursor.get(DatabaseStringConstants.REGISTRATION_KEY); } return null; }
Source:
public List<SAMValidationError> isValid(final boolean firstOnly) { if (!initializedFields.contains(LazyField.REFERENCE_NAME)) { getReferenceName(); } if (!initializedFields.contains(LazyField.MATE_REFERENCE_NAME)) { getMateReferenceName(); } getFlags(); return super.isValid(firstOnly); }

Target:
public List<SAMValidationError> isValid(final boolean firstOnly) { loadFields(); getFlags(); getBinaryAttributes(); return super.isValid(firstOnly); }
Source:
private void updateOrderLabel() { ECTransition transition = getModel(); if (null != transition.getSource()) { if (1 < transition.getSource().getOutTransitions().size()) { int i = 1 + transition.getSource().getOutTransitions().indexOf(transition); getConnectionFigure().setTransitionOder(Integer.toString(i)); } else { getConnectionFigure().setTransitionOder(""); } } }

Target:
private void updateOrderLabel() { ECTransition transition = getModel(); if (null != transition.getSource()) { if (1 < transition.getSource().getOutTransitions().size()) { int i = 1 + transition.getSource().getOutTransitions().indexOf(transition); getConnectionFigure().setTransitionOrder(Integer.toString(i)); } else { getConnectionFigure().setTransitionOrder(""); } } }
Source:
public void expunge(List<Long> knownDeletedUids) throws MessagingException { if (knownDeletedUids == null || knownDeletedUids.isEmpty()) { return; } open(OPEN_MODE_RW); checkOpen(); try { if (connection.isUidPlusCapable()) { UidExpungeCommand uidExpungeCommand = new UidExpungeCommand.Builder() .idSet(knownDeletedUids) .build(); uidExpungeCommand.execute(connection, this); } else { UidSearchCommand searchCommand = new UidSearchCommand.Builder() .requiredFlags(Collections.singleton(Flag.DELETED)) .useUids(true, true) .idSet(knownDeletedUids) .build(); List<Long> unknownDeletedUids = searchCommand.execute(connection, this).getNumbers(); setFlagsInternal(unknownDeletedUids, Collections.singleton(Flag.DELETED), false); executeSimpleCommand("EXPUNGE"); setFlagsInternal(unknownDeletedUids, Collections.singleton(Flag.DELETED), true); } } catch (IOException ioe) { throw ioExceptionHandler(connection, ioe); } }

Target:
public void expunge(List<Long> knownDeletedUids) throws MessagingException { if (knownDeletedUids == null || knownDeletedUids.isEmpty()) { return; } open(OPEN_MODE_RW); checkOpen(); try { if (connection.isUidPlusCapable()) { UidExpungeCommand uidExpungeCommand = new UidExpungeCommand.Builder() .idSet(knownDeletedUids) .build(); uidExpungeCommand.execute(connection, this); } else { expungeWithoutUidPlus(knownDeletedUids); } } catch (IOException ioe) { throw ioExceptionHandler(connection, ioe); } }
Source:
public void executeCommand() { if (getParameters().getTopImage().getSize() == getParameters().getBaseImage().getSize()) { log.debug("No image size update required"); setSucceeded(true); setCommandStatus(CommandStatus.SUCCEEDED); return; } if (isBaseRawBlock()) { Guid taskId = persistAsyncTaskPlaceHolder(getParameters().getParentCommand()); VDSReturnValue vdsReturnValue = extendImageSize(); if (vdsReturnValue != null && vdsReturnValue.getCreationInfo() != null) { getParameters().setVdsmTaskIds(new ArrayList<Guid>()); Guid result = createTask(taskId, vdsReturnValue.getCreationInfo(), getParameters().getParentCommand(), VdcObjectType.Storage, getParameters().getStorageDomainId()); getReturnValue().getInternalVdsmTaskIdList().add(result); getReturnValue().getVdsmTaskIdList().add(result); getParameters().getVdsmTaskIds().add(result); setSucceeded(vdsReturnValue.getSucceeded()); persistCommand(getParameters().getParentCommand(), true); log.info("Successfully started task to extend base image size in preparation for live merge"); } else { log.error("Failed to extend base image for live merge"); setSucceeded(false); setCommandStatus(CommandStatus.FAILED); } } else { updateSizeInDb(); setSucceeded(true); setCommandStatus(CommandStatus.SUCCEEDED); } }

Target:
public void executeCommand() { if (getParameters().getTopImage().getSize() == getParameters().getBaseImage().getSize()) { log.debug("No image size update required"); setSucceeded(true); setCommandStatus(CommandStatus.SUCCEEDED); return; } if (isBaseRawBlock()) { extendImageSize(); } else { updateSizeInDb(); setCommandStatus(CommandStatus.SUCCEEDED); } setSucceeded(true); }
Source:
public Map<String, Node> get(String uri) { GetResponse response; Map<String, Node> result = new HashMap<>(); if(uri != null) { response = client.prepareGet(INDEX_NAME, docDef.getEntityField(), uri).get(); if(response != null && !response.isSourceEmpty()) { String entityField = response.getId(); Node entity = NodeFactory.createURI(entityField) ; result.put(docDef.getEntityField(), entity); for (String field: docDef.fields()) { GetField fieldResponse = response.getField(field); if(fieldResponse == null || fieldResponse.getValue() == null) { continue; } if(fieldResponse instanceof List<?>) { continue; } String fieldValue = (String)fieldResponse.getValue(); Node fieldNode = NodeFactoryExtra.createLiteralNode(fieldValue, null, null); result.put(field, fieldNode); } } } return result; }

Target:
public Map<String, Node> get(String uri) { GetResponse response; Map<String, Node> result = new HashMap<>(); if(uri != null) { response = client.prepareGet(indexName, docDef.getEntityField(), uri).get(); if(response != null && !response.isSourceEmpty()) { String entityField = response.getId(); Node entity = NodeFactory.createURI(entityField) ; result.put(docDef.getEntityField(), entity); Map<String, Object> source = response.getSource(); for (String field: docDef.fields()) { Object fieldResponse = source.get(field); if(fieldResponse == null) { continue; } else if(fieldResponse instanceof List<?>) { List<?> responseList = (List<?>)fieldResponse; if(responseList != null && responseList.size() > 0) { String fieldValue = (String)responseList.get(0); Node fieldNode = NodeFactoryExtra.createLiteralNode(fieldValue, null, null); result.put(field, fieldNode); } } } } } return result; }
Source:
public void statusUpdate(SchedulerDriver driver, TaskStatus status) { switch (status.getState()) { case TASK_STAGING: case TASK_STARTING: LOG.debug("Received status update: {}", taskStatusToString(status)); break; case TASK_RUNNING: LOG.info("Received status update: {}", taskStatusToString(status)); break; case TASK_FINISHED: case TASK_FAILED: case TASK_KILLED: case TASK_LOST: case TASK_ERROR: LOG.info("Received status update: {}", taskStatusToString(status)); break; default: LOG.warn("Received unrecognized status update: {}", taskStatusToString(status)); break; } }

Target:
public void statusUpdate(SchedulerDriver driver, TaskStatus status) { String msg = String.format("Received status update: %s", taskStatusToString(status)); switch (status.getState()) { case TASK_STAGING: case TASK_STARTING: LOG.debug(msg); break; case TASK_RUNNING: LOG.info(msg); break; case TASK_FINISHED: case TASK_FAILED: case TASK_KILLED: case TASK_LOST: case TASK_ERROR: LOG.info(msg); break; default: LOG.warn("Received unrecognized status update: {}", taskStatusToString(status)); break; } }
Source:
public void testAdd() throws ArrayIndexOutOfBoundsException { SizeLimitedVector slv = new SizeLimitedVector(10); slv.add("testString"); assertEquals(slv.getMaxSize(), 10); assertEquals(slv.get(0), "testString"); }

Target:
public void testAdd() { SizeLimitedVector slv = new SizeLimitedVector(10); slv.add("testString"); assertEquals(slv.getMaxSize(), 10); assertEquals(slv.get(0), "testString"); }
Source:
private boolean parentClassImplementsEquals(ClassTree tree) { Tree superClass = tree.superClass(); if (superClass != null) { TypeSymbol superClassSymbol = ((AbstractTypedTree) superClass).getSymbolType().getSymbol(); while (!superClassSymbol.getType().is("java.lang.Object")) { if (hasEqualsMethod(superClassSymbol)) { return true; } Type superClassType = superClassSymbol.getSuperclass(); if (superClassType == null) { break; } superClassSymbol = superClassType.getSymbol(); } } return false; }

Target:
private boolean parentClassImplementsEquals(ClassTree tree) { Tree superClass = tree.superClass(); if (superClass != null) { Type superClassType = ((AbstractTypedTree) superClass).getSymbolType(); while (!superClassType.getSymbol().getType().isTagged(Type.UNKNOWN) && !superClassType.is("java.lang.Object")) { TypeSymbol superClassSymbol = superClassType.getSymbol(); if (hasEqualsMethod(superClassSymbol)) { return true; } superClassType = superClassSymbol.getSuperclass(); } } return false; }
Source:
public static<T> T loadFromConf(Configuration conf, String dataKey) throws IOException { String classKey = dataKey + "._class"; String className = conf.get(classKey); try { return (T) DefaultStringifier.load(conf, dataKey, ClassLoadingUtils.loadClass(className)); } catch (Exception ex) { throw new IOException(ex); } }

Target:
public static<T> T loadFromConf(Configuration conf, String dataKey) throws IOException { String classKey = dataKey + "._class"; String className = conf.get(classKey); try { return (T) DefaultStringifier.load(conf, dataKey, ClassLoadingUtils.loadClass(className)); } catch (IOException | ClassNotFoundException ex) { throw new IOException(ex); } }
Source:
public void testThatCodeForDecoratedMapperWorks() { Target mappedTarget = DecoratedUsesPlainMapper.INSTANCE.toTarget( this.source ); assertThat( mappedTarget ).isNotNull(); assertThat( mappedTarget ).isEqualTo( this.target ); }

Target:
public void testThatCodeForDecoratedMapperWorks() { Target mappedTarget = DecoratedUsesPlainMapper.INSTANCE.toTarget( this.source ); assertThatSourceWasMappedCorrectly( mappedTarget ); }
Source:
public static boolean isInstanceSetup(HelixZkClient zkclient, String clusterName, String instanceName, InstanceType type) { if (type == InstanceType.PARTICIPANT || type == InstanceType.CONTROLLER_PARTICIPANT) { ArrayList<String> requiredPaths = new ArrayList<>(); requiredPaths.add(PropertyPathBuilder.instanceConfig(clusterName, instanceName)); requiredPaths.add(PropertyPathBuilder.instanceMessage(clusterName, instanceName)); requiredPaths.add(PropertyPathBuilder.instanceCurrentState(clusterName, instanceName)); requiredPaths.add(PropertyPathBuilder.instanceCustomizedState(clusterName, instanceName)); requiredPaths.add(PropertyPathBuilder.instanceStatusUpdate(clusterName, instanceName)); requiredPaths.add(PropertyPathBuilder.instanceError(clusterName, instanceName)); boolean isValid = true; for (String path : requiredPaths) { if (!zkclient.exists(path)) { isValid = false; logger.error("Invalid instance setup, missing znode path: {}", path); } } if (isValid) { String historyPath = PropertyPathBuilder.instanceHistory(clusterName, instanceName); if (!zkclient.exists(historyPath)) { zkclient.createPersistent(historyPath, true); } } return isValid; } return true; }

Target:
public static boolean isInstanceSetup(HelixZkClient zkclient, String clusterName, String instanceName, InstanceType type) { if (type == InstanceType.PARTICIPANT || type == InstanceType.CONTROLLER_PARTICIPANT) { ArrayList<String> requiredPaths = new ArrayList<>(); requiredPaths.add(PropertyPathBuilder.instanceConfig(clusterName, instanceName)); requiredPaths.add(PropertyPathBuilder.instanceMessage(clusterName, instanceName)); requiredPaths.add(PropertyPathBuilder.instanceCurrentState(clusterName, instanceName)); requiredPaths.add(PropertyPathBuilder.instanceStatusUpdate(clusterName, instanceName)); requiredPaths.add(PropertyPathBuilder.instanceError(clusterName, instanceName)); boolean isValid = true; for (String path : requiredPaths) { if (!zkclient.exists(path)) { isValid = false; logger.error("Invalid instance setup, missing znode path: {}", path); } } if (isValid) { String historyPath = PropertyPathBuilder.instanceHistory(clusterName, instanceName); if (!zkclient.exists(historyPath)) { zkclient.createPersistent(historyPath, true); } } return isValid; } return true; }
Source:
public void testAddObjectDepth2() { JsonNode n = new ObjectNode(JsonNodeFactory.instance); ((ObjectNode) n).set("o", new ObjectNode(JsonNodeFactory.instance)); n.add(JsonPointer.compile("/o/i"), ONE); assertEquals(1, n.at("/o/i").asInt()); }

Target:
public void testAddObjectDepth2() { ObjectNode n = objectMapper().createObjectNode(); n.set("o", n.objectNode()); n.add(JsonPointer.compile("/o/i"), n.numberNode(1)); assertEquals(1, n.at("/o/i").asInt()); }
Source:
public void createActivity(WorkspaceActivity activity) throws ConflictException, ServerException { try { doCreate(activity); } catch (IntegrityConstraintViolationException e) { throw new ServerException( String.format( "Can not create activity record since the specified workspace with " + "id '%s' does not exist.", activity.getWorkspaceId()), e); } catch (DuplicateKeyException e) { throw new ConflictException( "Activity record for workspace ID " + activity.getWorkspaceId() + " already exists.", e); } catch (RuntimeException e) { throw new ServerException(e.getLocalizedMessage(), e); } }

Target:
public void createActivity(WorkspaceActivity activity) throws ConflictException, ServerException { try { doCreate(activity); } catch (IntegrityConstraintViolationException e) { throw new ServerException( String.format( "Can not create activity record since the specified workspace with " + "id '%s' does not exist.", activity.getWorkspaceId()), e); } catch (DuplicateKeyException e) { throw new ConflictException( "Activity record for workspace ID " + activity.getWorkspaceId() + " already exists.", e); } catch (RuntimeException e) { throw new ServerException(e.getMessage(), e); } }
Source:
public Program saveProgram(Program program) throws APIException { if (program.getConcept() == null) { throw new APIException("Program.concept.required", (Object[]) null); } for (ProgramWorkflow workflow : program.getAllWorkflows()) { ensureProgramIsSet(workflow, program); if (!workflow.getProgram().equals(program)) { throw new APIException("Program.error.contains.ProgramWorkflow", new Object[] { workflow.getProgram() }); } for (ProgramWorkflowState state : workflow.getStates()) { ensureProgramWorkflowIsSet(state, workflow); } } return dao.saveProgram(program); }

Target:
public Program saveProgram(Program program) throws APIException { if (program.getConcept() == null) { throw new APIException("Program.concept.required", (Object[]) null); } for (ProgramWorkflow workflow : program.getAllWorkflows()) { if (workflow.getConcept() == null) { throw new APIException("ProgramWorkflow.concept.required", (Object[]) null); } ensureProgramIsSet(workflow, program); for (ProgramWorkflowState state : workflow.getStates()) { if (state.getConcept() == null || state.getInitial() == null || state.getTerminal() == null) { throw new APIException("ProgramWorkflowState.requires", (Object[]) null); } ensureProgramWorkflowIsSet(state, workflow); } } return dao.saveProgram(program); }
Source:
private void close() { LOG.info("ZkBackedTaskListProvider::Unsubscribing to the changes under the path " + _path); _zkclient.unsubscribeChildChanges(_path, this); _zkclient.unsubscribeDataChanges(_path, this); }

Target:
public void close() { LOG.info("ZkBackedTaskListProvider::Unsubscribing to the changes under the path " + _path); _zkclient.unsubscribeChildChanges(_path, this); _zkclient.unsubscribeDataChanges(_path, this); }
Source:
public void initialize() { BooleanBinding passwordIsEmpty = passwordField.textProperty().isEmpty(); BooleanBinding passwordsDiffer = passwordField.textProperty().isNotEqualTo(retypePasswordField.textProperty()); okButton.disableProperty().bind(passwordIsEmpty.or(passwordsDiffer)); EasyBind.subscribe(passwordField.textProperty(), this::checkPasswordStrength); strengthRater.setLocalization(localization); passwordStrengthShape.widthProperty().bind(EasyBind.map(passwordStrength, strengthRater::getWidth)); passwordStrengthShape.fillProperty().bind(EasyBind.map(passwordStrength, strengthRater::getStrengthColor)); passwordStrengthShape.strokeWidthProperty().bind(EasyBind.map(passwordStrength, strengthRater::getStrokeWidth)); passwordStrengthLabel.textProperty().bind(EasyBind.map(passwordStrength, strengthRater::getStrengthDescription)); }

Target:
public void initialize() { BooleanBinding passwordIsEmpty = passwordField.textProperty().isEmpty(); BooleanBinding passwordsDiffer = passwordField.textProperty().isNotEqualTo(retypePasswordField.textProperty()); okButton.disableProperty().bind(passwordIsEmpty.or(passwordsDiffer)); passwordStrength.bind(EasyBind.map(passwordField.textProperty(), strengthRater::computeRate)); passwordStrengthShape.widthProperty().bind(EasyBind.map(passwordStrength, strengthRater::getWidth)); passwordStrengthShape.fillProperty().bind(EasyBind.map(passwordStrength, strengthRater::getStrengthColor)); passwordStrengthShape.strokeWidthProperty().bind(EasyBind.map(passwordStrength, strengthRater::getStrokeWidth)); passwordStrengthLabel.textProperty().bind(EasyBind.map(passwordStrength, strengthRater::getStrengthDescription)); }
Source:
public void testDefaultTemplateBuilder() throws IOException { Template defaultTemplate = view.getComputeService().templateBuilder().build(); assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), UBUNTU); assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true); assertEquals(defaultTemplate.getHardware().getName(), "micro"); assertEquals(getCores(defaultTemplate.getHardware()), 1.0d); }

Target:
public void testDefaultTemplateBuilder() throws IOException { Template defaultTemplate = view.getComputeService().templateBuilder().build(); String imageId = defaultTemplate.getImage().getId(); if (imageId.startsWith("ubuntu")) { assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), UBUNTU); } else if (imageId.startsWith("centos")) { assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), CENTOS); } assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true); assertEquals(defaultTemplate.getHardware().getName(), "micro"); assertEquals(getCores(defaultTemplate.getHardware()), 1.0d); }
Source:
public void putAndGetWrongProtobuf() throws Exception { String BASE_URL = String.format("http://localhost:%d/rest/v2/protobuf", restServer().getPort()); String errorProto = getResourceAsString("error.proto", getClass().getClassLoader()); ContentResponse response = client.newRequest(BASE_URL + "/error") .content(new StringContentProvider(errorProto)) .header("Content-type", "text/plain; charset=utf-8") .method(HttpMethod.PUT) .accept(APPLICATION_JSON_TYPE).send(); String validation = "java.lang.IllegalStateException:" + " Syntax error in error.proto at 3:8: unexpected label: messoge"; ResponseAssertion.assertThat(response).isBadRequest(); ResponseAssertion.assertThat(response).hasReturnedText("{validation:" + validation + "}"); checkListProtobufEndpointUrl("error.proto", validation); }

Target:
public void putAndGetWrongProtobuf() throws Exception { String BASE_URL = String.format("http://localhost:%d/rest/v2/schemas", restServer().getPort()); String errorProto = getResourceAsString("error.proto", getClass().getClassLoader()); ContentResponse response = addSchema("error", errorProto); String cause = "java.lang.IllegalStateException:" + " Syntax error in error.proto at 3:8: unexpected label: messoge"; ResponseAssertion.assertThat(response).isOk(); JsonNode jsonNode = new ObjectMapper().readTree(response.getContent()); assertEquals("error.proto", jsonNode.get("name").asText()); assertEquals("Schema error.proto has errors", jsonNode.get("error").get("message").asText()); assertEquals(cause, jsonNode.get("error").get("cause").asText()); response = client.newRequest(BASE_URL + "/error") .method(HttpMethod.GET) .accept(TEXT_PLAIN_TYPE).send(); ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasContentEqualToFile("error.proto"); checkListProtobufEndpointUrl("error.proto", cause); }
Source:
public void testNullUrl() { assertThrowsException(IllegalArgumentException.class, "url", new Runnable() { public void run() { WebRequestHandler request = new WebRequestHandler(); try { request.sendGet(null, null); } catch (IOException e) { fail(); } } }); }

Target:
public void testNullUrl() { assertThrowsException(IllegalArgumentException.class, "url", new ThrowableRunnable() { public void run() throws IOException { WebRequestHandler request = new WebRequestHandler(); request.sendGet(null, null); } }); }
Source:
public List<FeatureFlag> listAggregatedFeatureFlags(final Project project) { notNull(project, "project cannot be null!"); try { final FeatureFlags featureFlags = restTemplate.getForObject(AGGREGATED_FEATURE_FLAGS_TEMPLATE.expand(project.getId()), FeatureFlags.class); if (featureFlags == null) { throw new GoodDataException("empty response from API call"); } return featureFlags.getFeatureFlags(); } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Unable to list aggregated feature flags for project ID=" + project.getId(), e); } }

Target:
public List<FeatureFlag> listAggregatedFeatureFlags(final Project project) { notNull(project, "project"); try { final FeatureFlags featureFlags = restTemplate.getForObject(AGGREGATED_FEATURE_FLAGS_TEMPLATE.expand(project.getId()), FeatureFlags.class); if (featureFlags == null) { throw new GoodDataException("empty response from API call"); } return featureFlags.getFeatureFlags(); } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Unable to list aggregated feature flags for project ID=" + project.getId(), e); } }
Source:
public void putUnlessExists(final TableReference tableRef, final Map<Cell, byte[]> values) throws KeyAlreadyExistsException { try { Optional<KeyAlreadyExistsException> failure = clientPool.runWithRetry(client -> { for (Entry<Cell, byte[]> e : values.entrySet()) { CheckAndSetRequest request = CheckAndSetRequest.newCell(tableRef, e.getKey(), e.getValue()); CASResult casResult = executeCheckAndSet(client, request); if (!casResult.isSuccess()) { return Optional.of(new KeyAlreadyExistsException( String.format("The row in table %s already exists.", tableRef.getQualifiedName()), ImmutableList.of(e.getKey()))); } } clientPool.markWritesForTable(values, tableRef); return null; }); failure.ifPresent(exception -> { throw exception; }); } catch (KeyAlreadyExistsException e) { throw e; } catch (Exception e) { throw QosAwareThrowables.unwrapAndThrowRateLimitExceededOrAtlasDbDependencyException(e); } }

Target:
public void putUnlessExists(final TableReference tableRef, final Map<Cell, byte[]> values) throws KeyAlreadyExistsException { try { Optional<KeyAlreadyExistsException> failure = clientPool.runWithRetry(client -> { for (Entry<Cell, byte[]> e : values.entrySet()) { CheckAndSetRequest request = CheckAndSetRequest.newCell(tableRef, e.getKey(), e.getValue()); CASResult casResult = executeCheckAndSet(client, request); if (!casResult.isSuccess()) { return Optional.of(new KeyAlreadyExistsException( String.format("The row in table %s already exists.", tableRef.getQualifiedName()), ImmutableList.of(e.getKey()))); } } clientPool.markWritesForTable(values, tableRef); return Optional.empty(); }); failure.ifPresent(exception -> { throw exception; }); } catch (KeyAlreadyExistsException e) { throw e; } catch (Exception e) { throw QosAwareThrowables.unwrapAndThrowRateLimitExceededOrAtlasDbDependencyException(e); } }
Source:
public void printTrader() { System.out.println("Trader Name: " + name); System.out.println("====================="); System.out.println("Cash: " + cashInHand); System.out.println("Stocks Owned: "); for (Stock s : position) { if (!s.getSymbol().equals("")) System.out.println(s.getSymbol()); } System.out.println("Stocks Desired: "); for (Order o : ordersPlaced) { o.printOrder(); } System.out.println("+++++++++++++++++++++"); System.out.println("+++++++++++++++++++++"); }

Target:
public void printTrader() { System.out.println("Trader Name: " + name); System.out.println("====================="); System.out.println("Cash: " + cashInHand); System.out.println("Stocks Owned: "); for (Stock stock : position) { if (!stock.getSymbol().equals("")) System.out.println(stock.getSymbol()); } System.out.println("Stocks Desired: "); for (Order order : ordersPlaced) { order.printOrder(); } System.out.println("+++++++++++++++++++++"); System.out.println("+++++++++++++++++++++"); }
Source:
public int hashCode() { return Objects.hashCode(pointer, size); }

Target:
public int hashCode() { return Longs.hashCode(pointer); }
Source:
public List<IgniteModel<I, O>> submodels() { return new ArrayList<>(submodels); }

Target:
public List<IgniteModel<I, O>> submodels() { return Collections.unmodifiableList(submodels); }
Source:
public void execute(FunctionContext<Object[]> context) { InternalLocator locator = getLocator(); Object[] args = context.getArguments(); String group = (String) args[0]; String jarName = (String) args[1]; RemoteInputStream result = null; if (locator != null && group != null && jarName != null) { InternalConfigurationPersistenceService sharedConfig = locator.getConfigurationPersistenceService(); if (sharedConfig != null) { SystemManagementService managementService = getExistingManagementService(context); ManagementAgent managementAgent = managementService.getManagementAgent(); if (managementAgent == null) { throw new IllegalStateException( "Failed to download jar because JMX Management agent is not available. Please ensure geode property jmx-manager is set to true."); } RemoteInputStreamServer istream = null; try { File jarFile = sharedConfig.getPathToJarOnThisLocator(group, jarName).toFile(); if (jarFile.lastModified() > System.currentTimeMillis() - 1000) { Thread.sleep(1000); } RemoteStreamExporter exporter = managementAgent.getRemoteStreamExporter(); istream = new SimpleRemoteInputStream(new BufferedInputStream(new FileInputStream(jarFile))); result = exporter.export(istream); istream = null; } catch (Exception e) { logger.error(e); throw new IllegalStateException(e.getMessage()); } finally { if (istream != null) { istream.close(); } } } } context.getResultSender().lastResult(result); }

Target:
public void execute(FunctionContext<Object[]> context) { InternalLocator locator = getLocator(); Object[] args = context.getArguments(); String group = (String) args[0]; String jarName = (String) args[1]; RemoteInputStream result = null; if (locator != null && group != null && jarName != null) { InternalConfigurationPersistenceService sharedConfig = locator.getConfigurationPersistenceService(); if (sharedConfig != null) { SystemManagementService managementService = getExistingManagementService(context); ManagementAgent managementAgent = managementService.getManagementAgent(); if (managementAgent == null) { throw new IllegalStateException( "Failed to download jar because JMX Management agent is not available. Please ensure geode property jmx-manager is set to true."); } RemoteInputStreamServer istream = null; try { File jarFile = sharedConfig.getPathToJarOnThisLocator(group, jarName).toFile(); RemoteStreamExporter exporter = managementAgent.getRemoteStreamExporter(); istream = new SimpleRemoteInputStream(new BufferedInputStream(new FileInputStream(jarFile))); result = exporter.export(istream); istream = null; } catch (Exception e) { logger.error(e); throw new IllegalStateException(e.getMessage()); } finally { if (istream != null) { istream.close(); } } } } context.getResultSender().lastResult(result); }
Source:
public DeviceInactivePage generatePage() { final Jedis jedis = jedisPool.getResource(); final Set<Tuple> redisSenses = new TreeSet<>(); final Long afterCursor = (afterTimestamp.isPresent()) ? afterTimestamp.get() : Long.MIN_VALUE; final Long beforeCursor = (beforeTimestamp.isPresent()) ? beforeTimestamp.get() : Long.MAX_VALUE; try { redisSenses.addAll(jedis.zrangeByScoreWithScores(deviceType, afterCursor, beforeCursor, 0, maxItemsPerPage)); } catch (Exception e) { LOGGER.error("Failed to retrieve list of devices", e.getMessage()); } finally { jedisPool.returnResource(jedis); } final List<DeviceInactive> inactiveDevices = extractDevicesList(redisSenses); final DeviceInactivePage formattedPage = internalFormatPage(afterCursor, beforeCursor, inactiveDevices); return formattedPage; }

Target:
public DeviceInactivePage generatePage() { final Jedis jedis = jedisPool.getResource(); final Set<Tuple> redisSenses = new TreeSet<>(); final Long afterCursor = (afterTimestamp.isPresent()) ? afterTimestamp.get() : Long.MIN_VALUE; final Long beforeCursor = (beforeTimestamp.isPresent()) ? beforeTimestamp.get() : Long.MAX_VALUE; try { redisSenses.addAll(jedis.zrangeByScoreWithScores(deviceType, afterCursor, beforeCursor, 0, maxItemsPerPage)); } catch (Exception e) { LOGGER.error("Failed to retrieve list of devices {}", e.getMessage()); } finally { jedisPool.returnResource(jedis); } final List<DeviceInactive> inactiveDevices = extractDevicesList(redisSenses); final DeviceInactivePage formattedPage = internalFormatPage(afterCursor, beforeCursor, inactiveDevices); return formattedPage; }
Source:
public CliCommand init(final Arguments args) throws Exception { bucketName = args.getBucket(); if (bucketName == null) { CommandExceptionFactory.getInstance().handleException(this.getClass(). getSimpleName(), new MissingOptionException("The delete bucket command requires '-b' to be set."), true); } force = args.isForce(); return this; }

Target:
public CliCommand init(final Arguments args) throws Exception { bucketName = args.getBucket(); if (bucketName == null) { throw new MissingOptionException("The delete bucket command requires '-b' to be set."); } force = args.isForce(); return this; }
Source:
public void deleteAndWaitForCompletion(String workflow, long timeout) throws InterruptedException { delete(workflow); long endTime = System.currentTimeMillis() + timeout; BaseDataAccessor baseDataAccessor = _accessor.getBaseDataAccessor(); PropertyKey.Builder keyBuilder = _accessor.keyBuilder(); String workflowConfigPath = keyBuilder.resourceConfig(workflow).getPath(); String workflowContextPath = keyBuilder.workflowContext(workflow).getPath(); while (System.currentTimeMillis() <= endTime) { if (baseDataAccessor.exists(workflowConfigPath, AccessOption.PERSISTENT) || baseDataAccessor.exists(workflowContextPath, AccessOption.PERSISTENT)) { Thread.sleep(1000); } else { return; } } StringBuilder failed = new StringBuilder(); if (baseDataAccessor.exists(workflowConfigPath, AccessOption.PERSISTENT)) { failed.append("WorkflowConfig "); } if (baseDataAccessor.exists(workflowContextPath, AccessOption.PERSISTENT)) { failed.append("WorkflowContext "); } throw new HelixException( String.format( "Failed to delete the workflow/queue %s within %d milliseconds. " + "The following components still remain: %s", workflow, timeout, failed.toString())); }

Target:
public void deleteAndWaitForCompletion(String workflow, long timeout) throws InterruptedException { delete(workflow); long endTime = System.currentTimeMillis() + timeout; BaseDataAccessor baseDataAccessor = _accessor.getBaseDataAccessor(); PropertyKey.Builder keyBuilder = _accessor.keyBuilder(); String idealStatePath = keyBuilder.idealStates(workflow).getPath(); String workflowConfigPath = keyBuilder.resourceConfig(workflow).getPath(); String workflowContextPath = keyBuilder.workflowContext(workflow).getPath(); while (System.currentTimeMillis() <= endTime) { if (baseDataAccessor.exists(idealStatePath, AccessOption.PERSISTENT) || baseDataAccessor.exists(workflowConfigPath, AccessOption.PERSISTENT) || baseDataAccessor.exists(workflowContextPath, AccessOption.PERSISTENT)) { Thread.sleep(1000); } else { return; } } StringBuilder failed = new StringBuilder(); if (baseDataAccessor.exists(idealStatePath, AccessOption.PERSISTENT)) { failed.append("IdealState "); } if (baseDataAccessor.exists(workflowConfigPath, AccessOption.PERSISTENT)) { failed.append("WorkflowConfig "); } if (baseDataAccessor.exists(workflowContextPath, AccessOption.PERSISTENT)) { failed.append("WorkflowContext "); } throw new HelixException( String.format( "Failed to delete the workflow/queue %s within %d milliseconds. " + "The following components still remain: %s", workflow, timeout, failed.toString())); }
Source:
public Function<MultiValueMap<K, V>, MultiValueMap<K, V>> finisher() { return it -> it; }

Target:
public Function<MultiValueMap<K, V>, MultiValueMap<K, V>> finisher() { return Function.identity(); }
Source:
public Table(@Nonnull final String namespace, @Nonnull final String fullyQualifiedTableName, @Nonnull final V valueSchema, @Nullable final M metadataSchema, @Nonnull final CorfuRuntime corfuRuntime, @Nonnull final ISerializer serializer) { this.corfuRuntime = corfuRuntime; this.namespace = namespace; this.fullyQualifiedTableName = fullyQualifiedTableName; if (metadataSchema != null) { this.metadataOptions = MetadataOptions.builder() .metadataEnabled(true) .defaultMetadataInstance(metadataSchema) .build(); } else { this.metadataOptions = MetadataOptions.<M>builder().build(); } this.corfuTable = corfuRuntime.getObjectsView().build() .setTypeToken(new TypeToken<CorfuTable<K, CorfuRecord<V, M>>>() { }) .setStreamName(this.fullyQualifiedTableName) .setSerializer(serializer) .setArguments(new ProtobufIndexer(valueSchema)) .open(); }

Target:
public Table(@Nonnull final String namespace, @Nonnull final String fullyQualifiedTableName, @Nonnull final V valueSchema, @Nullable final M metadataSchema, @Nonnull final CorfuRuntime corfuRuntime, @Nonnull final ISerializer serializer) { this.corfuRuntime = corfuRuntime; this.namespace = namespace; this.fullyQualifiedTableName = fullyQualifiedTableName; this.metadataOptions = Optional.ofNullable(metadataSchema) .map(schema -> MetadataOptions.builder() .metadataEnabled(true) .defaultMetadataInstance(schema) .build()) .orElse(MetadataOptions.builder().build()); this.corfuTable = corfuRuntime.getObjectsView().build() .setTypeToken(CorfuTable.<K, CorfuRecord<V, M>>getTableType()) .setStreamName(this.fullyQualifiedTableName) .setSerializer(serializer) .setArguments(new ProtobufIndexer(valueSchema)) .open(); }
Source:
private void initialize() { executeVoid( String.format( "CREATE TABLE IF NOT EXISTS %s (seq BIGINT, val BLOB, CONSTRAINT pk_%s PRIMARY KEY (seq))", logNamespace, logNamespace)); }

Target:
private void initialize() { execute(dao -> dao.createTable(namespace)); }
Source:
public void checkAttributeSemantics(PerunSessionImpl sess, Group group, Attribute attribute) throws WrongReferenceAttributeValueException { if (attribute.getValue() == null) throw new WrongReferenceAttributeValueException(attribute, "Attribute collectionID cannot be null."); if (attribute.valueAsString().isEmpty()) { throw new WrongReferenceAttributeValueException(attribute, "Attribute collectionID cannot be empty."); } }

Target:
public void checkAttributeSemantics(PerunSessionImpl sess, Group group, Attribute attribute) throws WrongReferenceAttributeValueException { if (attribute.getValue() == null) throw new WrongReferenceAttributeValueException(attribute, "Attribute collectionID cannot be null."); }
Source:
public static synchronized void setMetricRegistries(MetricRegistry metricRegistry, TaggedMetricRegistry taggedMetricRegistry) { if (!metricRegistry.equals(metrics.get())) { log.warn("The MetricsRegistry was re-set to a different value: the previous registry will be ignored" + " and the metrics will be registered on the new one."); } if (!taggedMetricRegistry.equals(taggedMetrics.get())) { log.warn("The TaggedMetricsRegistry was re-set to a different value: the previous registry will be ignored" + " and the metrics will be registered on the new one."); } metrics.set(Preconditions.checkNotNull(metricRegistry, "Metric registry cannot be null")); taggedMetrics.set(Preconditions.checkNotNull(taggedMetricRegistry, "Tagged Metric registry cannot be null")); }

Target:
public static synchronized void setMetricRegistries(MetricRegistry metricRegistry, TaggedMetricRegistry taggedMetricRegistry) { if (metricRegistry != metrics.get()) { log.warn("The MetricsRegistry was re-set to a different value: the previous registry will be ignored" + " and metrics may be lost."); } if (taggedMetricRegistry != taggedMetrics.get()) { log.warn("The TaggedMetricsRegistry was re-set to a different value: the previous registry will be ignored" + " and metrics may be lost."); } metrics.set(Preconditions.checkNotNull(metricRegistry, "Metric registry cannot be null")); taggedMetrics.set(Preconditions.checkNotNull(taggedMetricRegistry, "Tagged Metric registry cannot be null")); }
Source:
public List<String> getChildren(String path, Stat stat, Watcher watcher) throws KeeperException.NoNodeException { DataNode n = nodes.get(path); if (n == null) { throw new KeeperException.NoNodeException(); } List<String> children; synchronized (n) { if (stat != null) { n.copyStat(stat); } children = new ArrayList<String>(n.getChildren()); if (watcher != null) { childWatches.addWatch(path, watcher); } } int bytes = 0; bytes = children.stream().mapToInt(child -> child.length()).sum(); updateReadStat(path, bytes); return children; }

Target:
public List<String> getChildren(String path, Stat stat, Watcher watcher) throws KeeperException.NoNodeException { DataNode n = nodes.get(path); if (n == null) { throw new KeeperException.NoNodeException(); } List<String> children; synchronized (n) { if (stat != null) { n.copyStat(stat); } children = new ArrayList<String>(n.getChildren()); if (watcher != null) { childWatches.addWatch(path, watcher); } } int bytes = 0; for (String child : children) { bytes += child.length(); } updateReadStat(path, bytes); return children; }