auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public InterpreterResult internalInterpret(String cmd, InterpreterContext context) { this.intpContext = context; TerminalManager.getInstance().setInterpreterContext(context); if (null == terminalThread) { try { terminalPort = RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces(); terminalThread = new TerminalThread(terminalPort); terminalThread.start(); } catch (IOException e) { LOGGER.error(e.getMessage(), e); return new InterpreterResult(Code.ERROR, e.getMessage()); } for (int i = 0; i < 10 && !terminalThread.isRunning(); i++) { try { LOGGER.info("loop = " + i); Thread.sleep(500); } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); } } if (!terminalThread.isRunning()) { LOGGER.error("Terminal interpreter can not running!"); } } setParagraphConfig(); Properties properties = getProperties(); String strIpMapping = properties.getProperty("zeppelin.terminal.ip.mapping"); if (!StringUtils.isEmpty(strIpMapping)) { Gson gson = new Gson(); mapIpMapping = gson.fromJson(strIpMapping, new TypeToken<Map<String, String>>(){}.getType()); } createTerminalDashboard(context.getNoteId(), context.getParagraphId(), terminalPort); return new InterpreterResult(Code.SUCCESS); }

Target:
public InterpreterResult internalInterpret(String cmd, InterpreterContext context) { this.intpContext = context; TerminalManager.getInstance().setInterpreterContext(context); if (null == terminalThread) { try { terminalPort = RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces(); terminalThread = new TerminalThread(terminalPort); terminalThread.start(); } catch (IOException e) { LOGGER.error(e.getMessage(), e); return new InterpreterResult(Code.ERROR, e.getMessage()); } for (int i = 0; i < 10 && !terminalThread.isRunning(); i++) { try { LOGGER.info("loop = " + i); Thread.sleep(500); } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); } } if (!terminalThread.isRunning()) { LOGGER.error("Terminal interpreter can not running!"); } } setParagraphConfig(); Properties properties = getProperties(); String strIpMapping = properties.getProperty("zeppelin.terminal.ip.mapping"); if (!StringUtils.isEmpty(strIpMapping)) { mapIpMapping = gson.fromJson(strIpMapping, new TypeToken<Map<String, String>>(){}.getType()); } createTerminalDashboard(context.getNoteId(), context.getParagraphId(), terminalPort); return new InterpreterResult(Code.SUCCESS); }
Source:
public void replacesTypeWithJson() throws Exception { MatcherAssert.assertThat( new RsPrint( new RsWithType.JSON(new RsWithType(new RsEmpty(), TYPE_XML)) ).print(), Matchers.equalTo( Joiner.on(CRLF).join( HTTP_OK, String.format(CONTENT_TYPE, TYPE_JSON), "", "" ) ) ); MatcherAssert.assertThat( new RsPrint( new RsWithType.JSON( new RsWithType(new RsEmpty(), TYPE_XML), StandardCharsets.ISO_8859_1 ) ).print(), Matchers.equalTo( Joiner.on(CRLF).join( HTTP_OK, String.format( CONTENT_TYPE_WITH_CHARSET, TYPE_JSON, StandardCharsets.ISO_8859_1 ), "", "" ) ) ); }

Target:
public void replacesTypeWithJson() throws Exception { MatcherAssert.assertThat( new RsPrint( new RsWithType.JSON( new RsWithType(new RsEmpty(), RsWithTypeTest.TYPE_XML) ) ).print(), Matchers.equalTo( Joiner.on(RsWithTypeTest.CRLF).join( RsWithTypeTest.HTTP_OK, String.format( RsWithTypeTest.CONTENT_TYPE, RsWithTypeTest.TYPE_JSON ), "", "" ) ) ); MatcherAssert.assertThat( new RsPrint( new RsWithType.JSON( new RsWithType(new RsEmpty(), RsWithTypeTest.TYPE_XML), StandardCharsets.ISO_8859_1 ) ).print(), Matchers.equalTo( Joiner.on(RsWithTypeTest.CRLF).join( RsWithTypeTest.HTTP_OK, String.format( RsWithTypeTest.TYPE_WITH_CHARSET, RsWithTypeTest.TYPE_JSON, StandardCharsets.ISO_8859_1 ), "", "" ) ) ); }
Source:
public boolean isUserCompaction() { return userCompaction; }

Target:
public boolean isUserCompaction() { if (scope != IteratorScope.majc) throw new IllegalStateException( "Asked about user initiated compaction type when scope is " + scope); return userCompaction; }
Source:
private static int computeRequiredBufferNum(int numChildNodes, int combineDegree) { final int numChildrenForLastNode = numChildNodes % combineDegree; final int numCurLevelNodes = numChildNodes / combineDegree + (numChildrenForLastNode > 1 ? 1 : 0); final int numChildOfParentNodes = numCurLevelNodes + (numChildrenForLastNode == 1 ? 1 : 0); if (numChildOfParentNodes == 1) { return numCurLevelNodes; } else { return numCurLevelNodes + computeRequiredBufferNum(numChildOfParentNodes, combineDegree); } }

Target:
private int computeRequiredBufferNum(int numChildNodes, int combineDegree) { final int numChildrenForLastNode = numChildNodes % combineDegree; final int numCurLevelNodes = numChildNodes / combineDegree + (numChildrenForLastNode > 1 ? 1 : 0); final int numChildOfParentNodes = numCurLevelNodes + (numChildrenForLastNode == 1 ? 1 : 0); if (numChildOfParentNodes == 1) { return numCurLevelNodes; } else { return numCurLevelNodes + computeRequiredBufferNum(numChildOfParentNodes, intermediateCombineDegree); } }
Source:
public void deleteObservation( final Integer studyId, final Integer datasetId, final Integer observationUnitId, final Integer observationId) { this.studyValidator.validate(studyId, true); this.datasetValidator.validateDataset(studyId, datasetId, false); this.observationValidator.validateObservation(studyId, datasetId, observationUnitId, observationId, null); final Integer observableId = this.middlewareDatasetService.getPhenotype(observationUnitId, observationId).getObservableId(); this.middlewareDatasetService.deletePhenotype(observationId); this.middlewareDatasetService.updateDependentPhenotypesAsOutOfSync(observableId, observationUnitId); }

Target:
public void deleteObservation( final Integer studyId, final Integer datasetId, final Integer observationUnitId, final Integer observationId) { this.studyValidator.validate(studyId, true); this.datasetValidator.validateDataset(studyId, datasetId); this.observationValidator.validateObservation(studyId, datasetId, observationUnitId, observationId, null); this.middlewareDatasetService.deletePhenotype(observationId); }
Source:
public void doCreateAccount(@NonNull String token) { progressDialog.show(); String email = null; if (emailEdit.getText().length() != 0) { email = emailEdit.getText().toString(); } new CreateAccountClient().request(wiki, usernameEdit.getText().toString(), passwordEdit.getText().toString(), passwordRepeatEdit.getText().toString(), token, email, captchaHandler.isActive() ? captchaHandler.captchaId() : "null", captchaHandler.isActive() ? captchaHandler.captchaWord() : "null", new CreateAccountClient.Callback() { @Override public void success(@NonNull Call<MwCreateAccountResponse> call, @NonNull CreateAccountSuccessResult result) { if (!progressDialog.isShowing()) { return; } createAccountResult = result; progressDialog.dismiss(); captchaHandler.cancelCaptcha(); funnel.logSuccess(); hideSoftKeyboard(CreateAccountActivity.this); Intent resultIntent = new Intent(); resultIntent.putExtra("username", ((CreateAccountSuccessResult) result).getUsername()); resultIntent.putExtra("password", passwordEdit.getText().toString()); setResult(RESULT_ACCOUNT_CREATED, resultIntent); finish(); } @Override public void failure(@NonNull Call<MwCreateAccountResponse> call, @NonNull CreateAccountResult result) { if (!progressDialog.isShowing()) { return; } createAccountResult = result; progressDialog.dismiss(); captchaHandler.cancelCaptcha(); if (result.getMessage() != null) { handleError(result.getMessage()); } } @Override public void failure(@NonNull Call<MwCreateAccountResponse> call, @NonNull Throwable caught) { L.d("Caught " + caught.toString()); if (!progressDialog.isShowing()) { return; } progressDialog.dismiss(); FeedbackUtil.showError(CreateAccountActivity.this, caught); } }); }

Target:
public void doCreateAccount(@NonNull String token) { progressDialog.show(); String email = null; if (emailEdit.getText().length() != 0) { email = emailEdit.getText().toString(); } String password = passwordEdit.getText().toString(); String repeat = passwordInput.isPasswordVisible() ? password : passwordRepeatEdit.getText().toString(); createAccountClient.request(wiki, usernameEdit.getText().toString(), password, repeat, token, email, captchaHandler.isActive() ? captchaHandler.captchaId() : "null", captchaHandler.isActive() ? captchaHandler.captchaWord() : "null", new CreateAccountClient.Callback() { @Override public void success(@NonNull Call<CreateAccountResponse> call, @NonNull CreateAccountSuccessResult result) { if (!progressDialog.isShowing()) { return; } createAccountResult = result; progressDialog.dismiss(); captchaHandler.cancelCaptcha(); funnel.logSuccess(); hideSoftKeyboard(CreateAccountActivity.this); Intent resultIntent = new Intent(); resultIntent.putExtra("username", result.getUsername()); resultIntent.putExtra("password", passwordEdit.getText().toString()); setResult(RESULT_ACCOUNT_CREATED, resultIntent); finish(); } @Override public void failure(@NonNull Call<CreateAccountResponse> call, @NonNull Throwable caught) { L.e(caught.toString()); if (!progressDialog.isShowing()) { return; } progressDialog.dismiss(); FeedbackUtil.showError(CreateAccountActivity.this, caught); } }); }
Source:
public Blob getBlobFromJSON(ObjectNode jsonObject) { Blob blob = null; if (!jsonObject.has("upload-batch")) { return null; } final String batchId = jsonObject.get("upload-batch").getTextValue(); String fileId = null; if (jsonObject.has("upload-fileId")) { fileId = jsonObject.get("upload-fileId").getTextValue(); } if (fileId != null) { BatchManager bm = Framework.getLocalService(BatchManager.class); blob = bm.getBlob(batchId, fileId); final boolean drop = !Boolean.parseBoolean( RequestContext.getActiveContext().getRequest().getHeader(BatchManagerConstants.NO_DROP_FLAG)); if (RequestContext.getActiveContext() != null && drop) { RequestContext.getActiveContext().addRequestCleanupHandler(new RequestCleanupHandler() { @Override public void cleanup(HttpServletRequest request) { BatchManager bm = Framework.getLocalService(BatchManager.class); bm.clean(batchId); } }); } } return blob; }

Target:
public Blob getBlobFromJSON(ObjectNode jsonObject) { Blob blob = null; if (!jsonObject.has("upload-batch")) { return null; } final String batchId = jsonObject.get("upload-batch").getTextValue(); String fileId = null; if (jsonObject.has("upload-fileId")) { fileId = jsonObject.get("upload-fileId").getTextValue(); } if (fileId != null) { BatchManager bm = Framework.getLocalService(BatchManager.class); blob = bm.getBlob(batchId, fileId); if (RequestContext.getActiveContext() != null) { final boolean drop = !Boolean.parseBoolean( RequestContext.getActiveContext().getRequest().getHeader(BatchManagerConstants.NO_DROP_FLAG)); if (drop) { RequestContext.getActiveContext().addRequestCleanupHandler(new RequestCleanupHandler() { @Override public void cleanup(HttpServletRequest request) { BatchManager bm = Framework.getLocalService(BatchManager.class); bm.clean(batchId); } }); } } } return blob; }
Source:
public void isNodeRegistered (String hostname, String token) throws CanNotCallChefException { String response = "RESPONSE"; int time = 10000; int check_time=10000; while (!response.contains(hostname)) { try { log.info("Checking node : " + hostname + " time:" + time); if (time > MAX_TIME) { String errorMesg = "Node " + hostname + " is not registered in ChefServer"; log.info(errorMesg); throw new CanNotCallChefException(errorMesg); } Thread.sleep(check_time); response = getNodes (token); time = time+ check_time; } catch (Exception e) { log.warn(e.getMessage()); String errorMesg = "Node " + hostname + " is not registered in ChefServer"; log.info(errorMesg); throw new CanNotCallChefException(errorMesg); } } log.debug ("Node " + hostname + " is registered in ChefServer"); }

Target:
public void isNodeRegistered (String hostname, String token) throws CanNotCallPuppetException { String response = "RESPONSE"; int time = 10000; int check_time=10000; while (!response.contains(hostname)) { try { log.info("Checking node : " + hostname + " time:" + time); if (time > MAX_TIME) { String errorMesg = "Node " + hostname + " is not registered in puppet master"; log.info(errorMesg); throw new CanNotCallPuppetException(errorMesg); } Thread.sleep(check_time); response = getNodes (token); time = time+ check_time; } catch (Exception e) { log.warn(e.getMessage()); String errorMesg = "Node " + hostname + " is not registered the puppet master " + e.getMessage(); log.info(errorMesg); throw new CanNotCallPuppetException(errorMesg); } } log.debug ("Node " + hostname + " is registered in puppet master"); }
Source:
public void addAlternativeSequenceName(final String name) { if (!mSequenceName.equals(name) && ! mAlternativeSequenceName.contains(name) ) { mAlternativeSequenceName.add(name); } }

Target:
public void addAlternativeSequenceName(final String name) { validateAltRegExp(name); final Set<String> altSequences = getAlternativeSequenceNames(); if (!mSequenceName.equals(name) && ! altSequences.contains(name) ) { altSequences.add(name); } encodeAltSequences(altSequences); }
Source:
public String toString() { return "Actor{" + "name='" + name + '\'' + ", description='" + description + '\'' + ", users=" + users + ", groups=" + groups + ", roles=" + roles + ", memberships=" + memberships + '}'; }

Target:
public String toString() { return new ToStringBuilder(this) .append("name", name) .append("description", description) .append("users", users) .append("groups", groups) .append("roles", roles) .append("memberships", memberships) .toString(); }
Source:
public ServiceCheck(String name, int status) { this.name = name; this.status = status; }

Target:
public ServiceCheck(String name, int status) { this(name, status, null, null, null); }
Source:
public PinotExpression visitCall(CallExpression call, Map<VariableReferenceExpression, Selection> context) { String displayName = call.getDisplayName().toLowerCase(ENGLISH); if (PROSCRIBED_FUNCTIONS.contains(displayName)) { throw new PinotException(PINOT_UNSUPPORTED_EXPRESSION, Optional.empty(), "Unsupported function in pinot aggregation: " + call); } if (displayName.equals("cast")) { return handleCast(call, context); } FunctionMetadata functionMetadata = functionMetadataManager.getFunctionMetadata(call.getFunctionHandle()); Optional<OperatorType> operatorTypeOptional = functionMetadata.getOperatorType(); if (operatorTypeOptional.isPresent()) { OperatorType operatorType = operatorTypeOptional.get(); if (operatorType.isArithmeticOperator()) { return handleArithmeticExpression(call, operatorType, context); } else if (operatorType.isComparisonOperator()) { throw new PinotException(PINOT_UNSUPPORTED_EXPRESSION, Optional.empty(), "Comparison operator not supported: " + call); } } return handleFunction(call, context); }

Target:
public PinotExpression visitCall(CallExpression call, Map<VariableReferenceExpression, Selection> context) { return basicCallHandling(call, context).orElseThrow(() -> new PinotException(PINOT_UNSUPPORTED_EXPRESSION, Optional.empty(), "Call not supported: " + call)); }
Source:
public void startKieServer() { if (server != null) { throw new RuntimeException("Kie execution server is already created!"); } System.setProperty(KieServerConstants.CFG_BYPASS_AUTH_USER, "true"); System.setProperty(KieServerConstants.CFG_HT_CALLBACK, "custom"); System.setProperty(KieServerConstants.CFG_HT_CALLBACK_CLASS, "org.kie.server.integrationtests.jbpm.util.FixedUserGroupCallbackImpl"); System.setProperty(KieServerConstants.CFG_PERSISTANCE_DS, "jdbc/jbpm-ds"); System.setProperty(KieServerConstants.CFG_PERSISTANCE_TM, "org.hibernate.service.jta.platform.internal.BitronixJtaPlatform"); System.setProperty(KieServerConstants.KIE_SERVER_CONTROLLER, TestConfig.getControllerHttpUrl()); System.setProperty(KieServerConstants.CFG_KIE_CONTROLLER_USER, TestConfig.getUsername()); System.setProperty(KieServerConstants.CFG_KIE_CONTROLLER_PASSWORD, TestConfig.getPassword()); System.setProperty(KieServerConstants.KIE_SERVER_LOCATION, TestConfig.getEmbeddedKieServerHttpUrl()); System.setProperty(KieServerConstants.KIE_SERVER_STATE_REPO, "./target"); if (KieServerEnvironment.getServerId() == null) { KieServerEnvironment.setServerId(KieServerBaseIntegrationTest.class.getSimpleName() + "@" + serverIdSuffixDateFormat.format(new Date())); KieServerEnvironment.setServerName("KieServer"); } server = new TJWSEmbeddedJaxrsServer(); server.setPort(TestConfig.getKieServerAllocatedPort()); server.start(); kieServer = new KieServerImpl(); server.getDeployment().getRegistry().addSingletonResource(new KieServerRestImpl(kieServer)); List<KieServerExtension> extensions = kieServer.getServerExtensions(); for (KieServerExtension extension : extensions) { List<Object> components = extension.getAppComponents(SupportedTransports.REST); for (Object component : components) { server.getDeployment().getRegistry().addSingletonResource(component); } } server.getDeployment().setProviderFactory(JacksonRestEasyTestConfig.createRestEasyProviderFactory()); }

Target:
public void startKieServer() { if (server != null) { throw new RuntimeException("Kie execution server is already created!"); } setKieServerProperties(); registerKieServerId(); server = new TJWSEmbeddedJaxrsServer(); server.setPort(TestConfig.getKieServerAllocatedPort()); server.start(); addServerSingltonResources(); }
Source:
private int[] calculateDetailWidths(int fullSize) { int[] hints = new int[mHints.length]; for (int i = 0; i < mHints.length; i++) { if (mHints[i] == null) { hints[i] = -1; } else if (mHints[i].contains("%")) { hints[i] = fullSize * Integer.parseInt(mHints[i].substring(0, mHints[i].indexOf("%"))) / 100; } else { hints[i] = Integer.parseInt(mHints[i]); } } int claimedSpace = 0; int indeterminateColumns = 0; for (int hint : hints) { if (hint != -1) { claimedSpace += hint; } else { indeterminateColumns++; } } if ( fullSize < claimedSpace + indeterminateColumns || fullSize > claimedSpace && indeterminateColumns == 0 ) { claimedSpace += indeterminateColumns; for (int i = 0; i < hints.length; i++) { if (hints[i] == -1) { hints[i] = 1; } else { hints[i] = fullSize * hints[i] / claimedSpace; } } } else if (indeterminateColumns > 0) { int defaultWidth = (fullSize - claimedSpace) / indeterminateColumns; for (int i = 0; i < hints.length; i++) { if (hints[i] == -1) { hints[i] = defaultWidth; } } } return hints; }

Target:
private int[] calculateDetailWidths(int fullSize) { int[] widths = new int[mHints.length]; for (int i = 0; i < mHints.length; i++) { if (mHints[i] == null) { widths[i] = -1; } else if (mHints[i].contains("%")) { widths[i] = fullSize * Integer.parseInt(mHints[i].substring(0, mHints[i].indexOf("%"))) / 100; } else { widths[i] = Integer.parseInt(mHints[i]); } } int claimedSpace = 0; int indeterminateColumns = 0; for (int width : widths) { if (width != -1) { claimedSpace += width; } else { indeterminateColumns++; } } if (fullSize < claimedSpace + indeterminateColumns || (fullSize > claimedSpace && indeterminateColumns == 0)) { claimedSpace += indeterminateColumns; for (int i = 0; i < widths.length; i++) { if (widths[i] == -1) { widths[i] = 1; } else { widths[i] = fullSize * widths[i] / claimedSpace; } } } else if (indeterminateColumns > 0) { int defaultWidth = (fullSize - claimedSpace) / indeterminateColumns; for (int i = 0; i < widths.length; i++) { if (widths[i] == -1) { widths[i] = defaultWidth; } } } return widths; }
Source:
private void onGoogleSignInAccountReady(@NonNull GoogleSignInAccount signInAccount) { synchronized (initializationLock) { if (isInitializing.get()) { AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String token = null; try { final String scopes = "oauth2:" + DriveScopes.DRIVE_APPDATA + " " + DriveScopes.DRIVE_FILE; token = GoogleAuthUtil.getToken(context, signInAccount.getAccount(), scopes); } catch (UserRecoverableAuthException e) { activity.startActivityForResult(e.getIntent(), REQUEST_CODE_GOOGLE_SERVICE_REAUTH); } catch (IOException e) { } catch (GoogleAuthException e) { } return token; } @Override protected void onPostExecute(String result) { if (!TextUtils.isEmpty(result)) { GoogleSignInAccountFinalization(signInAccount); } } }; task.execute(); } } }

Target:
private void onGoogleSignInAccountReady(@NonNull GoogleSignInAccount signInAccount) { synchronized (initializationLock) { if (isInitializing.get()) { Single.fromCallable(() -> { final String scopes = "oauth2:" + DriveScopes.DRIVE_APPDATA + " " + DriveScopes.DRIVE_FILE; return GoogleAuthUtil.getToken(context, signInAccount.getAccount(), scopes); }).doOnError(throwable -> { Logger.error(GoogleDriveBackupManager.this, "Failed to authenticate user with status: {}", throwable.getMessage()); }).subscribeOn(Schedulers.io()) .subscribe(onSuccess -> GoogleSignInAccountFinalization(signInAccount), onError -> { if (onError instanceof UserRecoverableAuthException) { activity.startActivityForResult(((UserRecoverableAuthException) onError).getIntent(), REQUEST_CODE_GOOGLE_SERVICE_REAUTH); } else if (onError instanceof UserRecoverableAuthIOException) { activity.startActivityForResult(((UserRecoverableAuthIOException) onError).getIntent(), REQUEST_CODE_GOOGLE_SERVICE_REAUTH); } }); } } }
Source:
public double getDouble() { return doubles[index] == null ? NullHandling.ZERO_DOUBLE : doubles[index]; }

Target:
public double getDouble() { if (doubles[index] != null) { return doubles[index]; } else if (NullHandling.replaceWithDefault()) { return NullHandling.ZERO_DOUBLE; } else { throw new IllegalStateException("Should never be invoked when current value is null && SQL-compatible null handling is enabled!"); } }
Source:
public Statement apply(Statement base, Description description) { if (description.isSuite()) { throw new MockitoException("JUnitTestRule can not be used as a @ClassRule."); } return createStatement(base, description.getDisplayName(), this.testInstance); }

Target:
public Statement apply(Statement base, Description description) { return sessionStore.createStatement(base, description.getDisplayName(), this.testInstance); }
Source:
private void postPrepareSanStorageForEdit(final SanStorageModelBase model, boolean isStorageActive, StorageDomain storage) { model.setStorageDomain(storage); VDS host = getContainer().getHost().getSelectedItem(); if (Objects.equals(previousGetLunsByVGIdHost, host) && isStorageActive) { return; } previousGetLunsByVGIdHost = host; Guid hostId = host != null && isStorageActive ? host.getId() : null; boolean isInMaintenance = false; Set<String> metadata = null; if (!model.getContainer().isNewStorage()) { isInMaintenance = model.getContainer().getStorage().getStatus() == StorageDomainStatus.Maintenance; metadata = model.getMetadataDevices(); } boolean finalIsInMaintenance = isInMaintenance; Set<String> finalMetadata = metadata; AsyncDataProvider.getInstance().getLunsByVgId(new AsyncQuery<>(lunList -> model.applyData(finalIsInMaintenance, finalMetadata, lunList, true, Linq.findSelectedItems((Collection<EntityModel<?>>) getSelectedItem()))), storage.getStorage(), hostId); }

Target:
private void postPrepareSanStorageForEdit(final SanStorageModelBase model, boolean isStorageActive, StorageDomain storage) { model.setStorageDomain(storage); VDS host = getContainer().getHost().getSelectedItem(); if (Objects.equals(previousGetLunsByVGIdHost, host) && isStorageActive) { return; } previousGetLunsByVGIdHost = host; Guid hostId = host != null && isStorageActive ? host.getId() : null; boolean isInMaintenance = false; Set<String> metadata = null; if (!model.getContainer().isNewStorage()) { isInMaintenance = model.getContainer().getStorage().getStatus() == StorageDomainStatus.Maintenance; metadata = model.getMetadataDevices(); } boolean finalIsInMaintenance = isInMaintenance; Set<String> finalMetadata = metadata; AsyncDataProvider.getInstance().getLunsByVgId(new AsyncQuery<>(lunList -> model.applyData(lunList, true, Linq.findSelectedItems((Collection<EntityModel<?>>) getSelectedItem()), finalIsInMaintenance, finalMetadata)), storage.getStorage(), hostId); }
Source:
public void setPromiscuousBinding(IBinding binding) { promiscuousBinding = binding; }

Target:
public final void setPromiscuousBinding(IBinding binding) { promiscuousBinding = binding; }
Source:
private static void notifyCallbacks() { synchronized (instance) { if (workspace == null) return; } while (!callbacks.isEmpty()) { Function<Workspace,Void> callback = callbacks.poll(); callback.apply(workspace); } }

Target:
private static void notifyCallbacks() { if (workspace == null) return; for (Function<Workspace,Void> callback = callbacks.poll(); callback != null; callback = callbacks.poll()) { try { callback.apply(workspace); } catch (Throwable t) { } } }
Source:
public void testHandlerMBeanRegistration() throws Exception { System.out.println(server); Set<ObjectName> names = this.server .queryNames(new ObjectName("org.springframework.integration:*,name=testGateway"), null); assertEquals(1, names.size()); names = this.server.queryNames(new ObjectName("org.springframework.integration:*,name=foo"), null); assertEquals(1, names.size()); names = this.server.queryNames(new ObjectName("org.springframework.integration:*,name=foo#2"), null); assertEquals(1, names.size()); }

Target:
public void testHandlerMBeanRegistration() throws Exception { Set<ObjectName> names = this.server .queryNames(new ObjectName("org.springframework.integration:*,name=testGateway"), null); assertEquals(1, names.size()); names = this.server.queryNames(new ObjectName("org.springframework.integration:*,type=MessageSource,name=foo"), null); assertEquals(1, names.size()); names = this.server.queryNames(new ObjectName("org.springframework.integration:*,name=foo#2"), null); assertEquals(1, names.size()); }
Source:
private void sendHeartbeat(Member target) { if (target == null) { return; } try { MembersViewMetadata membersViewMetadata = clusterService.getMembershipManager().createLocalMembersViewMetadata(); Collection<MemberInfo> suspectedMembers; if (clusterService.getMembershipManager().isPartialDisconnectionDetectionEnabled() && !clusterService.isMaster() && target.getAddress().equals(clusterService.getMasterAddress())) { suspectedMembers = clusterService.getMembershipManager() .getSuspectedMembers() .stream() .map(MemberInfo::new) .collect(toSet()); } else { suspectedMembers = Collections.emptySet(); } long clusterTime = clusterClock.getClusterTime(); Operation op = new HeartbeatOp(membersViewMetadata, target.getUuid(), clusterTime, suspectedMembers); op.setCallerUuid(clusterService.getThisUuid()); node.nodeEngine.getOperationService().send(op, target.getAddress()); } catch (Exception e) { if (logger.isFineEnabled()) { logger.fine(format("Error while sending heartbeat -> %s[%s]", e.getClass().getName(), e.getMessage())); } } }

Target:
private void sendHeartbeat(Member target) { if (target == null) { return; } try { MembersViewMetadata membersViewMetadata = clusterService.getMembershipManager().createLocalMembersViewMetadata(); Collection<MemberInfo> suspectedMembers = Collections.emptySet(); if (clusterService.getMembershipManager().isPartialDisconnectionDetectionEnabled() && !clusterService.isMaster() && target.getAddress().equals(clusterService.getMasterAddress())) { suspectedMembers = clusterService.getMembershipManager() .getSuspectedMembers() .stream() .map(MemberInfo::new) .collect(toSet()); } long clusterTime = clusterClock.getClusterTime(); Operation op = new HeartbeatOp(membersViewMetadata, target.getUuid(), clusterTime, suspectedMembers); op.setCallerUuid(clusterService.getThisUuid()); node.nodeEngine.getOperationService().send(op, target.getAddress()); } catch (Exception e) { if (logger.isFineEnabled()) { logger.fine(format("Error while sending heartbeat -> %s[%s]", e.getClass().getName(), e.getMessage())); } } }
Source:
private ClassFile newClassFile(String name, int accessFlags, String superclass, String... interfaces) { try { return SecurityActions.getConstructor(ClassFile.class, String.class, int.class, String.class, ClassLoader.class, Arrays2.EMPTY_STRING_ARRAY.getClass()) .newInstance(name, accessFlags, superclass, classLoader, interfaces); } catch (Exception e) { throw BeanLogger.LOG.unableToCreateClassFile(name, e.getCause()); } }

Target:
private ClassFile newClassFile(String name, int accessFlags, String superclass, String... interfaces) { try { return new ClassFile(name, accessFlags, superclass, classLoader, interfaces); } catch (Exception e) { throw BeanLogger.LOG.unableToCreateClassFile(name, e.getCause()); } }
Source:
public void testInvalidAddress() throws InterruptedException, IOException { final String invalidHost = "invalid.host"; final int port = 10501; Context context = new Context(); context.put("port", String.valueOf(port)); context.put("bind", invalidHost); Configurables.configure(source, context); try { source.start(); Assert.fail("Expected an exception during startup caused by binding on a invalid host"); } catch (FlumeException e) { logger.info("Received an expected exception.", e); Assert.assertTrue("Expected a bind related root cause", e.getMessage().contains("Failed to bind to")); } Assert.assertEquals("Server is stopped", LifecycleState.STOP, source.getLifecycleState()); }

Target:
public void testInvalidAddress() throws InterruptedException, IOException { final String invalidHost = "invalid.host"; final int port = 10501; Context context = new Context(); context.put("port", String.valueOf(port)); context.put("bind", invalidHost); Configurables.configure(source, context); try { source.start(); Assert.fail("Expected an exception during startup caused by binding on a invalid host"); } catch (FlumeException e) { logger.info("Received an expected exception.", e); Assert.assertTrue("Expected a server socket setup related root cause", e.getMessage().contains("server socket")); } Assert.assertEquals("Server is stopped", LifecycleState.STOP, source.getLifecycleState()); }
Source:
public VmSnapshotPreviewPopupWidget(CommonApplicationConstants constants) { memoryEditor = new EntityModelCheckBoxEditor(Align.RIGHT); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); localize(constants); ViewIdHandler.idHandler.generateAndSetIds(this); driver.initialize(this); }

Target:
public VmSnapshotPreviewPopupWidget(CommonApplicationConstants constants) { initEditors(); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); localize(constants); ViewIdHandler.idHandler.generateAndSetIds(this); driver.initialize(this); }
Source:
public static ProjectManager getInstance() { return INSTANCE; }

Target:
public static ProjectManager getInstance() { return instance; }
Source:
public void should_fail_if_actual_is_not_a_package_private_class() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> classes.assertIsPackagePrivate(someInfo(), Object.class)) .withMessage(shouldBePackagePrivate(Object.class).create()); }

Target:
public void should_fail_if_actual_is_not_a_package_private_class() { Class clazz = Object.class; AssertionError assertionError = expectAssertionError(() -> assertThat(clazz).isPackagePrivate()); then(assertionError).hasMessage(shouldBePackagePrivate(Object.class).create()); }
Source:
public void initialize() { if (state == null) { solenoids.shift(); } else { solenoids.shift(state); } }

Target:
public void initialize() { if (state == null) { solenoids.set(); } else { solenoids.set(state); } }
Source:
public boolean delete(final String queryId) { final PhysicalPlan<PartitionedQuery, StreamType.Direction> chainedPlan = physicalPlanMap.remove(queryId); if (chainedPlan != null) { final DAG<PartitionedQuery, StreamType.Direction> chainedOperators = chainedPlan.getOperators(); final Iterator<PartitionedQuery> partitionedQueryIterator = GraphUtils.topologicalSort(chainedOperators); while (partitionedQueryIterator.hasNext()) { final PartitionedQuery partitionedQuery = partitionedQueryIterator.next(); partitionedQueryManager.delete(partitionedQuery); } closeSourceAndSink(chainedPlan); return true; } return false; }

Target:
public boolean delete(final String queryId) { try { planStore.delete(queryId); } catch (final IOException e) { e.printStackTrace(); } return deleteChainedPlan(queryId); }
Source:
public void onStatusUpdate(QpidStatus oldStatus, QpidStatus newStatus) { if (newStatus.equals(oldStatus)) { return; } log.debug("EventSource was notified of a QpidStatus change: {}", newStatus); for (MessageReceiver receiver : this.messageReceivers) { if (!receiver.requiresQpid()) { continue; } if (QpidStatus.FLOW_STOPPED.equals(newStatus) || QpidStatus.DOWN.equals(newStatus)) { receiver.pause(); } else if (QpidStatus.CONNECTED.equals(newStatus)) { receiver.resume(); } } }

Target:
public void onStatusUpdate(QpidStatus oldStatus, QpidStatus newStatus) { if (newStatus.equals(oldStatus)) { return; } log.debug("EventSource was notified of a QpidStatus change: {}", newStatus); for (MessageReceiver receiver : this.messageReceivers) { if (!receiver.requiresQpid()) { continue; } switch (newStatus) { case FLOW_STOPPED: case DOWN: receiver.pause(); break; case CONNECTED: receiver.resume(); break; default: } } }
Source:
public static void composeObject_test1() throws Exception { String methodName = "composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget)"; if (!mintEnv) { System.out.println("Test :" + methodName); } long startTime = System.currentTimeMillis(); String mintArgs = "size: 6 MB & 6 MB "; try { String destinationObjectName = getRandomName(); String filename1 = createFile6Mb(); String filename2 = createFile6Mb(); PutObjectOptions options = new PutObjectOptions(6 * MB, -1); client.putObject(bucketName, filename1, filename1, options); client.putObject(bucketName, filename2, filename2, options); ComposeSource s1 = new ComposeSource(bucketName, filename1, null, null, null, null, null); ComposeSource s2 = new ComposeSource(bucketName, filename2, null, null, null, null, null); List<ComposeSource> listSourceObjects = new ArrayList<ComposeSource>(); listSourceObjects.add(s1); listSourceObjects.add(s2); try { client.composeObject(bucketName, destinationObjectName, listSourceObjects, null, null); client.removeObject( RemoveObjectArgs.builder().bucket(bucketName).object(destinationObjectName).build()); } finally { Files.delete(Paths.get(filename1)); Files.delete(Paths.get(filename2)); client.removeObject( RemoveObjectArgs.builder().bucket(bucketName).object(filename1).build()); client.removeObject( RemoveObjectArgs.builder().bucket(bucketName).object(filename2).build()); } mintSuccessLog(methodName, mintArgs, startTime); } catch (Exception e) { handleException(methodName, mintArgs, startTime, e); } }

Target:
public static void composeObject_test1() throws Exception { String methodName = "composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget)"; if (!mintEnv) { System.out.println("Test :" + methodName); } long startTime = System.currentTimeMillis(); String mintArgs = "size: 6 MB & 6 MB "; try { String destinationObjectName = getRandomName(); String filename1 = createFile6Mb(); String filename2 = createFile6Mb(); PutObjectOptions options = new PutObjectOptions(6 * MB, -1); client.putObject(bucketName, filename1, filename1, options); client.putObject(bucketName, filename2, filename2, options); ComposeSource s1 = new ComposeSource(bucketName, filename1, null, null, null, null, null); ComposeSource s2 = new ComposeSource(bucketName, filename2, null, null, null, null, null); List<ComposeSource> listSourceObjects = new ArrayList<ComposeSource>(); listSourceObjects.add(s1); listSourceObjects.add(s2); try { client.composeObject(bucketName, destinationObjectName, listSourceObjects, null, null); client.removeObject( RemoveObjectArgs.builder().bucket(bucketName).object(destinationObjectName).build()); } finally { deleteFilesAndObjects(bucketName, new String[] {filename1, filename2}); } mintSuccessLog(methodName, mintArgs, startTime); } catch (Exception e) { handleException(methodName, mintArgs, startTime, e); } }
Source:
public void run() { IBuild build = editor.getEditorInput().getBuild(); IBuildPlan plan = build.getPlan(); String label = build.getLabel(); EditorHandle handle = new EditorHandle(); handle.setPart(editor); GetBuildsRequest request = new GetBuildsRequest(plan, Collections.singletonList(label), Scope.FULL); GetBuildsOperation operation = BuildsUiInternal.getFactory().getGetBuildsOperation(request); operation.addOperationChangeListener(new RefreshBuildEditorOperationListener(build, handle)); operation.execute(); }

Target:
public void run() { IBuild build = getBuild(); IBuildPlan plan = build.getPlan(); String label = build.getLabel(); EditorHandle handle = new EditorHandle(); handle.setPart(editor); GetBuildsRequest request = new GetBuildsRequest(plan, Collections.singletonList(label), Scope.FULL); GetBuildsOperation operation = BuildsUiInternal.getFactory().getGetBuildsOperation(request); operation.addOperationChangeListener(new RefreshBuildEditorOperationListener(build, handle)); operation.execute(); }
Source:
void resizeHandle (int width, int height) { if (OS.GTK3) { if (fixedHandle != 0) { OS.swt_fixed_resize (OS.gtk_widget_get_parent(fixedHandle), fixedHandle, width, height); } long child = scrolledHandle != 0 ? scrolledHandle : handle; int sizes = resizeCalculationsGTK3 (child, width, height); width = sizes[0]; height = sizes[1]; OS.swt_fixed_resize (OS.gtk_widget_get_parent(child), child, width, height); } else { if (fixedHandle != 0) OS.gtk_widget_set_size_request (fixedHandle, width, height); OS.gtk_widget_set_size_request (scrolledHandle != 0 ? scrolledHandle : handle, width, height); } }

Target:
void resizeHandle (int width, int height) { if (OS.GTK3) { if (fixedHandle != 0) { OS.swt_fixed_resize (OS.gtk_widget_get_parent(fixedHandle), fixedHandle, width, height); } long child = scrolledHandle != 0 ? scrolledHandle : handle; Point sizes = resizeCalculationsGTK3 (child, width, height); width = sizes.x; height = sizes.y; OS.swt_fixed_resize (OS.gtk_widget_get_parent(child), child, width, height); } else { if (fixedHandle != 0) OS.gtk_widget_set_size_request (fixedHandle, width, height); OS.gtk_widget_set_size_request (scrolledHandle != 0 ? scrolledHandle : handle, width, height); } }
Source:
public long getBucketKeyFor(T event) { long expiryKey = getExpiryKey(event); if (expiryKey < expiryPoint) { return -1; } long key = expiryKey / bucketSpan; synchronized (lock) { if (expiryKey > endOfBuckets) { long move = expiryKey - endOfBuckets; endOfBuckets += move; expiryPoint = endOfBuckets - expiryPeriod + 1; if (recordStats) { bucketCounters.getCounter(CounterKeys.HIGH).setValue(endOfBuckets); bucketCounters.getCounter(CounterKeys.LOW).setValue(expiryPoint); } } } return key; }

Target:
public long getBucketKeyFor(T event) { long expiryKey = getExpiryKey(event); if (expiryKey < expiryPoint) { return -1; } synchronized (lock) { if (expiryKey > endOfBuckets) { endOfBuckets = expiryKey; expiryPoint = endOfBuckets - expiryPeriod + 1; if (recordStats) { bucketCounters.getCounter(CounterKeys.HIGH).setValue(endOfBuckets); bucketCounters.getCounter(CounterKeys.LOW).setValue(expiryPoint); } } } long key = expiryKey / bucketSpan; return key; }
Source:
public void testDownsample_afterAggregation() { iterators = new SeekableView[] { new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG) }; start_time_ms = BASE_TIME + 01000L; end_time_ms = BASE_TIME + 100000; AggregationIterator sgai = AggregationIterator.createForTesting(iterators, start_time_ms, end_time_ms, aggregator, interpolation, rate); Downsampler downsampler = new Downsampler(sgai, 15000, SUM); DataPoint[] expected_data_points = new DataPoint[] { MutableDataPoint.ofDoubleValue(BASE_TIME + 00000L, 7), MutableDataPoint.ofDoubleValue(BASE_TIME + 15000L, 7), MutableDataPoint.ofDoubleValue(BASE_TIME + 30000L, 14), MutableDataPoint.ofDoubleValue(BASE_TIME + 45000L, 7) }; for (DataPoint expected: expected_data_points) { assertTrue(downsampler.hasNext()); DataPoint dp = downsampler.next(); assertEquals(expected.timestamp(), dp.timestamp()); assertEquals(String.format("timestamp = %d", dp.timestamp()), expected.doubleValue(), dp.doubleValue(), 0); } assertFalse(downsampler.hasNext()); }

Target:
public void testDownsample_afterAggregation() { iterators = new SeekableView[] { new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG) }; start_time_ms = BASE_TIME + 01000L; end_time_ms = BASE_TIME + 100000; AggregationIterator sgai = AggregationIterator.createForTesting(iterators, start_time_ms, end_time_ms, aggregator, interpolation, rate); Downsampler downsampler = new Downsampler(sgai, 15000, SUM); DataPoint[] expected_data_points = new DataPoint[] { MutableDataPoint.ofDoubleValue(BASE_TIME + 00000L, 7), MutableDataPoint.ofDoubleValue(BASE_TIME + 15000L, 7), MutableDataPoint.ofDoubleValue(BASE_TIME + 30000L, 14), MutableDataPoint.ofDoubleValue(BASE_TIME + 45000L, 7) }; for (DataPoint expected: expected_data_points) { assertTrue(downsampler.hasNext()); DataPoint dp = downsampler.next(); assertEquals(expected.timestamp(), dp.timestamp()); assertEquals("timestamp = %d" + dp.timestamp(), expected.doubleValue(), dp.doubleValue(), 0); } assertFalse(downsampler.hasNext()); }
Source:
public void test_dotnet_core_checks_version_if_set_before() { ScannerForMSBuild build = ScannerForMSBuild.create(); build.setScannerVersion("4.2"); assertThat(build.isUsingDotNetCore()).isFalse(); build.setUseDotNetCore(true); assertThat(build.isUsingDotNetCore()).isTrue(); build = ScannerForMSBuild.create(); build.setScannerVersion("2.2"); try { build.setUseDotNetCore(true); fail("Should have failed"); } catch (IllegalStateException e) { assertThat(e.getMessage()).contains("Version of ScannerForMSBuild should be higher than or equals to 4.1.0.1148 to be able to use .Net Core."); } }

Target:
public void test_dotnet_core_checks_version_if_set_before() { ScannerForMSBuild build = ScannerForMSBuild.create(); build.setScannerVersion("4.2"); assertThat(build.isUsingDotNetCore()).isFalse(); build.setUseDotNetCore(true); assertThat(build.isUsingDotNetCore()).isTrue(); build = ScannerForMSBuild.create(); assertThat(build.isUsingDotNetCore()).isFalse(); build.setDotNetCoreExecutable(new File(".")); assertThat(build.isUsingDotNetCore()).isTrue(); build = ScannerForMSBuild.create(); build.setScannerVersion("2.2"); build.setUseDotNetCore(true); build.setProjectDir(new File(".")); thrown.expect(IllegalStateException.class); thrown.expectMessage("Version of ScannerForMSBuild should be higher than or equals to 4.1.0.1148 to be able to use .Net Core."); build.check(); }
Source:
Node createNode() { CommentNode node = new CommentNode(); node.setHtml(html); return node; }

Target:
Node createNode() { CommentNode node = new CommentNode(); node.setHtml(isHtml); return node; }
Source:
protected void doDownloadContent(HttpServletResponse httpResponse, SrampAtomApiClient client, String uuid) throws Exception { InputStream ontologyContent = null; String contentType = "application/rdf+xml"; RDF ontologyRDF=client.getOntology(uuid); Ontology ontology=null; if (ontologyRDF != null) { ontology=ontologyRDF.getOntology(); } else{ throw new Exception(Messages.i18n.format("OntologyDownloadServlet.ontology.not.found",uuid)); } StringWriter writer=new StringWriter(); JAXBContext jaxbContext = JAXBContext.newInstance(RDF.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(ontologyRDF, writer); String content = writer.getBuffer().toString(); ontologyContent = new ByteArrayInputStream(content.getBytes("UTF-8")); httpResponse.setHeader("Content-Size", content.getBytes().length + ""); String base = ontologyRDF.getOtherAttributes().get( new QName("<LINK_0>", "base")); String name = "sramp-ontology.owl"; if (base.endsWith(".owl")) { name = base.substring(base.lastIndexOf("/") + 1); } String disposition = "attachment; filename=\"" + name + "\""; super.doDownloadContent(ontologyContent, contentType, disposition, httpResponse); }

Target:
protected void doDownloadContent(HttpServletResponse httpResponse, SrampAtomApiClient client, String uuid) throws Exception { InputStream ontologyContent = null; String contentType = "application/rdf+xml"; RDF ontologyRDF=client.getOntology(uuid); StringWriter writer=new StringWriter(); JAXBContext jaxbContext = JAXBContext.newInstance(RDF.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(ontologyRDF, writer); String content = writer.getBuffer().toString(); ontologyContent = new ByteArrayInputStream(content.getBytes("UTF-8")); httpResponse.setHeader("Content-Size", content.getBytes().length + ""); String base = ontologyRDF.getOtherAttributes().get( new QName("<LINK_0>", "base")); String name = "sramp-ontology.owl"; if (base.endsWith(".owl")) { name = base.substring(base.lastIndexOf("/") + 1); } String disposition = "attachment; filename=\"" + name + "\""; super.doDownloadContent(ontologyContent, contentType, disposition, httpResponse); }
Source:
public void testFailSlowHeaderTooLong() { EmbeddedChannel slowFailCh = new EmbeddedChannel(new HAProxyMessageDecoder(false)); String headerPart1 = "PROXY TCP4 192.168.0.1 192.168.0.11 56324 " + "000000000000000000000000000000000000000000000000000000000000000000000443"; slowFailCh.writeInbound(copiedBuffer(headerPart1, CharsetUtil.US_ASCII)); String headerPart2 = "more header data"; slowFailCh.writeInbound(copiedBuffer(headerPart2, CharsetUtil.US_ASCII)); String headerPart3 = "end of header\r\n"; int discarded = headerPart1.length() + headerPart2.length() + headerPart3.length() - 2; exceptionRule.expect(HAProxyProtocolException.class); exceptionRule.expectMessage("over " + discarded); slowFailCh.writeInbound(copiedBuffer(headerPart3, CharsetUtil.US_ASCII)); }

Target:
public void testFailSlowHeaderTooLong() { EmbeddedChannel slowFailCh = new EmbeddedChannel(new HAProxyMessageDecoder(false)); try { String headerPart1 = "PROXY TCP4 192.168.0.1 192.168.0.11 56324 " + "000000000000000000000000000000000000000000000000000000000000000000000443"; assertFalse(slowFailCh.writeInbound(copiedBuffer(headerPart1, CharsetUtil.US_ASCII))); String headerPart2 = "more header data"; assertFalse(slowFailCh.writeInbound(copiedBuffer(headerPart2, CharsetUtil.US_ASCII))); String headerPart3 = "end of header\r\n"; int discarded = headerPart1.length() + headerPart2.length() + headerPart3.length() - 2; exceptionRule.expect(HAProxyProtocolException.class); exceptionRule.expectMessage("over " + discarded); assertFalse(slowFailCh.writeInbound(copiedBuffer(headerPart3, CharsetUtil.US_ASCII))); } finally { assertFalse(slowFailCh.finishAndReleaseAll()); } }