auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ListenableFuture<TaskStatus> run(final Task task) { final int taskId = Integer.parseInt(task.getId()); ListenableFuture<TaskStatus> future = MoreExecutors.listeningDecorator( Execs.singleThreaded( "noop_test_task_exec_%s" ) ).submit( new Callable<TaskStatus>() { @Override public TaskStatus call() throws Exception { try { taskLatches[taskId].await(2, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RuntimeException("Thread was interrupted!"); } runningTaskRunnerWorkItems.remove(taskId); return TaskStatus.success(task.getId()); } } ); TaskRunnerWorkItem taskRunnerWorkItem = new TaskRunnerWorkItem(task.getId(), future); runningTaskRunnerWorkItems.put(taskId, taskRunnerWorkItem); taskRunnerWorkItems.put(taskId, taskRunnerWorkItem); return future; }

Target:
public ListenableFuture<TaskStatus> run(final Task task) { final int taskId = Integer.parseInt(task.getId()); ListenableFuture<TaskStatus> future = MoreExecutors.listeningDecorator( Execs.singleThreaded( "noop_test_task_exec_%s" ) ).submit( new Callable<TaskStatus>() { @Override public TaskStatus call() throws Exception { try { taskLatches[taskId].await(); } catch (InterruptedException e) { throw new RuntimeException("Thread was interrupted!"); } runningTaskRunnerWorkItems.remove(taskId); return TaskStatus.success(task.getId()); } } ); TaskRunnerWorkItem taskRunnerWorkItem = new TaskRunnerWorkItem(task.getId(), future); runningTaskRunnerWorkItems.put(taskId, taskRunnerWorkItem); taskRunnerWorkItems.put(taskId, taskRunnerWorkItem); return future; }
Source:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_collaborations, container, false); mCollaboratorsListView = (ListView) view.findViewById(R.id.collaboratorsList); mCollaboratorsListView.setDivider(null); mCollaboratorsAdapter = new CollaboratorsAdapter(getActivity(), getItem(), mController); mCollaboratorsListView.setAdapter(mCollaboratorsAdapter); mCollaboratorsListView.setOnItemClickListener(this); mNoCollaboratorsText = (TextView) view.findViewById(R.id.no_collaborators_text); if (savedInstanceState == null) { fetchCollaborations(); }else if (savedInstanceState != null) { mCollaborations = (BoxIteratorCollaborations)savedInstanceState.getSerializable(CollaborationUtils.EXTRA_COLLABORATIONS); updateUi(); } else if (getArguments() != null){ Bundle args = getArguments(); mCollaborations = (BoxIteratorCollaborations)args.getSerializable(CollaborationUtils.EXTRA_COLLABORATIONS); updateUi(); } if (getItem().getAllowedInviteeRoles() == null) { fetchRoles(); } return view; }

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_collaborations, container, false); mCollaboratorsListView = (ListView) view.findViewById(R.id.collaboratorsList); mCollaboratorsListView.setDivider(null); mCollaboratorsAdapter = new CollaboratorsAdapter(getActivity(), getItem(), mController); mCollaboratorsListView.setAdapter(mCollaboratorsAdapter); mCollaboratorsListView.setOnItemClickListener(this); mNoCollaboratorsText = (TextView) view.findViewById(R.id.no_collaborators_text); if (savedInstanceState == null) { if (getArguments() != null){ Bundle args = getArguments(); mCollaborations = (BoxIteratorCollaborations)args.getSerializable(CollaborationUtils.EXTRA_COLLABORATIONS); } if (mCollaborations != null){ updateUi(); } fetchCollaborations(); } else { mCollaborations = (BoxIteratorCollaborations)savedInstanceState.getSerializable(CollaborationUtils.EXTRA_COLLABORATIONS); updateUi(); if (mCollaborations == null) { fetchCollaborations(); } } if (getItem().getAllowedInviteeRoles() == null) { fetchRoles(); } return view; }
Source:
public final T create(final CreationalContext<T> cc) { Context initialContext = null; CreationException e = null; try { initialContext = this.getNewInitialContext(); return this.type.cast(initialContext.lookup(this.name)); } catch (final NamingException namingException) { e = new CreationException(namingException.getMessage(), namingException); throw e; } finally { try { initialContext.close(); } catch (final NamingException namingException) { if (e != null) { e.addSuppressed(namingException); } else { e = new CreationException(namingException.getMessage(), namingException); } throw e; } } }

Target:
public final T create(final CreationalContext<T> cc) { Context initialContext = null; CreationException e = null; try { initialContext = this.getNewInitialContext(); return this.type.cast(initialContext.lookup(this.name)); } catch (final NamingException namingException) { e = new CreationException(namingException.getMessage(), namingException); throw e; } finally { if (initialContext != null) { try { initialContext.close(); } catch (final NamingException namingException) { if (e != null) { e.addSuppressed(namingException); } else { e = new CreationException(namingException.getMessage(), namingException); } throw e; } } } }
Source:
private static String key(Tree tree) { if (tree.is(Kind.NUMERIC_LITERAL)) { return ((NumericLiteral) tree).valueAsString(); } else if (tree.is(Kind.STRING_LITERAL)) { return ((StringLiteral) tree).trimmedQuotesValue(); } else if (tree.is(Kind.NAME)) { return ((Name) tree).name(); } else if (tree.is(Kind.SLICE_ITEM)) { SliceItem sliceItem = (SliceItem) tree; List<String> keyParts = Stream.of(sliceItem.lowerBound(), sliceItem.upperBound(), sliceItem.stride()) .map(e -> e == null ? "" : key(e)) .collect(Collectors.toList()); return keyParts.contains(null) ? null : String.join(":", keyParts); } return null; }

Target:
private static String key(Tree tree) { if (tree.is(Kind.NUMERIC_LITERAL)) { return ((NumericLiteral) tree).valueAsString(); } else if (tree.is(Kind.STRING_LITERAL)) { return ((StringLiteral) tree).trimmedQuotesValue(); } else if (tree.is(Kind.NAME)) { return ((Name) tree).name(); } else if (tree.is(Kind.SLICE_ITEM)) { SliceItem sliceItem = (SliceItem) tree; return Stream.of(sliceItem.lowerBound(), sliceItem.upperBound(), sliceItem.stride()) .map(e -> e == null ? "" : key(e)) .collect(Collectors.joining(":")); } return null; }
Source:
public Optional<Block> compute() { int length = selectedPositions.getOffset() + selectedPositions.size(); if (selectedPositions.isList()) { for (int index = nextIndexOrPosition; index < length; index++) { writeNativeValue(evaluator.getType(), blockBuilder, evaluator.evaluate(selectedPositions.getPositions()[index], blocks)); if (yieldSignal.isSet()) { nextIndexOrPosition = index + 1; return Optional.empty(); } } } else { for (int position = nextIndexOrPosition; position < length; position++) { writeNativeValue(evaluator.getType(), blockBuilder, evaluator.evaluate(position, blocks)); if (yieldSignal.isSet()) { nextIndexOrPosition = position + 1; return Optional.empty(); } } } Block block = blockBuilder.build(); blockBuilder = blockBuilder.newBlockBuilderLike(new BlockBuilderStatus()); return Optional.of(block); }

Target:
public Optional<Block> compute() { int length = selectedPositions.getOffset() + selectedPositions.size(); if (selectedPositions.isList()) { int[] positions = selectedPositions.getPositions(); while (nextIndexOrPosition < length) { writeNativeValue(evaluator.getType(), blockBuilder, evaluator.evaluate(positions[nextIndexOrPosition], blocks)); nextIndexOrPosition++; if (yieldSignal.isSet()) { return Optional.empty(); } } } else { while (nextIndexOrPosition < length) { writeNativeValue(evaluator.getType(), blockBuilder, evaluator.evaluate(nextIndexOrPosition, blocks)); nextIndexOrPosition++; if (yieldSignal.isSet()) { return Optional.empty(); } } } Block block = blockBuilder.build(); blockBuilder = blockBuilder.newBlockBuilderLike(new BlockBuilderStatus()); return Optional.of(block); }
Source:
MandateConnectorResponse createMandate(Account account, MandateConnectorRequest mandateConnectorRequest) { String requestJson; try { requestJson = objectMapper.writeValueAsString(mandateConnectorRequest); } catch (JsonProcessingException e) { throw new RuntimeException(e); } Response response = client.target(getDDConnectorUrl(format("/v1/api/accounts/%s/mandates", account.getName()))) .request() .accept(MediaType.APPLICATION_JSON) .post(json(requestJson)); if (response.getStatus() == HttpStatus.SC_CREATED) return response.readEntity(MandateConnectorResponse.class); throw new CreateAgreementException(response); }

Target:
MandateConnectorResponse createMandate(Account account, MandateConnectorRequest mandateConnectorRequest) { Response response = client.target(getDDConnectorUrl(format("/v1/api/accounts/%s/mandates", account.getName()))) .request() .accept(MediaType.APPLICATION_JSON) .post(Entity.entity(mandateConnectorRequest, MediaType.APPLICATION_JSON)); if (response.getStatus() == HttpStatus.SC_CREATED) return response.readEntity(MandateConnectorResponse.class); throw new CreateAgreementException(response); }
Source:
protected Builder() { id("dimensiondata-cloudcontrol").name("DimensionData CloudControl API").identityName("user name") .credentialName("user password") .documentation(URI.create("<LINK_1>")) .defaultEndpoint("<LINK_0>").version("2.4") .defaultProperties(DimensionDataCloudControlApiMetadata.defaultProperties()) .view(typeToken(ComputeServiceContext.class)).defaultModules( ImmutableSet.<Class<? extends Module>>builder().add(DimensionDataCloudControlHttpApiModule.class) .add(DimensionDataCloudControlParserModule.class) .add(DimensionDataComputeServiceContextModule.class).build()); }

Target:
protected Builder() { id("dimensiondata-cloudcontrol").name("DimensionData CloudControl API").identityName("user name") .credentialName("user password") .documentation(URI.create("<LINK_1>")) .defaultEndpoint("<LINK_0>").version("2.4") .defaultProperties(DimensionDataCloudControlApiMetadata.defaultProperties()) .view(typeToken(ComputeServiceContext.class)).defaultModules( ImmutableSet.<Class<? extends Module>>builder().add(DimensionDataCloudControlHttpApiModule.class) .add(DimensionDataCloudControlParserModule.class).build()); }
Source:
public static RegisteredTypeConstraint alreadyVisited(Set<String> encounteredTypeSymbolicNames, String anotherEncounteredType) { BasicRegisteredTypeConstraint result = new BasicRegisteredTypeConstraint(); result.encounteredTypes = MutableSet.copyOf(encounteredTypeSymbolicNames); if (anotherEncounteredType!=null) result.encounteredTypes.add(anotherEncounteredType); return result; }

Target:
public static RegisteredTypeConstraint alreadyVisited(Set<String> encounteredTypeSymbolicNames, String anotherEncounteredType) { BasicRegisteredTypeConstraint result = new BasicRegisteredTypeConstraint(); MutableSet<String> encounteredTypes = MutableSet.copyOf(encounteredTypeSymbolicNames); encounteredTypes.addIfNotNull(anotherEncounteredType); result.encounteredTypes = encounteredTypes.asUnmodifiable(); return result; }
Source:
public void execute() throws ExecutionException, InterruptedException { final String password = "password"; final DefaultResetPasswordFormData resetPasswordFormData = new DefaultResetPasswordFormData(); resetPasswordFormData.setConfirmPassword(password); resetPasswordFormData.setNewPassword(password); final String resetTokenValue = "reset-token-value"; when: { when(hookRunner.runUnaryOperatorHook(eq(CustomerPasswordResetCommandHook.class), any(), customerPasswordResetCommandCaptor.capture())) .thenAnswer(invocation -> invocation.getArgument(2)); when(sphereClient.execute(any())) .thenReturn(CompletableFuture.completedFuture(customer)); } final CompletableFuture<Customer> customerCompletableFuture = (CompletableFuture<Customer>) defaultResetPasswordControllerAction.apply(resetTokenValue, resetPasswordFormData); final Customer customer = customerCompletableFuture.get(); then: { assertThat(customer).isNotNull(); final CustomerPasswordResetCommand customerPasswordResetCommand = customerPasswordResetCommandCaptor.getValue(); assertThat(customerPasswordResetCommand.getTokenValue()).isEqualTo(resetTokenValue); assertThat(customerPasswordResetCommand.getNewPassword()).isEqualTo(password); } }

Target:
public void execute() throws ExecutionException, InterruptedException { final String password = "password"; final DefaultResetPasswordFormData resetPasswordFormData = new DefaultResetPasswordFormData(); resetPasswordFormData.setConfirmPassword(password); resetPasswordFormData.setNewPassword(password); final String resetTokenValue = "reset-token-value"; when: { when(hookRunner.runUnaryOperatorHook(eq(CustomerPasswordResetCommandHook.class), any(), customerPasswordResetCommandCaptor.capture())) .thenAnswer(invocation -> invocation.getArgument(2)); when(sphereClient.execute(any())) .thenReturn(CompletableFuture.completedFuture(customer)); } final Customer updatedCustomer = defaultResetPasswordControllerAction.apply(resetTokenValue, resetPasswordFormData) .toCompletableFuture().get(); then: { assertThat(updatedCustomer).isNotNull(); final CustomerPasswordResetCommand customerPasswordResetCommand = customerPasswordResetCommandCaptor.getValue(); assertThat(customerPasswordResetCommand.getTokenValue()).isEqualTo(resetTokenValue); assertThat(customerPasswordResetCommand.getNewPassword()).isEqualTo(password); } }
Source:
private static void populateAnalysisModules() { IPath pathToFiles = XmlUtils.getXmlFilesPath(); File fFolder = pathToFiles.toFile(); if (!(fFolder.isDirectory() && fFolder.exists())) { return; } File fOldFolder = XML_DIRECTORY_LEGACY.toFile(); if ((fOldFolder.isDirectory() && fOldFolder.exists())) { for (File fromFile : fOldFolder.listFiles()) { File toFile = pathToFiles.addTrailingSeparator().append(fromFile.getName()).toFile(); if (!toFile.exists()) { try (FileInputStream fis = new FileInputStream(fromFile); FileOutputStream fos = new FileOutputStream(toFile); FileChannel source = fis.getChannel(); FileChannel destination = fos.getChannel();) { destination.transferFrom(source, 0, source.size()); } catch (IOException e) { String error = Messages.XmlUtils_ErrorCopyingFile; Activator.logError(error, e); } } } } for (File xmlFile : fFolder.listFiles()) { processFile(xmlFile); } }

Target:
private static void populateAnalysisModules() { IPath pathToFiles = XmlUtils.getXmlFilesPath(); File fFolder = pathToFiles.toFile(); if (!(fFolder.isDirectory() && fFolder.exists())) { return; } File fOldFolder = XML_DIRECTORY_LEGACY.toFile(); if ((fOldFolder.isDirectory() && fOldFolder.exists())) { for (File fromFile : fOldFolder.listFiles()) { File toFile = pathToFiles.append(fromFile.getName()).toFile(); if (!toFile.exists() && !fromFile.isDirectory()) { try (FileInputStream fis = new FileInputStream(fromFile); FileOutputStream fos = new FileOutputStream(toFile); FileChannel source = fis.getChannel(); FileChannel destination = fos.getChannel();) { destination.transferFrom(source, 0, source.size()); } catch (IOException e) { String error = Messages.XmlUtils_ErrorCopyingFile; Activator.logError(error, e); } } } } for (File xmlFile : fFolder.listFiles()) { processFile(xmlFile); } }
Source:
public void pageFilterIsAppliedToReadRowsRequest() throws IOException { final String TABLE_ID = "tableId"; final RequestContext requestContext = RequestContext.create( InstanceName.of("ProjectId", "InstanceId"), "AppProfile"); ReadHooks hooks = new DefaultReadHooks(); FilterAdapterContext context = new FilterAdapterContext(new Scan(), hooks); PageFilter pageFilter = new PageFilter(20); Filters.Filter adaptedFilter = pageFilterAdapter.adapt(context, pageFilter); Assert.assertNull("PageFilterAdapter should not return a Filters.Filter.", adaptedFilter); Query query = Query.create(TABLE_ID).limit(100); Query postHookRequest = hooks.applyPreSendHook(query); Assert.assertEquals(20, postHookRequest.toProto(requestContext).getRowsLimit()); }

Target:
public void pageFilterIsAppliedToReadRowsRequest() throws IOException { final String TABLE_ID = "tableId"; final RequestContext requestContext = RequestContext.create("ProjectId", "InstanceId", "AppProfile"); ReadHooks hooks = new DefaultReadHooks(); FilterAdapterContext context = new FilterAdapterContext(new Scan(), hooks); PageFilter pageFilter = new PageFilter(20); Filters.Filter adaptedFilter = pageFilterAdapter.adapt(context, pageFilter); Assert.assertNull("PageFilterAdapter should not return a Filters.Filter.", adaptedFilter); Query query = Query.create(TABLE_ID).limit(100); hooks.applyPreSendHook(query); Assert.assertEquals(20, query.toProto(requestContext).getRowsLimit()); }
Source:
public boolean isExistsQuery() { return getName().toLowerCase().startsWith("exists"); }

Target:
public boolean isExistsQuery() { return getName().toLowerCase(Locale.ROOT).startsWith("exists"); }
Source:
private boolean calculateReplicatedStateForStmt(AbstractParsedStmt stmt, Set<String> visitedTables) { if (stmt == null) { return true; } for ( StmtTableScan scan : stmt.allScans()) { boolean guess; if (scan instanceof StmtCommonTableScan) { guess = ((StmtCommonTableScan)scan).calculateReplicatedState(visitedTables); } else { guess = scan.getIsReplicated(); } if ( ! guess ) { return guess; } } return true; }

Target:
private boolean calculateReplicatedStateForStmt(AbstractParsedStmt stmt, Set<String> visitedTables) { if (stmt == null) { return true; } for ( StmtTableScan scan : stmt.allScans()) { boolean isReplicated; if (scan instanceof StmtCommonTableScan) { isReplicated = ((StmtCommonTableScan)scan).calculateReplicatedState(visitedTables); } else { isReplicated = scan.getIsReplicated(); } if ( ! isReplicated ) { return isReplicated; } } return true; }
Source:
protected boolean canDoAction() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__CREATE); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__GLUSTER_VOLUME); if (!super.canDoAction()) { return false; } volume = getParameters().getVolume(); if (volume == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_REQUIRED); return false; } setVdsGroupId(volume.getClusterId()); VDSGroup cluster = getVdsGroup(); if(cluster == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_IS_NOT_VALID); return false; } if(!cluster.supportsGlusterService()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_DOES_NOT_SUPPORT_GLUSTER); return false; } if (StringHelper.isNullOrEmpty(volume.getName())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_NAME_REQUIRED); return false; } if (volume.getVolumeType() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_TYPE_REQUIRED); return false; } if (volume.getTransportType() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_TRANSPORT_TYPE_REQUIRED); return false; } return validateBricks(volume); }

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } setVdsGroupId(volume.getClusterId()); VDSGroup cluster = getVdsGroup(); if (cluster == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_IS_NOT_VALID); return false; } if (!cluster.supportsGlusterService()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_DOES_NOT_SUPPORT_GLUSTER); return false; } return validateBricks(volume); }
Source:
public void detachNodeFailInPassiveAtPrepare() throws Exception { final int activeId = findActive(1).getAsInt(); final int passiveId = findPassives(1)[0]; String propertySettingString = "stripe.1.node." + passiveId + ".tc-properties.detachStatus=prepareDeletion-failure"; assertThat(configToolInvocation("set", "-s", "localhost:" + getNodePort(1, 1), "-c", propertySettingString), is(successful())); out.clearLog(1, passiveId); assertThat( configToolInvocation("detach", "-f", "-d", "localhost:" + getNodePort(1, activeId), "-s", "localhost:" + getNodePort(1, passiveId)), containsOutput("Two-Phase commit failed")); waitUntil(out.getLog(1, passiveId), containsLog("Restarting the server")); waitUntil(out.getLog(1, passiveId), containsLog("Moved to State[ PASSIVE-STANDBY ]")); }

Target:
public void detachNodeFailInPassiveAtPrepare() throws Exception { final int activeId = findActive(1).getAsInt(); final int passiveId = findPassives(1)[0]; String propertySettingString = "stripe.1.node." + passiveId + ".tc-properties.detachStatus=prepareDeletion-failure"; assertThat(configToolInvocation("set", "-s", "localhost:" + getNodePort(1, 1), "-c", propertySettingString), is(successful())); assertThat( configToolInvocation("detach", "-f", "-d", "localhost:" + getNodePort(1, activeId), "-s", "localhost:" + getNodePort(1, passiveId)), containsOutput("Two-Phase commit failed")); assertThat(getUpcomingCluster("localhost", getNodePort(1, activeId)).getNodeCount(), is(equalTo(2))); assertThat(getRuntimeCluster("localhost", getNodePort(1, activeId)).getNodeCount(), is(equalTo(2))); assertThat(getUpcomingCluster("localhost", getNodePort(1, passiveId)).getNodeCount(), is(equalTo(2))); assertThat(getRuntimeCluster("localhost", getNodePort(1, passiveId)).getNodeCount(), is(equalTo(2))); withTopologyService(1, activeId, topologyService -> assertTrue(topologyService.isActivated())); withTopologyService(1, passiveId, topologyService -> assertTrue(topologyService.isActivated())); }
Source:
public void benchNioWavTrack() throws Exception { WavTrackImpl wavTrackImpl = new WavTrackImpl(url); boolean isEOMReached = false; while (!isEOMReached) { Frame process = wavTrackImpl.process(0); isEOMReached = process.isEOM(); } wavTrackImpl.close(); }

Target:
public void benchNioWavTrack() throws Exception { try { rsp = new CachedRemoteStreamProvider(10); wavTrackImpl = new WavTrackImpl(url, rsp); boolean isEOMReached = false; while (!isEOMReached) { Frame process = wavTrackImpl.process(0); isEOMReached = process.isEOM(); } }finally { wavTrackImpl.close(); } }
Source:
public void onFailure(Throwable caught) { close(); status.setContents("Monitoring is unavailable on this host. Maybe node was started with --disableMonitoring option.<br>"+ "Error message: "+ JSONUtils.getJsonErrorMessage(caught)); }

Target:
public void onFailure(Throwable caught) { close(); status.setContents("Monitoring is unavailable on this host. <br>" + "Either monitoring was disabled with the disableMonitoring option or an error occurred. <br>" + "More information are available inside the node logs."); }
Source:
protected Quip getRandomQuip(QuipType quipType, Queue<String> recentlyUsedQuips){ QuipStore quipStore = QuipStore.getInstance(); LOG.debug("Recently used "+quipType.toString().toLowerCase()+"s in user session:\n"+recentlyUsedQuips.toString()); int maxQuipHistorySize = determineMaxQuipHistorySize(quipStore.getQuips(quipType).size()); Quip quip = quipStore.getRandomQuip(quipType); while(recentlyUsedQuips.contains(quip.getQuipGroup())){ quip = quipStore.getRandomQuip(quipType); } recentlyUsedQuips.add(quip.getQuipGroup()); while(recentlyUsedQuips.size() > maxQuipHistorySize){ recentlyUsedQuips.remove(); } LOG.debug(quipType.toString().toLowerCase()+" being used ("+quip.getQuipGroup()+"): "+quip.getText()); return quip; }

Target:
protected Quip getRandomQuip(QuipType quipType, Queue<String> recentlyUsedQuips){ QuipStore quipStore = QuipStore.getInstance(); LOG.debug("Recently used "+quipType.toString().toLowerCase()+"s in user session:\n"+recentlyUsedQuips.toString()); int maxQuipHistorySize = determineMaxQuipHistorySize(quipStore.getQuips(quipType).size()); Quip quip = quipStore.getRandomQuip(quipType); int rerolls = 0; while(recentlyUsedQuips.contains(quip.getQuipGroup()) && rerolls < MAX_QUIP_REROLLS){ quip = quipStore.getRandomQuip(quipType); rerolls++; } recentlyUsedQuips.add(quip.getQuipGroup()); while(recentlyUsedQuips.size() > maxQuipHistorySize){ recentlyUsedQuips.remove(); } LOG.debug(quipType.toString().toLowerCase()+" being used ("+quip.getQuipGroup()+"): "+quip.getText()); return quip; }
Source:
private void persistDiffPreferences() { setEnabled(false); listenablePrefs.save(new GerritCallback<VoidResult>() { @Override public void onSuccess(VoidResult result) { setEnabled(true); } @Override public void onFailure(Throwable caught) { setEnabled(true); } }); }

Target:
private void persistDiffPreferences() { setEnabled(false); DiffPreferenceInput in = DiffPreferenceInput.create(); final AccountDiffPreference p = listenablePrefs.get(); in.fromAccountDiffPreference(p); AccountApi.self().view("preferences.diff") .put(in, new AsyncCallback<JavaScriptObject>() { @Override public void onSuccess(JavaScriptObject result) { Gerrit.setAccountDiffPreference(p); setEnabled(true); } @Override public void onFailure(Throwable caught) { setEnabled(true); } }); }
Source:
public void start(StartContext context) { healthReporter = new HealthReporter(emptyLivenessChecksStatus, emptyReadinessChecksStatus); modelControllerClient = modelControllerClientFactory.get().createClient(managementExecutor.get()); if (System.getProperty("__MP_HEALTH_TCK_DISABLE_SERVER_CHECKS") == null) { healthReporter.addServerReadinessCheck(new ServerStateCheck(modelControllerClient), Thread.currentThread().getContextClassLoader()); healthReporter.addServerReadinessCheck(new NoBootErrorsCheck(modelControllerClient), Thread.currentThread().getContextClassLoader()); healthReporter.addServerReadinessCheck(new DeploymentsStatusCheck(modelControllerClient), Thread.currentThread().getContextClassLoader()); } HealthCheckResponse.setResponseProvider(new ResponseProvider()); }

Target:
public void start(StartContext context) { final boolean defaultServerProceduresDisabled = ConfigProvider.getConfig().getOptionalValue("mp.health.disable-default-procedures", Boolean.class).orElse(false); healthReporter = new HealthReporter(emptyLivenessChecksStatus, emptyReadinessChecksStatus, defaultServerProceduresDisabled); modelControllerClient = modelControllerClientFactory.get().createClient(managementExecutor.get()); if (!defaultServerProceduresDisabled) { healthReporter.addServerReadinessCheck(new ServerStateCheck(modelControllerClient), Thread.currentThread().getContextClassLoader()); healthReporter.addServerReadinessCheck(new NoBootErrorsCheck(modelControllerClient), Thread.currentThread().getContextClassLoader()); healthReporter.addServerReadinessCheck(new DeploymentsStatusCheck(modelControllerClient), Thread.currentThread().getContextClassLoader()); } HealthCheckResponse.setResponseProvider(new ResponseProvider()); }
Source:
public void filter_users_where_not_a_member_of_group() throws Exception { Group expectedGroup = getGroupByName(NAME_GROUP_TWO); assertNotContainsUser(expectedGroup, TEST_USER_ID); SCIMSearchResult<User> result = searchUser(String.format("not(groups eq \"%s\")", expectedGroup.getId())); assertThat(String.format("The user %s is in the group %s but should not be!", TEST_USER_NAME, NAME_GROUP_TWO), result.getResources(), not(hasItem(new User.Builder(TEST_USER_NAME).setId(TEST_USER_ID).build()))); }

Target:
public void filter_users_where_not_a_member_of_group() throws Exception { final SCIMSearchResult<User> result = searchUser("not(groups eq \"44e8645f-a0ff-4b5b-849e-d9f83b9a9bd9\")"); final User expectedUser = new User.Builder(TEST_USER_NAME).setId("cef9452e-00a9-4cec-a086-d171374ffbef") .build(); assertThat("The user marissa is in the group test_group02 but should not be!", result.getResources(), not(hasItem(expectedUser))); }
Source:
public void resendVerificationToken(ChannelType type, AccountId accountId) { checkNotNull(type); checkNotNull(accountId); Study study = studyService.getStudy(accountId.getStudyId()); Account account = accountDao.getAccount(accountId); if (account != null) { if (type == ChannelType.EMAIL) { sendEmailVerificationToken(study, account.getId(), account.getEmail()); } else if (type == ChannelType.PHONE) { sendPhoneVerificationToken(study, account.getId(), account.getPhone()); } } }

Target:
public void resendVerificationToken(ChannelType type, AccountId accountId) { checkNotNull(accountId); Study study = studyService.getStudy(accountId.getStudyId()); Account account = accountDao.getAccount(accountId); if (account != null) { if (type == ChannelType.EMAIL) { sendEmailVerificationToken(study, account.getId(), account.getEmail()); } else if (type == ChannelType.PHONE) { sendPhoneVerificationToken(study, account.getId(), account.getPhone()); } else { throw new UnsupportedOperationException("Channel type not implemented"); } } }
Source:
public Response registerDataFileAll() { Integer count = fileService.findAll().size(); Integer successes = 0; Integer alreadyRegistered = 0; logger.info("Starting to register " + count + " files. " + new Date()); for (DataFile df : fileService.findAll()) { try { if ((df.getIdentifier() == null || df.getIdentifier().isEmpty())&& df.isReleased()) { User u =findAuthenticatedUserOrDie(); DataverseRequest r = createDataverseRequest(u); execCommand(new RegisterDvObjectCommand(r, df)); successes++; if (successes % 100 == 0){ logger.info(successes + " of " + count + " files registered successfully. " + new Date()); } } else { alreadyRegistered++; } } catch (WrappedResponse ex) { logger.info("Failed to register file id: "+df.getId()); Logger.getLogger(Datasets.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception e){ logger.info("Unexpected Exception: " + e.getMessage()); } } logger.info(alreadyRegistered + " of " + count + " files were already registered. " + new Date()); logger.info(successes + " of " + count + " files registered successfully. " + new Date()); return ok("Datafile registration complete." + successes + " of " + count + " files registered successfully."); }

Target:
public Response registerDataFileAll() { Integer count = fileService.findAll().size(); Integer successes = 0; Integer alreadyRegistered = 0; Integer released = 0; Integer draft = 0; logger.info("Starting to register: analyzing " + count + " files. " + new Date()); logger.info("Only unregistered, published files will be registered."); for (DataFile df : fileService.findAll()) { try { if ((df.getIdentifier() == null || df.getIdentifier().isEmpty())) { if (df.isReleased()) { released++; User u = findAuthenticatedUserOrDie(); DataverseRequest r = createDataverseRequest(u); execCommand(new RegisterDvObjectCommand(r, df)); successes++; if (successes % 100 == 0) { logger.info(successes + " of " + count + " files registered successfully. " + new Date()); } } else { draft++; logger.info(draft + " of " + count + " files not yet published"); } } else { alreadyRegistered++; logger.info(alreadyRegistered + " of " + count + " files are already registered. " + new Date()); } } catch (WrappedResponse ex) { released++; logger.info("Failed to register file id: " + df.getId()); Logger.getLogger(Datasets.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception e) { logger.info("Unexpected Exception: " + e.getMessage()); } } logger.info("Final Results:"); logger.info(alreadyRegistered + " of " + count + " files were already registered. " + new Date()); logger.info(draft + " of " + count + " files are not yet published. " + new Date()); logger.info(released + " of " + count + " unregistered, published files to register. " + new Date()); logger.info(successes + " of " + released + " unregistered, published files registered successfully. " + new Date()); return ok("Datafile registration complete." + successes + " of " + released + " unregistered, published files registered successfully."); }
Source:
public SplitEnumerator<MockSourceSplit, List<MockSourceSplit>> restoreEnumerator( SplitEnumeratorContext<MockSourceSplit> enumContext, List<MockSourceSplit> checkpoint) throws IOException { FutureNotifier futureNotifier = new FutureNotifier(); FutureCompletingBlockingQueue<RecordsWithSplitIds<int[]>> elementsQueue = new FutureCompletingBlockingQueue<>(futureNotifier); return new MockSplitEnumerator(checkpoint, enumContext); }

Target:
public SplitEnumerator<MockSourceSplit, List<MockSourceSplit>> restoreEnumerator( SplitEnumeratorContext<MockSourceSplit> enumContext, List<MockSourceSplit> checkpoint) throws IOException { return new MockSplitEnumerator(checkpoint, enumContext); }
Source:
private void refreshTreeContentFromLS() { if (symbols != null && !symbols.isDone()) { symbols.cancel(true); } lastError = null; DocumentSymbolParams params = new DocumentSymbolParams(new TextDocumentIdentifier(info.getFileUri().toString())); symbols = info.getLanguageClient().getTextDocumentService().documentSymbol(params); symbols.thenAccept((List<? extends SymbolInformation> t) -> { symbolsModel.update(t); viewer.getControl().getDisplay().asyncExec(() -> { viewer.refresh(); }); if (!InstanceScope.INSTANCE.getNode(CNFOutlinePage.ID + '.' + info.getFileUri()) .getBoolean(CNFOutlinePage.linkWithEditorPreference, true)) { return; } Display.getDefault().asyncExec(() -> { IEditorPart editorPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .getActiveEditor(); ITextOperationTarget target = editorPart.getAdapter(ITextOperationTarget.class); if (editorPart instanceof AbstractTextEditor && target instanceof ITextViewerExtension5) { ITextSelection selection = (ITextSelection) ((AbstractTextEditor) editorPart).getSelectionProvider() .getSelection(); int offset = ((ITextViewerExtension5) target).widgetOffset2ModelOffset(selection.getOffset()); CNFOutlinePage.refreshTreeSelection(viewer, offset, info.getDocument()); } }); }); symbols.exceptionally(ex -> { lastError = ex; viewer.getControl().getDisplay().asyncExec(() -> { viewer.refresh(); }); return Collections.emptyList(); }); }

Target:
private void refreshTreeContentFromLS() { if (symbols != null && !symbols.isDone()) { symbols.cancel(true); } lastError = null; DocumentSymbolParams params = new DocumentSymbolParams(new TextDocumentIdentifier(info.getFileUri().toString())); symbols = info.getLanguageClient().getTextDocumentService().documentSymbol(params); symbols.thenAccept((List<? extends SymbolInformation> t) -> { symbolsModel.update(t); viewer.getControl().getDisplay().asyncExec(() -> { viewer.refresh(); }); if (!InstanceScope.INSTANCE.getNode(CNFOutlinePage.ID + '.' + info.getFileUri()) .getBoolean(CNFOutlinePage.linkWithEditorPreference, true)) { return; } Display.getDefault().asyncExec(() -> { IEditorPart editorPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .getActiveEditor(); if (editorPart instanceof AbstractTextEditor) { ITextSelection selection = (ITextSelection) ((AbstractTextEditor) editorPart).getSelectionProvider() .getSelection(); CNFOutlinePage.refreshTreeSelection(viewer, selection.getOffset(), info.getDocument()); } }); }); symbols.exceptionally(ex -> { lastError = ex; viewer.getControl().getDisplay().asyncExec(() -> { viewer.refresh(); }); return Collections.emptyList(); }); }
Source:
public boolean applies(UUID objectId, Ability source, UUID affectedControllerId, Game game) { if (!(source instanceof FlashbackAbility) && affectedControllerId.equals(source.getControllerId())) { Player player = game.getPlayer(affectedControllerId); Card card = game.getCard(objectId); if (card != null && player != null && card.equals(player.getGraveyard().getTopCard(game)) && (card.isInstant() || card.isSorcery()) && game.getState().getZone(objectId).equals(Zone.GRAVEYARD)) { return true; } } return false; }

Target:
public boolean applies(UUID objectId, Ability source, UUID affectedControllerId, Game game) { if (!(source instanceof FlashbackAbility) && affectedControllerId.equals(source.getControllerId())) { Player player = game.getPlayer(affectedControllerId); Card card = game.getCard(objectId); if (card != null && player != null && card.equals(player.getGraveyard().getTopCard(game)) && StaticFilters.FILTER_CARD_INSTANT_OR_SORCERY.match(card, game) && game.getState().getZone(objectId) == Zone.GRAVEYARD) { game.getState().setValue("BosiumStrip", card); return true; } } return false; }
Source:
public void connectionLost(Throwable t) { logger.error(String.format("MQTT connection to broker '{}' was lost", name), t); started = false; logger.info("Starting connection helper to periodically try restore connection to broker '{}'", name); MqttBrokerConnectionHelper helper = new MqttBrokerConnectionHelper(this); reconnectTimer = new Timer(true); reconnectTimer.schedule(helper, 10000, RECONNECT_FREQUENCY); }

Target:
public void connectionLost(Throwable t) { logger.error("MQTT connection to broker was lost", t); started = false; logger.info("Starting connection helper to periodically try restore connection to broker '{}'", name); MqttBrokerConnectionHelper helper = new MqttBrokerConnectionHelper(this); reconnectTimer = new Timer(true); reconnectTimer.schedule(helper, 10000, RECONNECT_FREQUENCY); }
Source:
public FileSegment<TrecCollection.Document> createFileSegment(Path p) throws IOException { return new FileSegment<>(p); }

Target:
public FileSegment<Document> createFileSegment(Path p) throws IOException { return new FileSegment<>(p); }
Source:
public int compareExcludingSensitivity(PointSensitivity other) { if (other instanceof ZeroRateSensitivity) { ZeroRateSensitivity otherZero = (ZeroRateSensitivity) other; return ComparisonChain.start() .compare(currencyCurve, otherZero.currencyCurve) .compare(date, otherZero.date) .compare(currency, otherZero.currency) .result(); } return getClass().getSimpleName().compareTo(other.getClass().getSimpleName()); }

Target:
public int compareExcludingSensitivity(PointSensitivity other) { if (other instanceof ZeroRateSensitivity) { ZeroRateSensitivity otherZero = (ZeroRateSensitivity) other; return ComparisonChain.start() .compare(curveCurrency, otherZero.curveCurrency) .compare(currency, otherZero.currency) .compare(date, otherZero.date) .result(); } return getClass().getSimpleName().compareTo(other.getClass().getSimpleName()); }
Source:
private void updateActionBarTitle(int page) { String sura = QuranInfo.getSuraNameFromPage(this, page, true); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(sura); String desc = QuranInfo.getPageSubtitle(this, page); actionBar.setSubtitle(desc); } }

Target:
private void updateActionBarTitle(int page) { String sura = QuranInfo.getSuraNameFromPage(this, page, true); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { translationsSpinner.setVisibility(View.GONE); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(sura); String desc = QuranInfo.getPageSubtitle(this, page); actionBar.setSubtitle(desc); } }
Source:
public GuiContainer createGui(InventoryPlayer inventoryplayer, World world, BlockPos pos) { return new GuiTinkerTank((ContainerTinkerTank) createContainer(inventoryplayer, world, pos), this); }

Target:
public GuiContainer createGui(InventoryPlayer inventoryplayer, World world, BlockPos pos) { return new GuiTinkerTank(createContainer(inventoryplayer, world, pos), this); }
Source:
public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; final HttpServletResponse response = (HttpServletResponse) servletResponse; boolean isGzipped = Optional .ofNullable(request.getHeader(CONTENT_ENCODING)) .map(encoding -> encoding.contains("gzip")) .orElse(false); if (isGzipped && !POST.equals(request.getMethod())) { throw new IllegalStateException(request.getMethod() + " method doesn't support gzip content encoding"); } else if (isGzipped) { request = new GzipServletRequestWrapper(request); } chain.doFilter(request, response); }

Target:
public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; final boolean isGzipped = Optional .ofNullable(request.getHeader(CONTENT_ENCODING)) .map(encoding -> encoding.contains("gzip")) .orElse(false); if (isGzipped && !POST.equals(request.getMethod())) { reportNotAcceptableError((HttpServletResponse) servletResponse, request); return; } else if (isGzipped) { request = new GzipServletRequestWrapper(request); } chain.doFilter(request, servletResponse); }
Source:
public void convertEmptyAttrValueToNull(Attribute attribute) { if(attribute.getValue() == null) { return; } if (attribute.getValue() instanceof String) { if(((String)attribute.getValue()).matches("\\s*")) { attribute.setValue(null); } } else if (attribute.getValue() instanceof Boolean) { if(attribute.getValue().equals(Boolean.FALSE)) { attribute.setValue(null); } } else if (attribute.getValue() instanceof ArrayList) { if(((ArrayList)attribute.getValue()).isEmpty()) { attribute.setValue(null); } } else if (attribute.getValue() instanceof HashMap) { if(((HashMap)attribute.getValue()).isEmpty()) { attribute.setValue(null); } } }

Target:
public void convertEmptyAttrValueToNull(Attribute attribute) throws ConsistencyErrorException { if(attribute.getValue() == null) { return; } if (attribute.getValue() instanceof Integer) { return; } if (attribute.getValue() instanceof String) { if(((String)attribute.getValue()).matches("\\s*")) { attribute.setValue(null); } } else if (attribute.getValue() instanceof Boolean) { if(attribute.getValue().equals(Boolean.FALSE)) { attribute.setValue(null); } } else if (attribute.getValue() instanceof ArrayList) { if(((ArrayList)attribute.getValue()).isEmpty()) { attribute.setValue(null); } } else if (attribute.getValue() instanceof LinkedHashMap) { if(((LinkedHashMap)attribute.getValue()).isEmpty()) { attribute.setValue(null); } } else { throw new ConsistencyErrorException("Invalid attribute value type: " + attribute.getType() + " class: " + attribute.getValue().getClass().getName()); } }
Source:
public XStreamMarshaller (List<DMNExtensionRegister> extensionRegisters) { this.extensionRegisters = new ArrayList<DMNExtensionRegister>(); this.extensionRegisters.addAll(extensionRegisters); }

Target:
public XStreamMarshaller (List<DMNExtensionRegister> extensionRegisters) { this.extensionRegisters.addAll(extensionRegisters); }
Source:
public synchronized void onContent(Response response, ByteBuffer content) { int length = content.remaining(); size += length; if (size > maxLength) { response.abort(new ResponseTooLargeException()); return; } while (length > 0) { allocateCurrentArray(); int readLength = min(length, currentArray.length - nextBytes); content.get(currentArray, nextBytes, readLength); length -= readLength; nextBytes += readLength; } }

Target:
public synchronized void onContent(Response response, ByteBuffer content) { int length = content.remaining(); size += length; if (size > maxLength) { response.abort(new ResponseTooLargeException()); return; } while (length > 0) { if (currentBufferPosition >= currentBuffer.length) { allocateCurrentBuffer(); } int readLength = min(length, currentBuffer.length - currentBufferPosition); content.get(currentBuffer, currentBufferPosition, readLength); length -= readLength; currentBufferPosition += readLength; } }
Source:
public long getUpdateCount() { return Math.max(parent.getUpdateCount(), getPropCacheAccessor().getZooCache().getUpdateCount()); }

Target:
public long getUpdateCount() { return parent.getUpdateCount() + getPropCacheAccessor().getZooCache().getUpdateCount(); }
Source:
public long getQueuedQueries() { return getQuerySvc().getQueuedQueriesCount(); }

Target:
public long getQueuedQueries() { return queuedQueries.getValue(); }
Source:
void convertToReftable(boolean writeLogs, boolean backup) throws IOException { File newRefs = new File(getDirectory(), "refs.new"); File reftableDir = new File(getDirectory(), Constants.REFTABLE); if (reftableDir.exists() && reftableDir.listFiles().length > 0) { throw new IOException(JGitText.get().reftableDirExists); } FileReftableDatabase.convertFrom(this, newRefs, writeLogs); File refsFile = new File(getDirectory(), "refs"); File packedRefs = new File(getDirectory(), Constants.PACKED_REFS); File logsDir = new File(getDirectory(), Constants.LOGS); List<String> additional = this.getRefDatabase().getAdditionalRefs().stream().map(r -> r.getName()).collect( Collectors.toList()); additional.add(Constants.HEAD); if (backup) { FileUtils.rename(refsFile, new File(getDirectory(), "refs.old")); if (packedRefs.exists()) { FileUtils.rename(packedRefs, new File(getDirectory(), Constants.PACKED_REFS + ".old")); } if (logsDir.exists()) { FileUtils.rename(logsDir, new File(getDirectory(), Constants.LOGS + ".old")); } for (String r : additional) { FileUtils.rename(new File(getDirectory(), r), new File(getDirectory(), r + ".old")); } } else { packedRefs.delete(); FileUtils.delete(logsDir, FileUtils.RECURSIVE); FileUtils.delete(refsFile, FileUtils.RECURSIVE); for (String r : additional) { new File(getDirectory(), r).delete(); } } FileUtils.rename(newRefs, refsFile); refs.close(); refs = new FileReftableDatabase(this, refsFile); }

Target:
void convertToReftable(boolean writeLogs, boolean backup) throws IOException { File newRefs = new File(getDirectory(), "refs.new"); File reftableDir = new File(getDirectory(), Constants.REFTABLE); if (reftableDir.exists() && reftableDir.listFiles().length > 0) { throw new IOException(JGitText.get().reftableDirExists); } FileReftableDatabase.convertFrom(this, newRefs, writeLogs); File refsFile = new File(getDirectory(), "refs"); File packedRefs = new File(getDirectory(), Constants.PACKED_REFS); File logsDir = new File(getDirectory(), Constants.LOGS); List<String> additional = getRefDatabase().getAdditionalRefs().stream() .map(Ref::getName).collect(toList()); additional.add(Constants.HEAD); if (backup) { FileUtils.rename(refsFile, new File(getDirectory(), "refs.old")); if (packedRefs.exists()) { FileUtils.rename(packedRefs, new File(getDirectory(), Constants.PACKED_REFS + ".old")); } if (logsDir.exists()) { FileUtils.rename(logsDir, new File(getDirectory(), Constants.LOGS + ".old")); } for (String r : additional) { FileUtils.rename(new File(getDirectory(), r), new File(getDirectory(), r + ".old")); } } else { packedRefs.delete(); FileUtils.delete(logsDir, FileUtils.RECURSIVE); FileUtils.delete(refsFile, FileUtils.RECURSIVE); for (String r : additional) { new File(getDirectory(), r).delete(); } } FileUtils.rename(newRefs, refsFile); refs.close(); refs = new FileReftableDatabase(this, refsFile); }
Source:
private void initTemplates() { if (templateContainer == null) { return; } for (TemplateData template : templateContainer.getTemplateData()) { add(template); } }

Target:
private void initTemplates() { if (templateContainer == null) { return; } addAll(templateContainer.getTemplateData()); }
Source:
public void testFailedMetadataUpdate() throws Throwable { Path testFile = path("testFile"); FSDataOutputStream outputStream = fs.create(testFile); outputStream.write(1); useIOExceptionMetadataStore(); if (failOnError) { Exception thrown = intercept(MetadataPersistenceException.class, () -> { outputStream.close(); }); assertTrue("expected MetadataPersistenceException wasn't thrown", thrown instanceof MetadataPersistenceException); assertEquals("cause didn't match original exception", ioException, thrown.getCause()); } else { outputStream.close(); assertEquals(1, fs.getInstrumentation().getCounterValue(Statistic.IGNORED_ERRORS)); } }

Target:
public void testFailedMetadataUpdate() throws Throwable { Path testFile = path("testFile"); FSDataOutputStream outputStream = fs.create(testFile); outputStream.write(1); if (failOnError) { MetadataPersistenceException thrown = intercept( MetadataPersistenceException.class, () -> { outputStream.close(); }); assertEquals("cause didn't match original exception", ioException, thrown.getCause()); } else { MetricDiff ignoredCount = new MetricDiff(fs, Statistic.IGNORED_ERRORS); outputStream.close(); ignoredCount.assertDiffEquals("ignored errors", 1); } }