auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public NewAgileSprint createSprint(NewAgileSprint newSprint) { List<String> names = new LinkedList<String>(); if (Strings.isValid(newSprint.getName())) { names.add(newSprint.getName()); } names.addAll(newSprint.getNames()); if (names.isEmpty()) { throw new OseeArgumentException("name is not valid"); } if (newSprint.getTeamUuid() <= 0) { throw new OseeArgumentException("teamUuid is not valid"); } NewAgileSprint created = null; for (String name : names) { String guid = newSprint.getGuid(); if (guid == null) { guid = GUID.create(); } IAgileSprint sprint = atsServer.getAgileService().createAgileSprint(newSprint.getTeamUuid(), name, guid); created = new NewAgileSprint(); created.setGuid(sprint.getGuid()); created.setName(sprint.getName()); created.setUuid(sprint.getId()); created.setTeamUuid(sprint.getTeamUuid()); created.setActive(sprint.isActive()); } return created; }

Target:
public NewAgileSprint createSprint(NewAgileSprint newSprint) { List<String> names = new LinkedList<String>(); if (Strings.isValid(newSprint.getName())) { names.add(newSprint.getName()); } names.addAll(newSprint.getNames()); if (names.isEmpty()) { throw new OseeWebApplicationException(Status.BAD_REQUEST, "name is not valid"); } if (newSprint.getTeamUuid() <= 0) { throw new OseeWebApplicationException(Status.BAD_REQUEST, "teamUuid is not valid"); } NewAgileSprint created = null; for (String name : names) { String guid = newSprint.getGuid(); if (guid == null) { guid = GUID.create(); } IAgileSprint sprint = atsServer.getAgileService().createAgileSprint(newSprint.getTeamUuid(), name, guid); created = new NewAgileSprint(); created.setGuid(sprint.getGuid()); created.setName(sprint.getName()); created.setUuid(sprint.getId()); created.setTeamUuid(sprint.getTeamUuid()); created.setActive(sprint.isActive()); } return created; }
Source:
public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() != 1) { throw new IAE("function '%s' needs 1 argument", name()); } final String arg = args.get(0).eval(bindings).asString(); return ExprEval.of(Strings.nullToEmpty(arg).trim()); }

Target:
public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() != 1) { throw new IAE("Function[%s] needs 1 argument", name()); } final String arg = args.get(0).eval(bindings).asString(); return ExprEval.of(Strings.nullToEmpty(arg).trim()); }
Source:
@CheckForNull String getUserData() { Executor executor = Executor.currentExecutor(); if (executor != null) { Queue.Executable currentExecutable = executor.getCurrentExecutable(); if (currentExecutable != null) { Config userData = ConfigFiles.getByIdOrNull((Run<?, ?>) currentExecutable, getEffectiveSlaveOptions().getUserDataId()); return (userData == null || userData.content.isEmpty()) ? null : userData.content ; } } return null; }

Target:
@CheckForNull String getUserData() { String userDataId = Util.fixEmpty(getEffectiveSlaveOptions().getUserDataId()); if(userDataId != null) { Config userData = ConfigFiles.getByIdOrNull(Jenkins.getActiveInstance(), userDataId); return (userData == null || userData.content.isEmpty()) ? null : userData.content ; } return null; }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initializeFacebookSdk(); setContentView(R.layout.activity_project); currentFragmentPosition = FRAGMENT_SCENES; if (getIntent() != null && getIntent().hasExtra(Constants.PROJECT_OPENED_FROM_PROJECTS_LIST)) { setReturnToProjectsList(true); } if (savedInstanceState == null) { Bundle bundle = this.getIntent().getExtras(); if (bundle != null) { currentFragmentPosition = bundle.getInt(EXTRA_FRAGMENT_POSITION, FRAGMENT_SCENES); } } Project project = ProjectManager.getInstance().getCurrentProject(); if (project.getSceneList() == null || project.getSceneList().size() == 1) { currentFragmentPosition = FRAGMENT_SPRITES; } FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); updateCurrentFragment(currentFragmentPosition, fragmentTransaction); fragmentTransaction.commit(); showLegoInfoFragmentIfNeeded(this.getFragmentManager()); }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initializeFacebookSdk(); setContentView(R.layout.activity_project); currentFragmentPosition = FRAGMENT_SCENES; if (getIntent() != null && getIntent().hasExtra(Constants.PROJECT_OPENED_FROM_PROJECTS_LIST)) { setReturnToProjectsList(true); } if (savedInstanceState == null) { Bundle bundle = this.getIntent().getExtras(); if (bundle != null) { currentFragmentPosition = bundle.getInt(EXTRA_FRAGMENT_POSITION, FRAGMENT_SCENES); } } List<Scene> scenes = ProjectManager.getInstance().getCurrentProject().getSceneList(); if (scenes == null || scenes.size() == 1) { currentFragmentPosition = FRAGMENT_SPRITES; } FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); updateCurrentFragment(currentFragmentPosition, fragmentTransaction); fragmentTransaction.commit(); showLegoInfoFragmentIfNeeded(this.getFragmentManager()); }
Source:
public final ValidationErrors validateModel(final Collection<DataSample> model) { final ValidationErrors validationErrors = new ValidationErrors(); int recordNumber = 2; for (final DataSample record : model) { final Set<ConstraintViolation<DataSample>> violations = this.validator.validate(record); for (final ConstraintViolation<DataSample> violation : violations) { int errorCode = 0; String errorType = "Unknown"; final Matcher errorKeyMatcher = ERROR_KEY_PATTERN.matcher(violation.getMessageTemplate()); if (errorKeyMatcher.matches()) { errorCode = Integer.parseInt(errorKeyMatcher.group("errorCode")); errorType = errorKeyMatcher.group("errorType"); } ValidationError error = null; if (errorType.equals(COMBINATION)) { error = new DependencyValidationError( (record.getReturnType() != null) ? record.getReturnType().getEntity().getName() : null, null, (record.getParameter() != null) ? record.getParameter().getEntity().getName() : null, (record.getUnit() != null) ? record.getUnit().getEntity().getName() : null ); } else { error = new ValidationError(); } String errorValue = null; FieldDefinition definition = getFieldForViolation(model, violation); if (violation.getInvalidValue() instanceof String) { errorValue = (String) violation.getInvalidValue(); } else if (violation.getInvalidValue() instanceof FieldValue) { errorValue = ((FieldValue) violation.getInvalidValue()).getInputValue(); } if (definition != null) { error.setFieldName(definition.getName()); error.setDefinition(definition.getDescription()); } error.setErrorValue(errorValue); error.setLineNumber(recordNumber); error.setErrorMessage(violation.getMessage()); error.setErrorCode(errorCode); error.setErrorType(errorType); validationErrors.addError(error); } recordNumber++; } return validationErrors; }

Target:
public final ValidationErrors validateModel(final Collection<DataSample> model) { final ValidationErrors validationErrors = new ValidationErrors(); int recordNumber = 2; for (final DataSample record : model) { final Set<ConstraintViolation<DataSample>> violations = this.validator.validate(record); for (final ConstraintViolation<DataSample> violation : violations) { int errorCode = 0; String errorType = "Unknown"; final Matcher errorKeyMatcher = ERROR_KEY_PATTERN.matcher(violation.getMessageTemplate()); if (errorKeyMatcher.matches()) { errorCode = Integer.parseInt(errorKeyMatcher.group("errorCode")); errorType = errorKeyMatcher.group("errorType"); } List<FieldDefinition> fieldsForValidation = getFieldsForViolation(violation); ValidationError.ErrorData[] errorData = getErrorDataFromFields(record, fieldsForValidation); ValidationError error = new ValidationError(); error.setErrorData(errorData); error.setLineNumber(recordNumber); error.setErrorMessage(violation.getMessage()); error.setErrorCode(errorCode); error.setErrorType(errorType); validationErrors.addError(error); } recordNumber++; } return validationErrors; }
Source:
private void initializePlayer() { if (player == null) { TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(BANDWIDTH_METER); trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory); player = ExoPlayerFactory.newSimpleInstance(getContext(), trackSelector, new DefaultLoadControl()); player.addListener(this); player.setMetadataOutput(this); exoPlayerView.setPlayer(player); audioBecomingNoisyReceiver.setListener(this); playerNeedsSource = true; PlaybackParameters params = new PlaybackParameters(rate, 1f); player.setPlaybackParameters(params); } setPlayWhenReady(!isPaused); if (playerNeedsSource && srcUri != null) { MediaSource mediaSource = buildMediaSource(srcUri, extension); mediaSource = repeat ? new LoopingMediaSource(mediaSource) : mediaSource; boolean haveResumePosition = resumeWindow != C.INDEX_UNSET; if (haveResumePosition) { player.seekTo(resumeWindow, resumePosition); } player.prepare(mediaSource, !haveResumePosition, false); playerNeedsSource = false; eventEmitter.loadStart(); loadVideoStarted = true; } }

Target:
private void initializePlayer() { if (player == null) { TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(BANDWIDTH_METER); trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory); player = ExoPlayerFactory.newSimpleInstance(getContext(), trackSelector, new DefaultLoadControl()); player.addListener(this); player.setMetadataOutput(this); exoPlayerView.setPlayer(player); audioBecomingNoisyReceiver.setListener(this); setPlayWhenReady(!isPaused); playerNeedsSource = true; PlaybackParameters params = new PlaybackParameters(rate, 1f); player.setPlaybackParameters(params); } if (playerNeedsSource && srcUri != null) { MediaSource mediaSource = buildMediaSource(srcUri, extension); mediaSource = repeat ? new LoopingMediaSource(mediaSource) : mediaSource; boolean haveResumePosition = resumeWindow != C.INDEX_UNSET; if (haveResumePosition) { player.seekTo(resumeWindow, resumePosition); } player.prepare(mediaSource, !haveResumePosition, false); playerNeedsSource = false; eventEmitter.loadStart(); loadVideoStarted = true; } }
Source:
public OVirtNodeUpgrade(VDS vds, String iso) { _vds = vds; _iso = Path.Combine(Config.resolveOVirtISOsRepositoryPath(), iso); _messages = new InstallerMessages(_vds); _thread = new Thread(this); _dialog = new EngineSSHDialog(); }

Target:
public OVirtNodeUpgrade(VDS vds, String iso) { _vds = vds; _iso = Path.Combine(Config.resolveOVirtISOsRepositoryPath(), iso); _messages = new InstallerMessages(_vds); _dialog = new EngineSSHDialog(); _thread = new Thread( new Runnable() { @Override public void run() { _threadMain(); } }, "OVirtNodeUpgrade" ); }
Source:
public RetryOptions build() { return new RetryOptions( options.retriesEnabled, options.allowRetriesWithoutTimestamp, options.initialBackoffMillis, options.backoffMultiplier, options.maxElapsedBackoffMillis, options.streamingBufferSize, options.readPartialRowTimeoutMillis, options.maxScanTimeoutRetries, ImmutableSet.copyOf(options.statusToRetryOn)); }

Target:
public RetryOptions build() { return options; }
Source:
private void updateAccessPoints() { final int wifiState = mWifiManager.getWifiState(); switch (wifiState) { case WifiManager.WIFI_STATE_ENABLED: final Collection<AccessPoint> accessPoints = constructAccessPoints(); getPreferenceScreen().removeAll(); if (mInXlSetupWizard) { ((WifiSettingsForSetupWizardXL)getActivity()).onAccessPointsUpdated( getPreferenceScreen(), accessPoints); } else { if(accessPoints.size() == 0) addMessagePreference(R.string.wifi_empty_list_wifi_on); for (AccessPoint accessPoint : accessPoints) { getPreferenceScreen().addPreference(accessPoint); } } break; case WifiManager.WIFI_STATE_ENABLING: getPreferenceScreen().removeAll(); break; case WifiManager.WIFI_STATE_DISABLING: addMessagePreference(R.string.wifi_stopping); break; case WifiManager.WIFI_STATE_DISABLED: addMessagePreference(R.string.wifi_empty_list_wifi_off); break; } }

Target:
private void updateAccessPoints() { final int wifiState = mWifiManager.getWifiState(); switch (wifiState) { case WifiManager.WIFI_STATE_ENABLED: final Collection<AccessPoint> accessPoints = constructAccessPoints(); getPreferenceScreen().removeAll(); if (mInXlSetupWizard) { ((WifiSettingsForSetupWizardXL)getActivity()).onAccessPointsUpdated( getPreferenceScreen(), accessPoints); } else { if(accessPoints.size() == 0) { addMessagePreference(R.string.wifi_empty_list_wifi_on); } for (AccessPoint accessPoint : accessPoints) { getPreferenceScreen().addPreference(accessPoint); } } break; case WifiManager.WIFI_STATE_ENABLING: getPreferenceScreen().removeAll(); break; case WifiManager.WIFI_STATE_DISABLING: addMessagePreference(R.string.wifi_stopping); break; case WifiManager.WIFI_STATE_DISABLED: addMessagePreference(R.string.wifi_empty_list_wifi_off); break; } }
Source:
public void addMessage(final Message m) { synchronized (lock) { if (m == null) { throw new IllegalArgumentException("Cannot add null message"); } if (isMessageLimitExceeded()) { LOGGER.log(Level.WARNING, "cannot add message to the system, limit of {0} messages exceeded." + "consider setting the ''messageLimit'' tunable.", messageLimit); throw new IllegalStateException("Cannot add message - message limit exceeded"); } if (expirationTimer == null) { expireMessages(); } AcceptedMessage acceptedMessage = new AcceptedMessage(m); addMessage(acceptedMessage); } }

Target:
public void addMessage(final Message m) { synchronized (lock) { if (m == null) { throw new IllegalArgumentException("Cannot add null message"); } if (isMessageLimitExceeded()) { LOGGER.log(Level.WARNING, "cannot add message to the system, " + "exceeded Configuration messageLimit of {0}", messageLimit); throw new IllegalStateException("Cannot add message - message limit exceeded"); } if (expirationTimer == null) { expireMessages(); } AcceptedMessage acceptedMessage = new AcceptedMessage(m); addMessage(acceptedMessage); } }
Source:
public Map<String, String> getOptions(@NonNull TaskAttribute attribute) { if (attribute.getId().equals(BugzillaRestCreateTaskSchema.getDefault().TARGET_MILESTONE.getKey()) || attribute.getId().equals(BugzillaRestCreateTaskSchema.getDefault().VERSION.getKey()) || attribute.getId().equals(BugzillaRestCreateTaskSchema.getDefault().COMPONENT.getKey())) { TaskAttribute productAttribute = attribute.getParentAttribute() .getAttribute(BugzillaRestCreateTaskSchema.getDefault().PRODUCT.getKey()); BugzillaRestConfiguration repositoryConfiguration; try { repositoryConfiguration = connector.getRepositoryConfiguration(this.getTaskRepository()); Product actualProduct = repositoryConfiguration.getProductWithName(productAttribute.getValue()); if (attribute.getId().equals(BugzillaRestCreateTaskSchema.getDefault().TARGET_MILESTONE.getKey())) { internalSetAttributeOptions(attribute, actualProduct.getMilestones()); } else if (attribute.getId().equals(BugzillaRestCreateTaskSchema.getDefault().VERSION.getKey())) { internalSetAttributeOptions(attribute, actualProduct.getVersions()); } else if (attribute.getId().equals(BugzillaRestCreateTaskSchema.getDefault().COMPONENT.getKey())) { internalSetAttributeOptions(attribute, actualProduct.getComponents()); } } catch (CoreException e) { StatusHandler.log(new RepositoryStatus(getTaskRepository(), IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, 0, "Failed to obtain repository configuration", e)); } } return super.getOptions(attribute); }

Target:
public Map<String, String> getOptions(@NonNull TaskAttribute attribute) { if (attribute.getId().equals(BugzillaRestCreateTaskSchema.getDefault().TARGET_MILESTONE.getKey()) || attribute.getId().equals(BugzillaRestCreateTaskSchema.getDefault().VERSION.getKey()) || attribute.getId().equals(BugzillaRestCreateTaskSchema.getDefault().COMPONENT.getKey())) { TaskAttribute productAttribute = attribute.getParentAttribute() .getAttribute(BugzillaRestCreateTaskSchema.getDefault().PRODUCT.getKey()); BugzillaRestConfiguration repositoryConfiguration; try { repositoryConfiguration = connector.getRepositoryConfiguration(this.getTaskRepository()); if (!productAttribute.getValue().equals("")) { Product actualProduct = repositoryConfiguration.getProductWithName(productAttribute.getValue()); if (attribute.getId().equals(BugzillaRestCreateTaskSchema.getDefault().TARGET_MILESTONE.getKey())) { internalSetAttributeOptions(attribute, actualProduct.getMilestones()); } else if (attribute.getId().equals(BugzillaRestCreateTaskSchema.getDefault().VERSION.getKey())) { internalSetAttributeOptions(attribute, actualProduct.getVersions()); } else if (attribute.getId().equals(BugzillaRestCreateTaskSchema.getDefault().COMPONENT.getKey())) { internalSetAttributeOptions(attribute, actualProduct.getComponents()); } } } catch (CoreException e) { StatusHandler.log(new RepositoryStatus(getTaskRepository(), IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, 0, "Failed to obtain repository configuration", e)); } } return super.getOptions(attribute); }
Source:
public void testConsumerAlreadyExists() throws Exception { final CompletableFuture<DescribeStreamSummaryResponse> dssFuture = CompletableFuture .completedFuture(createDescribeStreamSummaryResponse()); final CompletableFuture<DescribeStreamConsumerResponse> dscFuture = CompletableFuture .completedFuture(createDescribeStreamConsumerResponse(ConsumerStatus.ACTIVE)); when(client.describeStreamSummary(any(DescribeStreamSummaryRequest.class))).thenReturn(dssFuture); when(client.describeStreamConsumer(any(DescribeStreamConsumerRequest.class))).thenReturn(dscFuture); final String consumerArn = consumerRegistration.getOrCreateStreamConsumerArn(); assertThat(consumerArn, equalTo(CONSUMER_ARN)); verify(client, times(2)).describeStreamConsumer(any(DescribeStreamConsumerRequest.class)); verify(client).describeStreamSummary(any(DescribeStreamSummaryRequest.class)); verify(client, never()).registerStreamConsumer(any(RegisterStreamConsumerRequest.class)); }

Target:
public void testConsumerAlreadyExists() throws Exception { final CompletableFuture<DescribeStreamSummaryResponse> dssFuture = CompletableFuture .completedFuture(createDescribeStreamSummaryResponse()); final CompletableFuture<DescribeStreamConsumerResponse> dscFuture = CompletableFuture .completedFuture(createDescribeStreamConsumerResponse(ConsumerStatus.ACTIVE)); when(client.describeStreamSummary(any(DescribeStreamSummaryRequest.class))).thenReturn(dssFuture); when(client.describeStreamConsumer(any(DescribeStreamConsumerRequest.class))).thenReturn(dscFuture); final String consumerArn = consumerRegistration.getOrCreateStreamConsumerArn(); assertThat(consumerArn, equalTo(CONSUMER_ARN)); verify(client, never()).registerStreamConsumer(any(RegisterStreamConsumerRequest.class)); }
Source:
private static void compareJson(LinkedList<String> arguments) throws IOException { String oldJsonPath = arguments.pollFirst(); String newJsonPath = arguments.pollFirst(); File oldJsonFile = new File(oldJsonPath); checkExist(oldJsonFile); File newJsonFile = new File(newJsonPath); checkExist(newJsonFile); ObjectMapper mapper = new ObjectMapper(); ThriftType.StructType oldStruct = mapper.readValue(oldJsonFile, ThriftType.StructType.class); ThriftType.StructType newStruct = mapper.readValue(newJsonFile, ThriftType.StructType.class); CompatibilityReport report = new CompatibilityChecker().checkCompatibility(oldStruct, newStruct); if (!report.isCompatible) { System.err.println("schema not compatible"); System.err.println(report.getMessages()); System.exit(1); } if (!report.hasEmptyStruct()) { System.err.println("schema contains empty struct"); System.err.println(report.getMessages()); System.exit(1); } System.out.println("[success] schema is compatible"); }

Target:
private static void compareJson(LinkedList<String> arguments) throws IOException { String oldJsonPath = arguments.pollFirst(); String newJsonPath = arguments.pollFirst(); File oldJsonFile = new File(oldJsonPath); checkExist(oldJsonFile); File newJsonFile = new File(newJsonPath); checkExist(newJsonFile); ObjectMapper mapper = new ObjectMapper(); ThriftType.StructType oldStruct = mapper.readValue(oldJsonFile, ThriftType.StructType.class); ThriftType.StructType newStruct = mapper.readValue(newJsonFile, ThriftType.StructType.class); CompatibilityReport report = new CompatibilityChecker().checkCompatibility(oldStruct, newStruct); if (!report.isCompatible) { System.err.println("schema not compatible"); System.err.println(report.getMessages()); System.exit(1); } if (report.hasEmptyStruct()) { System.err.println("schema contains empty struct"); System.err.println(report.getMessages()); System.exit(1); } System.out.println("[success] schema is compatible"); }
Source:
public void updateContents() { errorView.setVisibility(View.GONE); containerView.setVisibility(summary == null ? View.GONE : View.VISIBLE); progressBar.setVisibility(summary == null ? View.VISIBLE : View.GONE); if (summary == null) { return; } articleTitleView.setText(summary.getNormalizedTitle()); articleSubtitleView.setText(null); extractView.setText(StringUtil.fromHtml(summary.getExtractHtml())); ViewTreeObserver observer = extractView.getViewTreeObserver(); observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (!isAdded() || extractView == null) { return; } int maxLines = extractView.getHeight() / extractView.getLineHeight() - 1; final int minLines = 3; extractView.setMaxLines(Math.max(maxLines, minLines)); extractView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); imageView.loadImage(TextUtils.isEmpty(summary.getThumbnailUrl()) ? null : Uri.parse((WikipediaApp.getInstance().isTablet() ? ImageUrlUtil.getUrlForPreferredSize(summary.getThumbnailUrl(), PREFERRED_TABLET_THUMBNAIL_SIZE) : summary.getThumbnailUrl()))); }

Target:
public void updateContents() { errorView.setVisibility(View.GONE); containerView.setVisibility(summary == null ? View.GONE : View.VISIBLE); progressBar.setVisibility(summary == null ? View.VISIBLE : View.GONE); if (summary == null) { return; } articleTitleView.setText(summary.getNormalizedTitle()); articleSubtitleView.setText(null); extractView.setText(StringUtil.fromHtml(summary.getExtractHtml())); ViewTreeObserver observer = extractView.getViewTreeObserver(); observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (!isAdded() || extractView == null) { return; } int maxLines = extractView.getHeight() / extractView.getLineHeight() - 1; final int minLines = 3; extractView.setMaxLines(Math.max(maxLines, minLines)); extractView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); imageView.loadImage(TextUtils.isEmpty(summary.getThumbnailUrl()) ? null : Uri.parse(ImageUrlUtil.getUrlForPreferredSize(summary.getThumbnailUrl(), PREFERRED_CARD_THUMBNAIL_SIZE))); }
Source:
public void onCreate() { super.onCreate(); if (LeakCanary.isInAnalyzerProcess(this)) { return; } refWatcher = installLeakCanary(); context = this; SettingsActivity.initSettings(this); NewPipe.init(getDownloader()); StateSaver.init(this); initNotificationChannel(); ImageLoader.getInstance().init(getImageLoaderConfigurations(10, 50)); configureRxJavaErrorHandler(); new CheckForNewAppVersionTask().execute(); }

Target:
public void onCreate() { super.onCreate(); if (LeakCanary.isInAnalyzerProcess(this)) { return; } refWatcher = installLeakCanary(); app = this; SettingsActivity.initSettings(this); NewPipe.init(getDownloader(), org.schabi.newpipe.util.Localization.getPreferredExtractorLocal(this)); StateSaver.init(this); initNotificationChannel(); ImageLoader.getInstance().init(getImageLoaderConfigurations(10, 50)); configureRxJavaErrorHandler(); new CheckForNewAppVersionTask().execute(); }
Source:
public int getVersion() { return Helper.staticHashCode(toString()); }

Target:
public int getVersion() { return Helper.staticHashCode(createContentString()); }
Source:
public DailyJobSun(String thingUID, AstroThingHandler handler) { checkNotNull(thingUID, "Thing UID cannot be null"); checkNotNull(handler, "AstroThingHandler instance cannot be null"); this.thingUID = thingUID; this.handler = handler; }

Target:
public DailyJobSun(String thingUID, AstroThingHandler handler) { checkArgument(thingUID != null, "Thing UID cannot be null"); checkArgument(handler != null, "AstroThingHandler instance cannot be null"); this.thingUID = thingUID; this.handler = handler; }
Source:
public AlgorithmParameterSpec getEncryptionParameterSpec(final byte[] iv, final long position) { Validate.notNull(iv, "Initialization vector must not be null"); Validate.isTrue(iv.length == getIVLengthInBytes(), "Initialization vector has the wrong byte count [%d] " + "expected [%d] bytes", iv.length, getIVLengthInBytes()); final int ivLength = getIVLengthInBytes(); final int blockSize = getBlockSizeInBytes(); final long startingBlock = position / blockSize; byte[] startingBlockArray = ByteBuffer.allocate(ivLength).putLong(8, startingBlock).array(); byte[] updatedIV = new byte[ivLength]; int carry = 0; for (int ivIndex = ivLength - 1; ivIndex >= 0; ivIndex--) { int newIVByteAsInt = ((int)iv[ivIndex] & 0xff) + ((int)startingBlockArray[ivIndex] & 0xff) + carry; byte newIVByte = (byte) newIVByteAsInt; carry = newIVByteAsInt >>> 8; updatedIV[ivIndex] = (byte)newIVByte; } return new IvParameterSpec(updatedIV); }

Target:
public AlgorithmParameterSpec getEncryptionParameterSpec(final byte[] iv, final long position) { Validate.notNull(iv, "Initialization vector must not be null"); Validate.isTrue(iv.length == getIVLengthInBytes(), "Initialization vector has the wrong byte count [%d] " + "expected [%d] bytes", iv.length, getIVLengthInBytes()); final int ivLength = getIVLengthInBytes(); final int blockSize = getBlockSizeInBytes(); final long startingBlock = position / blockSize; byte[] startingBlockArray = ByteBuffer.allocate(ivLength).putLong(8, startingBlock).array(); byte[] updatedIV = new byte[ivLength]; int carry = 0; for (int ivIndex = ivLength - 1; ivIndex >= 0; ivIndex--) { int newIVByteAsInt = ((int)iv[ivIndex] & 0xff) + ((int)startingBlockArray[ivIndex] & 0xff) + carry; carry = newIVByteAsInt >>> 8; byte newIVByte = (byte) newIVByteAsInt; updatedIV[ivIndex] = newIVByte; } return new IvParameterSpec(updatedIV); }
Source:
public long getFileSize() { String uriString = s3Uri.toString(); String removedScheme = uriString.substring(5); String bucket = removedScheme.substring(0, removedScheme.indexOf('/')); String key = removedScheme.substring(removedScheme.indexOf('/') + 1); initializeClient(); return s3Client.getObjectMetadata(bucket, key).getContentLength(); }

Target:
public Long getFileSize() { if (fileSize == null) { fileSize = getS3Client().getObjectMetadata(bucket, key).getContentLength(); } return fileSize; }
Source:
public KafkaFuture<Void> partitionResult(final TopicPartition partition) { final KafkaFutureImpl<Void> result = new KafkaFutureImpl<>(); this.future.whenComplete((topicPartitions, throwable) -> { if (throwable != null) { result.completeExceptionally(throwable); } else { Throwable exception = KafkaAdminClient.getSubLevelError(topicPartitions, partition, "Group offset deletion for partition \"" + partition + "\" was not attempted"); if (exception != null) { result.completeExceptionally(exception); } else { result.complete(null); } } }); return result; }

Target:
public KafkaFuture<Void> partitionResult(final TopicPartition partition) { if (!partitions.contains(partition)) { throw new IllegalArgumentException("Partition " + partition + " was not included in the original request"); } final KafkaFutureImpl<Void> result = new KafkaFutureImpl<>(); this.future.whenComplete((topicPartitions, throwable) -> { if (throwable != null) { result.completeExceptionally(throwable); } else if (!maybeCompleteExceptionally(topicPartitions, partition, result)) { result.complete(null); } }); return result; }
Source:
public void testParticipantObjectId() { String oid = PRPAIN201305UV02Parser.getQueryId(request); assertEquals("QueryId mismatch", TestPatientDiscoveryMessageHelper.QUERY_ID_EXTENSION, oid); }

Target:
public void testParticipantObjectId() { assertEquals("QueryId mismatch", "abd3453dcd24wkkks545", PRPAIN201305UV02Parser.getQueryId( TestPatientDiscoveryMessageHelper.createPRPAIN201305UV02Request("Gallow", "Younger", "M", "01-12-2967", "1.1", "D12345", "2.2", "abd3453dcd24wkkks545"))); }
Source:
protected void setTimeZone(char timeZoneFlag, char t0, char t1, char t3, char t4) { int timeZoneOffset = ((t0 - '0') * 10 + (t1 - '0')) * 3600 * 1000; timeZoneOffset += ((t3 - '0') * 10 + (t4 - '0')) * 60 * 1000; if (timeZoneFlag == '-') { timeZoneOffset = -timeZoneOffset; } if (calendar.getTimeZone().getRawOffset() != timeZoneOffset) { calendar.setTimeZone(new SimpleTimeZone(timeZoneOffset, "" + timeZoneOffset)); } }

Target:
protected void setTimeZone(char timeZoneFlag, char t0, char t1, char t3, char t4) { int timeZoneOffset = ((t0 - '0') * 10 + (t1 - '0')) * 3600 * 1000; timeZoneOffset += ((t3 - '0') * 10 + (t4 - '0')) * 60 * 1000; if (timeZoneFlag == '-') { timeZoneOffset = -timeZoneOffset; } if (calendar.getTimeZone().getRawOffset() != timeZoneOffset) { calendar.setTimeZone(new SimpleTimeZone(timeZoneOffset, Integer.toString(timeZoneOffset))); } }
Source:
@Override @Nullable public Column loadColumn(int chunkX, int chunkZ) throws IOException { NBTTagCompound nbt; SaveEntry<EntryLocation2D> saveEntry; if ((saveEntry = columnsToSave.get(new ChunkPos(chunkX, chunkZ))) != null) { nbt = saveEntry.nbt; } else { Optional<ByteBuffer> buf = this.save.load(new EntryLocation2D(chunkX, chunkZ)); if (!buf.isPresent()) { return null; } nbt = this.dataFixer.process(FixTypes.CHUNK, CompressedStreamTools.readCompressed(new ByteArrayInputStream(buf.get().array()))); } return IONbtReader.readColumn(world, chunkX, chunkZ, nbt); }

Target:
@Override @Nullable public Column loadColumn(int chunkX, int chunkZ) throws IOException { NBTTagCompound nbt; SaveEntry<EntryLocation2D> saveEntry; if ((saveEntry = columnsToSave.get(new ChunkPos(chunkX, chunkZ))) != null) { nbt = saveEntry.nbt; } else { Optional<ByteBuffer> buf = this.save.load(new EntryLocation2D(chunkX, chunkZ)); if (!buf.isPresent()) { return null; } nbt = FMLCommonHandler.instance().getDataFixer().process(FixTypes.CHUNK, CompressedStreamTools.readCompressed(new ByteArrayInputStream(buf.get().array()))); } return IONbtReader.readColumn(world, chunkX, chunkZ, nbt); }
Source:
public void setParentIds(ObjectId... newParents) { parentIds = new ObjectId[newParents.length]; int newParentCount = 0; for (int i = 0; i < newParents.length; i++) { for (int j = 0; j < newParentCount; j++) if (parentIds[j].equals(newParents[i])) throw new IllegalArgumentException(MessageFormat.format( JGitText.get().duplicateParents, parentIds[j].getName())); parentIds[newParentCount++] = newParents[i].copy(); } if (newParentCount == parentIds.length) return; ObjectId[] tmpIds = new ObjectId[newParentCount]; System.arraycopy(parentIds, 0, tmpIds, 0, newParentCount); parentIds = tmpIds; }

Target:
public void setParentIds(ObjectId... newParents) { ObjectId[] tmpIds = new ObjectId[newParents.length]; int newParentCount = 0; for (int i = 0; i < newParents.length; i++) { for (int j = 0; j < newParentCount; j++) if (tmpIds[j].equals(newParents[i])) throw new IllegalArgumentException(MessageFormat.format( JGitText.get().duplicateParents, tmpIds[j].getName())); tmpIds[newParentCount++] = newParents[i].copy(); } parentIds = tmpIds; }
Source:
public void failIfUnknownSetting() throws Exception { try { db.execute( "CALL dbms.setConfigValue('unknown.setting.indeed', 'foo')" ); } catch ( Exception e ) { Throwable cause = Exceptions.rootCause( e ); assertThat( cause, instanceOf( IllegalArgumentException.class ) ); assertThat( cause.getMessage(), equalTo( "Unknown setting: unknown.setting.indeed" ) ); return; } fail( "Should throw IllegalArgumentException" ); }

Target:
public void failIfUnknownSetting() throws Exception { expect.expect( new NestedThrowableMatcher( IllegalArgumentException.class ) ); expect.expectMessage( "Unknown setting: unknown.setting.indeed" ); db.execute( "CALL dbms.setConfigValue('unknown.setting.indeed', 'foo')" ); }
Source:
public void vmTypeChanged(VmType vmType) { if (getModel().getProvisioning().getIsAvailable()) { getModel().getProvisioning().setEntity(vmType == VmType.Server || vmType == VmType.HighPerformance); } if (getModel().getIoThreadsEnabled().getIsAvailable()) { getModel().getIoThreadsEnabled().setEntity(vmType == VmType.Server || vmType == VmType.HighPerformance); } super.vmTypeChanged(vmType); }

Target:
public void vmTypeChanged(VmType vmType) { if (getModel().getProvisioning().getIsAvailable()) { getModel().getProvisioning().setEntity(vmType == VmType.Server || vmType == VmType.HighPerformance); } super.vmTypeChanged(vmType); }
Source:
public void scheduleHealthCheck() { zookeeperClientManager.getClients().forEach(client -> client.ensurePathExists(healthCheckPath)); executorService.scheduleAtFixedRate(healthCheckTask, 0, period, TimeUnit.SECONDS); }

Target:
public void scheduleHealthCheck() { logger.info("Starting the storage health check scheduler"); executorService.scheduleAtFixedRate(healthCheckTask, 0, period, TimeUnit.SECONDS); }
Source:
String mesosMasterAddress() { try (CuratorFramework cf = zkClient()) { cf.start(); List<String> children = cf.getChildren().forPath("/mesos"); List<Integer> masterIDList= new ArrayList<Integer>(); if (children.isEmpty()) { return null; } JSONObject cfData = null; for (String child : children) { if (child.startsWith("json.info")) { masterIDList.add(Integer.parseInt(child.split("_")[1])); } } Collections.sort(masterIDList); for (String child : children) { if (child.endsWith(String.valueOf(masterIDList.get(0)))) { cfData = new JSONObject(new String(cf.getData().forPath("/mesos/" + child))); break; } } if (cfData != null) { JSONObject address = cfData.getJSONObject("address"); return String.format("%s:%d", address.getString("ip"), address.getInt("port")); } } catch (Exception e) { LOGGER.error("Error while obtaining a mesos address from the curator framework: ", e); } return null; }

Target:
String mesosMasterAddress() { try (CuratorFramework cf = zkClient()) { cf.start(); List<String> children = cf.getChildren().forPath("/mesos"); List<Integer> masterIds= new ArrayList<Integer>(); if (children.isEmpty()) { return null; } JSONObject cfData = null; for (String child : children) { if (child.startsWith("json.info")) { masterIds.add(Integer.parseInt(child.split("_")[1])); } } Collections.sort(masterIds); for (String child : children) { if (child.endsWith(String.valueOf(masterIds.get(0)))) { cfData = new JSONObject(new String(cf.getData().forPath("/mesos/" + child))); break; } } if (cfData != null) { JSONObject address = cfData.getJSONObject("address"); return String.format("%s:%d", address.getString("ip"), address.getInt("port")); } } catch (Exception e) { LOGGER.error("Error while obtaining a mesos address from the curator framework: ", e); } return null; }
Source:
public static Class getJavaType(int sqlType) { switch (sqlType) { case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: return String.class; case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: return byte[].class; case Types.BIT: return Boolean.class; case Types.TINYINT: case Types.SMALLINT: return Short.class; case Types.INTEGER: return Integer.class; case Types.BIGINT: return Long.class; case Types.REAL: return Float.class; case Types.DOUBLE: case Types.FLOAT: return Double.class; case Types.DATE: return Date.class; case Types.TIME: return Time.class; case Types.TIMESTAMP: return Timestamp.class; default: throw new RuntimeException("We do not support tables with SqlType: " + getSqlTypeName(sqlType)); } }

Target:
public static Class getJavaType(int sqlType) { switch (sqlType) { case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: case Types.CLOB: return String.class; case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: return byte[].class; case Types.BIT: return Boolean.class; case Types.TINYINT: case Types.SMALLINT: return Short.class; case Types.INTEGER: return Integer.class; case Types.BIGINT: return Long.class; case Types.REAL: return Float.class; case Types.DOUBLE: case Types.FLOAT: return Double.class; case Types.DATE: return Date.class; case Types.TIME: return Time.class; case Types.TIMESTAMP: return Timestamp.class; default: throw new RuntimeException("We do not support tables with SqlType: " + getSqlTypeName(sqlType)); } }
Source:
public Map toMap () { ObjectMapper mapper = new ObjectMapper(); String uiSpecification; try { uiSpecification = mapper.writeValueAsString(serviceUISpecification); } catch (JsonProcessingException e) { throw new RuntimeException(e); } Map<String, Object> map = new HashMap<String, Object>(); map.put(ID, id); map.put(NAME, name); map.put(TIMESTAMP, timestamp); map.put(UI_SPECIFICATION, uiSpecification); map.put(REGISTER_CLASS, registerClass); return map; }

Target:
public Map toMap () { String uiSpecification; try { uiSpecification = mapper.writeValueAsString(serviceUISpecification); } catch (JsonProcessingException e) { throw new RuntimeException(e); } Map<String, Object> map = new HashMap<String, Object>(); map.put(ID, id); map.put(NAME, name); map.put(TIMESTAMP, timestamp); map.put(UI_SPECIFICATION, uiSpecification); map.put(REGISTER_CLASS, registerClass); return map; }
Source:
private StreamingResponse _findAndStream(FindRequest req,OperationContext ctx) { StreamingResponse response = new StreamingResponse(factory.getNodeFactory()); response.setStatus(OperationStatus.ERROR); response.setEntity(ctx.getTopLevelEntityName(),ctx.getTopLevelEntityVersion()); CompositeMetadata md = ctx.getTopLevelEntityMetadata(); if (!md.getAccess().getFind().hasAccess(ctx.getCallerRoles())) { ctx.setStatus(OperationStatus.ERROR); LOGGER.debug("No access"); ctx.addError(Error.get(CrudConstants.ERR_NO_ACCESS, "find " + ctx.getTopLevelEntityName())); } else if (checkQueryAccess(ctx, req.getQuery())) { factory.getInterceptors().callInterceptors(InterceptPoint.PRE_MEDIATOR_FIND, ctx); Finder finder; if (ctx.isSimple()) { LOGGER.debug("Simple entity"); finder = new SimpleFindImpl(md, factory); } else { LOGGER.debug("Composite entity"); finder = new CompositeFindImpl(md); ((CompositeFindImpl) finder).setParallelism(9); } ctx.measure.begin("finder.find"); CRUDFindResponse result = finder.find(ctx, req.getCRUDFindRequest()); ctx.measure.end("finder.find"); if(!ctx.hasErrors()) { ctx.setStatus(OperationStatus.COMPLETE); response.documentStream=ctx.getDocumentStream(); if(ctx.isComputeMatchCount()) { response.matchCount=result.getSize(); } } else { ctx.setStatus(OperationStatus.ERROR); } } response.setStatus(ctx.getStatus()); response.getErrors().addAll(ctx.getErrors()); return response; }

Target:
private StreamingResponse _findAndStream(FindRequest req,OperationContext ctx) { StreamingResponse response = new StreamingResponse(factory.getNodeFactory()); response.setStatus(OperationStatus.ERROR); response.setEntity(ctx.getTopLevelEntityName(),ctx.getTopLevelEntityVersion()); CompositeMetadata md = ctx.getTopLevelEntityMetadata(); if (!md.getAccess().getFind().hasAccess(ctx.getCallerRoles())) { ctx.setStatus(OperationStatus.ERROR); LOGGER.debug("No access"); ctx.addError(Error.get(CrudConstants.ERR_NO_ACCESS, "find " + ctx.getTopLevelEntityName())); } else if (checkQueryAccess(ctx, req.getQuery())) { factory.getInterceptors().callInterceptors(InterceptPoint.PRE_MEDIATOR_FIND, ctx); Finder finder; if (ctx.isSimple()) { LOGGER.debug("Simple entity"); finder = new SimpleFindImpl(md, factory); } else { LOGGER.debug("Composite entity"); finder = new CompositeFindImpl(md); ((CompositeFindImpl) finder).setParallelism(9); } ctx.measure.begin("finder.find"); CRUDFindResponse result = finder.find(ctx, req.getCRUDFindRequest()); ctx.measure.end("finder.find"); if(!ctx.hasErrors()) { ctx.setStatus(OperationStatus.COMPLETE); response.documentStream=ctx.getDocumentStream(); if(ctx.isComputeCounts()) { response.matchCount=result.getSize(); } } else { ctx.setStatus(OperationStatus.ERROR); } } response.setStatus(ctx.getStatus()); response.getErrors().addAll(ctx.getErrors()); return response; }
Source:
@Override public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) { Map<TypeElement, ExtraInjector> targetClassMap = findAndParseTargets(env); for (Map.Entry<TypeElement, ExtraInjector> entry : targetClassMap.entrySet()) { TypeElement typeElement = entry.getKey(); ExtraInjector extraInjector = entry.getValue(); try { JavaFileObject jfo = filer.createSourceFile(extraInjector.getFqcn(), typeElement); Writer writer = jfo.openWriter(); writer.write(extraInjector.brewJava()); writer.flush(); writer.close(); } catch (IOException e) { error(typeElement, "Unable to write injector for type %s: %s", typeElement, e.getMessage()); } try { IntentBuilder intentBuilder = new IntentBuilder(extraInjector.getClassPackage(), typeElement.getSimpleName()+INTENT_BUILDER_SUFFIX, extraInjector.getTargetClass(), extraInjector.getInjectionMap()); JavaFileObject jfo = filer.createSourceFile(intentBuilder.getFqcn(), typeElement); Writer writer = jfo.openWriter(); writer.write(intentBuilder.brewJava()); writer.flush(); writer.close(); } catch (IOException e) { error(typeElement, "Unable to write intent builder for type %s: %s", typeElement, e.getMessage()); } } return true; }

Target:
@Override public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) { Map<TypeElement, ExtraInjector> targetClassMap = findAndParseTargets(env); for (Map.Entry<TypeElement, ExtraInjector> entry : targetClassMap.entrySet()) { TypeElement typeElement = entry.getKey(); ExtraInjector extraInjector = entry.getValue(); Writer writer = null; try { JavaFileObject jfo = filer.createSourceFile(extraInjector.getFqcn(), typeElement); writer = jfo.openWriter(); writer.write(extraInjector.brewJava()); } catch (IOException e) { error(typeElement, "Unable to write injector for type %s: %s", typeElement, e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { error(typeElement, "Unable to close injector source file for type %s: %s", typeElement, e.getMessage()); } } } Writer writer2 = null; try { IntentBuilder intentBuilder = new IntentBuilder(extraInjector.getClassPackage(), typeElement.getSimpleName() + INTENT_BUILDER_SUFFIX, extraInjector.getTargetClass(), extraInjector.getInjectionMap()); JavaFileObject jfo = filer.createSourceFile(intentBuilder.getFqcn(), typeElement); writer2 = jfo.openWriter(); writer2.write(intentBuilder.brewJava()); } catch (IOException e) { error(typeElement, "Unable to write intent builder for type %s: %s", typeElement, e.getMessage()); } finally { if (writer2 != null) { try { writer2.close(); } catch (IOException e) { error(typeElement, "Unable to close intent builder source file for type %s: %s", typeElement, e.getMessage()); } } } } return true; }
Source:
public void reserveAvailableResource() throws Exception { LockableResourcesManager lm = LockableResourcesManager.get(); lm.createResourceWithLabel("resource1", "label1"); WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition(SCRIPT_TRY_DONT_RELEASE)); WorkflowRun b1 = p.scheduleBuild2(0).waitForStart(); j.assertBuildStatusSuccess(j.waitForCompletion(b1)); j.assertLogContains("Returned True", b1); }

Target:
public void reserveAvailableResource() throws Exception { final LockableResourcesManager lm = LockableResourcesManager.get(); lm.createResourceWithLabel("resource1", "label1"); final WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition(SCRIPT_TRY_DONT_RELEASE)); final WorkflowRun b1 = p.scheduleBuild2(0).waitForStart(); j.assertBuildStatusSuccess(j.waitForCompletion(b1)); j.assertLogContains("Returned True", b1); j.assertLogContains("[lockable-resources] released lock on [resource1]", b1); }
Source:
private String getUserAlias(LinkedHashMap<String, LinkedHashMap<String, String>> attribute, String fullAttributeName){ String alias = attribute.get(fullAttributeName).get(ALIAS); if (alias == null) { return null; } alias = this.replaceByAlias(alias); alias = alias.replace("$attribute", fullAttributeName); alias = alias.replace("$domain", domain); try { alias = alias.replace("$value", getJmxValue().toString()); } catch (Exception e) { } return alias; }

Target:
private String getUserAlias(LinkedHashMap<String, LinkedHashMap<String, String>> attribute, String fullAttributeName){ String alias = attribute.get(fullAttributeName).get(ALIAS); if (alias == null) { return null; } alias = this.replaceByAlias(alias); alias = alias.replace("$attribute", fullAttributeName); alias = alias.replace("$domain", domain); try { alias = alias.replace("$value", getJmxValue().toString()); } catch (JMException e) { LOGGER.warn("Unable to replace $value for attribute " + fullAttributeName, e); } catch (IOException e) { LOGGER.warn("Unable to replace $value for attribute " + fullAttributeName, e); } return alias; }
Source:
public void testGetFieldType() { StringMultipleInputFieldDefinition fieldDefinition = new StringMultipleInputFieldDefinition(); fieldDefinition.setStandaloneClassName(String.class.getName()); assertEquals(fieldDefinition.getFieldTypeInfo().getType(), TypeKind.BASE); fieldDefinition.setStandaloneClassName(Object.class.getName()); assertNotEquals(fieldDefinition.getFieldTypeInfo().getType(), TypeKind.BASE); }

Target:
public void testGetFieldType() { StringMultipleSelectorFieldDefinition fieldDefinition = new StringMultipleSelectorFieldDefinition(); fieldDefinition.setStandaloneClassName(String.class.getName()); assertEquals(TypeKind.BASE, fieldDefinition.getFieldTypeInfo().getType()); fieldDefinition.setStandaloneClassName(Object.class.getName()); assertEquals(TypeKind.OBJECT, fieldDefinition.getFieldTypeInfo().getType()); }
Source:
protected ZkClient(IZkConnection zkConnection, int connectionTimeout, long operationRetryTimeout, PathBasedZkSerializer zkSerializer, String monitorType, String monitorKey, String monitorInstanceName, boolean monitorRootPathOnly) { if (zkConnection == null) { throw new NullPointerException("Zookeeper connection is null!"); } _uid = UID.getAndIncrement(); _connection = zkConnection; _pathBasedZkSerializer = zkSerializer; _operationRetryTimeoutInMillis = operationRetryTimeout; _isNewSessionEventFired = false; _asyncCallRetryThread = new ZkAsyncRetryThread(zkConnection.getServers()); _asyncCallRetryThread.start(); LOG.debug("ZkClient created with _uid {}, _asyncCallRetryThread id {}", _uid, _asyncCallRetryThread.getId()); if (monitorKey != null && !monitorKey.isEmpty() && monitorType != null && !monitorType .isEmpty()) { _monitor = new ZkClientMonitor(monitorType, monitorKey, monitorInstanceName, monitorRootPathOnly, _eventThread); } else { LOG.info("ZkClient monitor key or type is not provided. Skip monitoring."); } connect(connectionTimeout, this); }

Target:
protected ZkClient(IZkConnection zkConnection, int connectionTimeout, long operationRetryTimeout, PathBasedZkSerializer zkSerializer, String monitorType, String monitorKey, String monitorInstanceName, boolean monitorRootPathOnly) { if (zkConnection == null) { throw new NullPointerException("Zookeeper connection is null!"); } _uid = UID.getAndIncrement(); _connection = zkConnection; _pathBasedZkSerializer = zkSerializer; _operationRetryTimeoutInMillis = operationRetryTimeout; _isNewSessionEventFired = false; _asyncCallRetryThread = new ZkAsyncRetryThread(zkConnection.getServers()); _asyncCallRetryThread.start(); LOG.debug("ZkClient created with _uid {}, _asyncCallRetryThread id {}", _uid, _asyncCallRetryThread.getId()); if (monitorKey != null && !monitorKey.isEmpty() && monitorType != null && !monitorType .isEmpty()) { _monitor = new ZkClientMonitor(monitorType, monitorKey, monitorInstanceName, monitorRootPathOnly, _eventThread); } else { LOG.info("ZkClient monitor key or type is not provided. Skip monitoring."); } connect(connectionTimeout, this); try { if (_monitor != null) { _monitor.register(); } } catch (JMException e){ LOG.error("Error in creating ZkClientMonitor", e); } }