auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void should_return_http400_error_code_when_no_locale_param() throws Exception { Response response = request("/system/i18ntranslationv2?f=test").get(); assertThat(response).hasStatus(Status.CLIENT_ERROR_BAD_REQUEST); }

Target:
public void should_return_http400_error_code_when_no_locale_param() throws Exception { Response response = request("/system/i18ntranslation?f=test").get(); assertThat(response).hasStatus(Status.CLIENT_ERROR_BAD_REQUEST); }
Source:
protected final Event doAuthentication(final RequestContext context, final Credentials credentials, final MessageContext messageContext, final String id) throws Exception { final String primaryAuthnEventId = this.wrapperAuthenticationAction.submit(context, credentials, messageContext); final Event primaryAuthnEvent = new Event(this, primaryAuthnEventId); if (!"success".equals(primaryAuthnEventId)) { return primaryAuthnEvent; } final MultiFactorAuthenticationRequestContext mfaRequest = this.multiFactorAuthenticationRequestResolver.resolve(this.authenticationSupport.getAuthenticationFrom(WebUtils.getTicketGrantingTicketId(context)), WebApplicationService.class.cast(WebUtils.getService(context))); if (mfaRequest != null) { putIntoRequestAttribute(mfaRequest, context); return doMultiFactorAuthentication(context, credentials, messageContext, id); } return primaryAuthnEvent; }

Target:
protected final Event doAuthentication(final RequestContext context, final Credentials credentials, final MessageContext messageContext, final String id) throws Exception { final String primaryAuthnEventId = this.wrapperAuthenticationAction.submit(context, credentials, messageContext); final Event primaryAuthnEvent = new Event(this, primaryAuthnEventId); if (!success().getId().equals(primaryAuthnEvent.getId())) { return primaryAuthnEvent; } final MultiFactorAuthenticationRequestContext mfaRequest = this.multiFactorAuthenticationRequestResolver.resolve( this.authenticationSupport.getAuthenticationFrom(WebUtils.getTicketGrantingTicketId(context)), WebApplicationService.class.cast(WebUtils.getService(context))); if (mfaRequest != null) { this.authenticationMethodVerifier.verifyAuthenticationMethod(mfaRequest.getAuthenticationMethod(), mfaRequest.getTargetService(), HttpServletRequest.class.cast(context.getExternalContext().getNativeRequest())); logger.info("There is an existing mfa request for service with a requested authentication method of [{}]", mfaRequest.getTargetService().getId(), mfaRequest.getAuthenticationMethodSource()); final MultiFactorAuthenticationSupportingWebApplicationService svc = this.mfaWebApplicationServiceFactory.create(mfaRequest.getTargetService().getId(), mfaRequest.getTargetService().getId(), mfaRequest.getTargetService().getArtifactId(), mfaRequest.getAuthenticationMethod(), mfaRequest.getAuthenticationMethodSource()); MultiFactorRequestContextUtils.setMultifactorWebApplicationService(context, svc); return doMultiFactorAuthentication(context, credentials, messageContext, id); } return primaryAuthnEvent; }
Source:
public void testValidate() throws UnsupportedEncodingException, IOException { VALIDATOR.validate("VALID_NAME"); VALIDATOR.validate("VALID-NAME"); VALIDATOR.validate("VALID255NAME"); VALIDATOR.validate("255VALID-NAME"); VALIDATOR.validate("VALID.NAME"); VALIDATOR.validate(new String(buildData(255).read(), UTF_8)); }

Target:
public void testValidate() { VALIDATOR.validate("VALID_NAME"); VALIDATOR.validate("VALID-NAME"); VALIDATOR.validate("VALID255NAME"); VALIDATOR.validate("255VALID-NAME"); VALIDATOR.validate("VALID.NAME"); }
Source:
public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mHandler = ViewModelProviders.of(this).get(CheckEmailHandler.class); mHandler.init(getFlowParams()); FragmentActivity activity = getActivity(); if (!(activity instanceof CheckEmailListener)) { throw new IllegalStateException("Activity must implement CheckEmailListener"); } mListener = (CheckEmailListener) activity; mHandler.getOperation().observe(this, new ResourceObserver<User>( this, R.string.fui_progress_dialog_checking_accounts) { @Override protected void onSuccess(@NonNull User user) { String email = user.getEmail(); String provider = user.getProviderId(); mEmailEditText.setText(email); if (provider == null) { mListener.onNewUser(new User.Builder(EmailAuthProvider.PROVIDER_ID, email) .setName(user.getName()) .setPhotoUri(user.getPhotoUri()) .build()); } else if (provider.equals(EmailAuthProvider.PROVIDER_ID) || provider.equals (EMAIL_LINK_PROVIDER)) { mListener.onExistingEmailUser(user); } else { mListener.onExistingIdpUser(user); } } @Override protected void onFailure(@NonNull Exception e) { } }); if (savedInstanceState != null) { return; } String email = getArguments().getString(ExtraConstants.EMAIL); if (!TextUtils.isEmpty(email)) { mEmailEditText.setText(email); validateAndProceed(); } else if (getFlowParams().enableHints) { mHandler.fetchCredential(); } }

Target:
public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mHandler = ViewModelProviders.of(this).get(CheckEmailHandler.class); mHandler.init(getFlowParams()); FragmentActivity activity = getActivity(); if (!(activity instanceof CheckEmailListener)) { throw new IllegalStateException("Activity must implement CheckEmailListener"); } mListener = (CheckEmailListener) activity; mHandler.getOperation().observe(this, new ResourceObserver<User>( this, R.string.fui_progress_dialog_checking_accounts) { @Override protected void onSuccess(@NonNull User user) { String email = user.getEmail(); String provider = user.getProviderId(); mEmailEditText.setText(email); if (provider == null) { mListener.onNewUser(new User.Builder(EmailAuthProvider.PROVIDER_ID, email) .setName(user.getName()) .setPhotoUri(user.getPhotoUri()) .build()); } else if (provider.equals(EmailAuthProvider.PROVIDER_ID) || provider.equals(EMAIL_LINK_PROVIDER)) { mListener.onExistingEmailUser(user); } else { mListener.onExistingIdpUser(user); } } @Override protected void onFailure(@NonNull Exception e) { if (e instanceof FirebaseUiException && ((FirebaseUiException) e).getErrorCode() == ErrorCodes.DEVELOPER_ERROR) { mListener.onDeveloperFailure(e); } } }); if (savedInstanceState != null) { return; } String email = getArguments().getString(ExtraConstants.EMAIL); if (!TextUtils.isEmpty(email)) { mEmailEditText.setText(email); validateAndProceed(); } else if (getFlowParams().enableHints) { mHandler.fetchCredential(); } }
Source:
public void initSystem() { try { logger.info("Sending " + LIGHTING_DIAGNOSTIC_FRAME + " frame to (re)initialize LIGHTING"); myPlant.sendCommandSync(LIGHTING_DIAGNOSTIC_FRAME); logger.info("Sending " + AUTOMATIONS_DIAGNOSTIC_FRAME + " frame to (re)initialize AUTOMATIONS"); myPlant.sendCommandSync(AUTOMATIONS_DIAGNOSTIC_FRAME); logger.info("Sending " + ALARM_DIAGNOSTIC_FRAME + " frame to (re)initialize ALARM"); myPlant.sendCommandSync(ALARM_DIAGNOSTIC_FRAME); logger.info("Sending " + POWER_MANAGEMENT_DIAGNOSTIC_FRAME + " frame to (re)initialize POWER MANAGEMENT"); myPlant.sendCommandSync(POWER_MANAGEMENT_DIAGNOSTIC_FRAME); logger.info("Sending *4#* frames to (re)initialize HEATING"); myPlant.sendCommandSync("*#4*#1*20##"); myPlant.sendCommandSync("*#4*#0##"); for (int i = 1; i <= m_heating_zones; i++) { myPlant.sendCommandSync("*#4*#" + i + "##"); myPlant.sendCommandSync("*#4*" + i + "##"); } } catch (Exception e) { logger.error("initSystem failed : " + e.getMessage()); } }

Target:
public void initSystem() { try { logger.info("Sending frames to (re)initialize subsystems"); logger.debug("Sending frame to (re)initialize LIGHTING", LIGHTING_DIAGNOSTIC_FRAME); myPlant.sendCommandSync(LIGHTING_DIAGNOSTIC_FRAME); logger.debug("Sending frame to (re)initialize AUTOMATIONS", AUTOMATIONS_DIAGNOSTIC_FRAME); myPlant.sendCommandSync(AUTOMATIONS_DIAGNOSTIC_FRAME); logger.debug("Sending frame to (re)initialize ALARM", ALARM_DIAGNOSTIC_FRAME); myPlant.sendCommandSync(ALARM_DIAGNOSTIC_FRAME); logger.debug("Sending frame to (re)initialize POWER MANAGEMENT", POWER_MANAGEMENT_DIAGNOSTIC_FRAME); myPlant.sendCommandSync(POWER_MANAGEMENT_DIAGNOSTIC_FRAME); logger.debug("Sending Diagnostic Frame Actors to (re)initialize HEATING"); myPlant.sendCommandSync("*#4*#1*20##"); logger.debug("Sending Diagnostic Frame Main Unit to (re)initialize HEATING"); myPlant.sendCommandSync("*#4*#0##"); Calendar rightNow = Calendar.getInstance(); if (m_heating_zones > 0 && rightNow.get(Calendar.MINUTE) == 59) { logger.debug("Sending Diagnostic Frame Heat Zones 1 .. to (re)initialize HEATING", m_heating_zones); for (int i = 1; i <= m_heating_zones; i++) { logger.debug("Sending Diagnostic Frame Heat Zone to (re)initialize HEATING", i); myPlant.sendCommandSync("*#4*#" + i + "##"); myPlant.sendCommandSync("*#4*" + i + "##"); } logger.debug("Sending Diagnostic Frames to (re)initialize HEATING finished"); } } catch (Exception e) { logger.warn("initSystem failed : {}", e.getMessage()); } }
Source:
private void handleSynchronization(Event event) { final Shell shell = event.display.getActiveShell(); SynchronizationBehavior syncBehavior = filterManager.getCurrentSynchronizationBehavior(); if (syncBehavior != SynchronizationBehavior.NEVER) { shell.getDisplay().asyncExec(new SynchronizationBehaviorRunnable(shell)); } }

Target:
private void handleSynchronization(Event event) { String sync = preferences.get(FiltersPreferencePage.SYNCHRONIZATION_BEHAVIOR, MessageDialogWithToggle.PROMPT); final Shell shell = event.display.getActiveShell(); if (MessageDialogWithToggle.PROMPT.equals(sync) && shell != null) { shell.getDisplay().asyncExec(new SynchronizationBehaviorRunnable(shell)); } else if (MessageDialogWithToggle.ALWAYS.equals(sync)) { setSelectedGroupAsDefault(isChecked()); } }
Source:
public CustomUIPane(HaskellCatalog catalog) { this.connectionCreationManager = new ConnectionCreationManager(this); this.selectedBlock = new SimpleObjectProperty<>(Optional.empty()); this.dragStart = Point2D.ZERO; this.offset = Point2D.ZERO; this.catalog = catalog; this.envInstance = catalog.asEnvironment(); try { this.ghci = Optional.of(new GhciSession()); } catch (HaskellException e) { this.ghci = Optional.empty(); } this.addEventHandler(MouseEvent.MOUSE_PRESSED, this::handlePress); this.addEventHandler(MouseEvent.MOUSE_DRAGGED, this::handleDrag); this.addEventHandler(MouseEvent.MOUSE_RELEASED, this::handleRelease); this.addEventHandler(ScrollEvent.SCROLL, this::handleScroll); this.addEventHandler(KeyEvent.KEY_PRESSED, this::handleKey); Platform.runLater(() -> inspector = new InspectorWindow(this)); Platform.runLater(() -> preferences = new PreferencesWindow(this)); }

Target:
public CustomUIPane(HaskellCatalog catalog) { this.connectionCreationManager = new ConnectionCreationManager(this); this.selectedBlock = new SimpleObjectProperty<>(Optional.empty()); this.dragStart = Point2D.ZERO; this.offset = Point2D.ZERO; this.catalog = catalog; this.envInstance = catalog.asEnvironment(); try { this.ghci = Optional.of(new GhciSession()); } catch (HaskellException e) { this.ghci = Optional.empty(); } this.addEventHandler(MouseEvent.MOUSE_PRESSED, this::handlePress); this.addEventHandler(MouseEvent.MOUSE_DRAGGED, this::handleDrag); this.addEventHandler(MouseEvent.MOUSE_RELEASED, this::handleRelease); this.addEventHandler(ScrollEvent.SCROLL, this::handleScroll); this.addEventHandler(KeyEvent.KEY_PRESSED, this::handleKey); }
Source:
public void process(final K key, final V value) { KeyValueTimestamp<Object, Object> keyValueTimestamp = new KeyValueTimestamp<>(key == null ? "null" : key, value == null ? "null" : value, context().timestamp()); if (value != null) { lastValueAndTimestampPerKey.put(key, ValueAndTimestamp.make(value, context().timestamp())); } else { lastValueAndTimestampPerKey.remove(key); } processed.add(keyValueTimestamp); if (commitRequested) { context().commit(); commitRequested = false; } }

Target:
public void process(final K key, final V value) { KeyValueTimestamp<Object, Object> keyValueTimestamp = new KeyValueTimestamp<>(key, value, context().timestamp()); if (value != null) { lastValueAndTimestampPerKey.put(key, ValueAndTimestamp.make(value, context().timestamp())); } else { lastValueAndTimestampPerKey.remove(key); } processed.add(keyValueTimestamp); if (commitRequested) { context().commit(); commitRequested = false; } }
Source:
protected LockProperties applyLockProperties(LockProperties lockProperties) { int timeout = Config.<Integer> getValue(ConfigValues.SetupNetworksWaitTimeout); return lockProperties.withScope(Scope.Execution).withWaitTimeout(timeout * 1000); }

Target:
protected LockProperties applyLockProperties(LockProperties lockProperties) { int timeout = Config.<Integer> getValue(ConfigValues.SetupNetworksWaitTimeoutSeconds); return lockProperties.withScope(Scope.Execution).withWaitTimeout(TimeUnit.SECONDS.toMillis(timeout)); }
Source:
public static RelDataType toSql(final RelDataTypeFactory typeFactory, RelDataType type) { if (type instanceof RelRecordType) { return typeFactory.createTypeWithNullability( typeFactory.createStructType( type.getFieldList() .stream() .map(field -> toSql(typeFactory, field.getType())) .collect(Collectors.toList()), type.getFieldNames()), type.isNullable()); } else if (type instanceof JavaType) { SqlTypeName sqlTypeName = type.getSqlTypeName(); final RelDataType relDataType; if (sqlTypeName == SqlTypeName.ARRAY) { RelDataType elementType = type.getComponentType() == null ? typeFactory.createSqlType(SqlTypeName.ANY) : type.getComponentType(); relDataType = typeFactory.createArrayType(elementType, -1); } else { relDataType = typeFactory.createSqlType(sqlTypeName); } return typeFactory.createTypeWithNullability(relDataType, type.isNullable()); } return type; }

Target:
public static RelDataType toSql(final RelDataTypeFactory typeFactory, RelDataType type) { if (type instanceof RelRecordType) { return typeFactory.createTypeWithNullability( typeFactory.createStructType( type.getFieldList() .stream() .map(field -> toSql(typeFactory, field.getType())) .collect(Collectors.toList()), type.getFieldNames()), type.isNullable()); } else if (type instanceof JavaType) { SqlTypeName sqlTypeName = type.getSqlTypeName(); final RelDataType relDataType; if (SqlTypeUtil.isArray(type)) { RelDataType elementType = type.getComponentType(); if (elementType == null) { elementType = typeFactory.createSqlType(SqlTypeName.ANY); } else { elementType = toSql(typeFactory, elementType); } relDataType = typeFactory.createArrayType(elementType, -1); } else { relDataType = typeFactory.createSqlType(sqlTypeName); } return typeFactory.createTypeWithNullability(relDataType, type.isNullable()); } return type; }
Source:
private void forceRebalance(HelixManager manager, ClusterEventType eventType) { NotificationContext changeContext = new NotificationContext(manager); changeContext.setType(NotificationContext.Type.CALLBACK); String uid = UUID.randomUUID().toString().substring(0, 8); ClusterEvent event = new ClusterEvent(_clusterName, eventType, uid); Optional<String> leaderSession = manager.getSessionIdIfLead(); if (!leaderSession.isPresent()) { logger.warn("Cluster manager is not leader for {}. Event is discarded.", manager.getInstanceName(), manager.getClusterName(), event); return; } event.addAttribute(AttributeName.EVENT_SESSION.name(), leaderSession.get()); event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); event.addAttribute(AttributeName.changeContext.name(), changeContext); event.addAttribute(AttributeName.eventData.name(), new ArrayList<>()); event.addAttribute(AttributeName.AsyncFIFOWorkerPool.name(), _asyncFIFOWorkerPool); enqueueEvent(_taskEventQueue, event); enqueueEvent(_eventQueue, event.clone(uid)); logger.info(String .format("Controller rebalance pipeline triggered with event type: %s for cluster %s", eventType, _clusterName)); }

Target:
private void forceRebalance(HelixManager manager, ClusterEventType eventType) { NotificationContext changeContext = new NotificationContext(manager); changeContext.setType(NotificationContext.Type.CALLBACK); String uid = UUID.randomUUID().toString().substring(0, 8); ClusterEvent event = new ClusterEvent(_clusterName, eventType, uid); event.addAttribute(AttributeName.EVENT_SESSION.name(), changeContext.getManager().getSessionIdIfLead()); event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); event.addAttribute(AttributeName.changeContext.name(), changeContext); event.addAttribute(AttributeName.eventData.name(), new ArrayList<>()); event.addAttribute(AttributeName.AsyncFIFOWorkerPool.name(), _asyncFIFOWorkerPool); enqueueEvent(_taskEventQueue, event); enqueueEvent(_eventQueue, event.clone(uid)); logger.info(String .format("Controller rebalance pipeline triggered with event type: %s for cluster %s", eventType, _clusterName)); }
Source:
public void init(StreamGraph graph, Config config) { MessageStream<PageView> pageViews = graph.getInputStream(INPUT_TOPIC, new JsonSerdeV2<>(PageView.class)); OutputStream<KV<String, Integer>> outputStream = graph.getOutputStream(OUTPUT_TOPIC, new KVSerde<>(new StringSerde(), new IntegerSerde())); pageViews .filter(m -> !FILTER_KEY.equals(m.getUserId())) .window(Windows.keyedSessionWindow(PageView::getUserId, Duration.ofSeconds(3), null, null)) .map(m -> KV.of(m.getKey().getKey(), m.getMessage().size())) .sendTo(outputStream); }

Target:
public void init(StreamGraph graph, Config config) { MessageStream<PageView> pageViews = graph.getInputStream(INPUT_TOPIC, new JsonSerdeV2<>(PageView.class)); OutputStream<KV<String, Integer>> outputStream = graph.getOutputStream(OUTPUT_TOPIC, new KVSerde<>(new StringSerde(), new IntegerSerde())); pageViews .filter(m -> !FILTER_KEY.equals(m.getUserId())) .window(Windows.keyedSessionWindow(PageView::getUserId, Duration.ofSeconds(3), new StringSerde(), new JsonSerdeV2<>(PageView.class))) .map(m -> KV.of(m.getKey().getKey(), m.getMessage().size())) .sendTo(outputStream); }
Source:
public void refreshAnchorTypes() { this.inputAnchor.setFreshRequiredType(this.getPane().getEnvInstance().buildType("Show a => a"), new TypeScope()); }

Target:
public void refreshAnchorTypes() { this.inputAnchor.setFreshRequiredType(showConstraint, new TypeScope()); }
Source:
private InputStream getJarFile (CustomProcessorInfo customProcessorInfo, File tarFile) { InputStream is = null; byte[] jarFileBytes = this.getFileAsByteArray(tarFile, customProcessorInfo.getJarFileName()); if (jarFileBytes != null && jarFileBytes.length > 0) { is = new ByteArrayInputStream(jarFileBytes); } else { LOG.warn(customProcessorInfo.getJarFileName() + " not present in tar file: " + tarFile); } return is; }

Target:
private InputStream getJarFile (CustomProcessorInfo customProcessorInfo, File tarFile) { InputStream is = null; byte[] jarFileBytes = getFileAsByteArray(tarFile, customProcessorInfo.getJarFileName()); if (jarFileBytes != null && jarFileBytes.length > 0) { is = new ByteArrayInputStream(jarFileBytes); } else { LOG.warn(customProcessorInfo.getJarFileName() + " not present in tar file: " + tarFile); } return is; }
Source:
public String getHostFingerprint() throws IOException { return ((EngineSSHClient) _client).getHostFingerprint(); }

Target:
public String getHostFingerprint() throws IOException { if (_client == null) { throw new ConnectException("SSH is not connected"); } return ((EngineSSHClient)_client).getHostFingerprint(); }
Source:
public FeedsCredentials getCredentials() throws RequestException, IOException { FeedsCredentials fc = getCredentials("/config", CREDENTIALS_PATTERN); if(fc != null) { int presumedUsernameLength = (username != null && !username.isEmpty()) ? username.length() : httpAuthUsername != null ? httpAuthUsername.length() : 0; boolean failedToCheck = false; if(presumedUsernameLength > 0) { if(fc.userID != null && presumedUsernameLength != fc.userID.length()) { if(fc.userID.length() > presumedUsernameLength) { Log.d(TAG, "getCredentials() fc.userID is longer than presumedUsername"); fc.userID = fc.userID.substring(fc.userID.length() - presumedUsernameLength); } else { Log.i(TAG, "getCredentials() fc.userID is shorter than presumedUsername"); failedToCheck = true; } } } else { Log.i(TAG, "getCredentials() no presumedUsername, can't check fc.userID"); failedToCheck = true; } if(failedToCheck) { Log.w(TAG, "getCredentials() if you see this and can't access feeds, " + "check \"feeds user ID\""); } } return fc; }

Target:
public FeedsCredentials getCredentials() throws RequestException, IOException { FeedsCredentials fc = getCredentials("/config", CREDENTIALS_PATTERN); if(fc == null || fc.userID == null) return fc; int presumedUsernameLength = (username != null && !username.isEmpty()) ? username.length() : httpAuthUsername != null ? httpAuthUsername.length() : 0; boolean failedToCheck = false; if(presumedUsernameLength <= 0) { Log.i(TAG, "getCredentials() no presumedUsername, can't check fc.userID"); failedToCheck = true; } else if(presumedUsernameLength != fc.userID.length()) { if(fc.userID.length() > presumedUsernameLength) { Log.d(TAG, "getCredentials() fc.userID is longer than presumedUsername"); fc.userID = fc.userID.substring(fc.userID.length() - presumedUsernameLength); } else { Log.i(TAG, "getCredentials() fc.userID is shorter than presumedUsername"); failedToCheck = true; } } if(failedToCheck) { Log.w(TAG, "getCredentials() if you see this and can't access feeds, " + "check \"feeds user ID\""); } return fc; }
Source:
<R> R executeOnEndPoint(ServiceEndPoint endPoint, ServiceCallback<S, R> callback) throws Exception { S service = null; try { service = _serviceCache.checkOut(endPoint); TimerContext timer = _callbackExecutionTime.time(); try { return callback.call(service); } finally { timer.stop(); } } catch (NoCachedInstancesAvailableException e) { LOG.debug("Service cache exhausted. End point ID: {}", endPoint.getId(), e); throw e; } catch (Exception e) { if (_serviceFactory.isRetriableException(e)) { markEndPointAsBad(endPoint); LOG.debug("Bad end point discovered. End point ID: {}", endPoint.getId(), e); } throw e; } finally { if (service != null) { try { _serviceCache.checkIn(endPoint, service); } catch (Exception e) { LOG.warn("Error returning end point to cache. End point ID: {}", endPoint.getId()); LOG.debug("Exception", e); } } } }

Target:
<R> R executeOnEndPoint(ServiceEndPoint endPoint, ServiceCallback<S, R> callback) throws Exception { S service = null; try { service = _serviceCache.checkOut(endPoint); TimerContext timer = _callbackExecutionTime.time(); try { return callback.call(service); } finally { timer.stop(); } } catch (NoCachedInstancesAvailableException e) { LOG.debug("Service cache exhausted. End point ID: {}", endPoint.getId(), e); throw e; } catch (Exception e) { if (_serviceFactory.isRetriableException(e)) { markEndPointAsBad(endPoint); LOG.debug("Bad end point discovered. End point ID: {}", endPoint.getId(), e); } throw e; } finally { if (service != null) { try { _serviceCache.checkIn(endPoint, service); } catch (Exception e) { LOG.warn("Error returning end point to cache. End point ID: {}, {}", endPoint.getId(), e.toString()); LOG.debug("Exception", e); } } } }
Source:
public void findV4() throws Exception { final List<IPv4.Availability> availabilities = Lists.newArrayList(PUBLIC); List<String> dto = Lists.newArrayList("PUBLIC"); context.checking(new Expectations() {{ oneOf(v4Catalog).findAll(); will(returnValue(availabilities)); }}); Reply<?> reply = service.findV4(); assertThat(reply, contains(dto)); assertThat(reply, isOk()); }

Target:
public void findV4() throws Exception { final List<IPv4.Availability> availabilities = Lists.newArrayList(IPv4.Availability.PUBLIC); List<String> dto = Lists.newArrayList("PUBLIC"); context.checking(new Expectations() {{ oneOf(v4Catalog).findAll(); will(returnValue(availabilities)); }}); Reply<?> reply = service.findV4(); assertThat(reply, contains(dto)); assertThat(reply, isOk()); }
Source:
private void storeEnvVars(Map< ? extends Object, ? extends Object > map) { final Set< ? extends Object > keys = map.keySet(); for (Object oKey : keys) { Assert.verify(oKey instanceof String, "Key: '" + String.valueOf(oKey) + "' is not a String"); final String key = (String)oKey; if (key.startsWith(USERDEF_ENV_VAR_PREFIX)) { String value = System.getenv(key); if (value == null) { value = EnvironmentUtils.getProcessOrSystemProperty(key); } final String varName = key.substring(USERDEF_ENV_VAR_PREFIX.length()); store(varName, value); } } }

Target:
private void storeEnvVars(Map< ? extends Object, ? extends Object > map) { final Set< ? extends Object > keys = map.keySet(); for (Object oKey : keys) { Assert.verify(oKey instanceof String, "Key: '" + String.valueOf(oKey) + "' is not a String"); final String key = (String)oKey; if (key.startsWith(USERDEF_ENV_VAR_PREFIX)) { String value = System.getenv(key); if (value == null) { value = System.getProperty(key); } final String varName = key.substring(USERDEF_ENV_VAR_PREFIX.length()); store(varName, value); } } }
Source:
public void validateDate(Date date) throws ValidationException { if (date == null) { String message = "The Date must not be null."; LOG.debug("validateDate, " + message); throw new ValidationException(message); } else { if (LOG.isDebugEnabled()) { LOG.debug("validateDate, found a valid date: " + date); } } }

Target:
public boolean validateDate(Date date) { boolean valid = date != null; if (valid) { LOG.debug("validateDate, found a valid date: " + date); } else { LOG.error("validateDate, found a a null date."); } return valid; }
Source:
public RetryingPrestoThriftServiceProvider(@NonRetrying PrestoThriftServiceProvider original, @ForRetryDriver ListeningScheduledExecutorService retryExecutor, ThriftConnectorConfig config) { this.original = requireNonNull(original, "original is null"); requireNonNull(retryExecutor, "retryExecutor is null"); requireNonNull(config, "config is null"); retryingPrestoThriftServiceStats = new RetryingPrestoThriftServiceStats(); retry = RetryDriver.retry(retryExecutor) .maxAttempts(config.getMaxRetryAttempts()) .stopRetryingWhen(e -> e instanceof PrestoThriftServiceException && !((PrestoThriftServiceException) e).isRetryable()) .withClassifier(RetryingPrestoThriftServiceProvider::classifyException) .exponentialBackoff( config.getMinRetrySleepTime(), config.getMaxRetrySleepTime(), config.getMaxRetryDuration(), config.getRetryScaleFactor()); }

Target:
public RetryingPrestoThriftServiceProvider(@NonRetrying PrestoThriftServiceProvider original, @ForRetryDriver ListeningScheduledExecutorService retryExecutor, ThriftConnectorConfig config) { this.original = requireNonNull(original, "original is null"); requireNonNull(retryExecutor, "retryExecutor is null"); requireNonNull(config, "config is null"); retry = RetryDriver.retry(retryExecutor) .maxAttempts(config.getMaxRetryAttempts()) .stopRetryingWhen(e -> e instanceof PrestoThriftServiceException && !((PrestoThriftServiceException) e).isRetryable()) .withClassifier(RetryingPrestoThriftServiceProvider::classifyException) .exponentialBackoff( config.getMinRetrySleepTime(), config.getMaxRetrySleepTime(), config.getMaxRetryDuration(), config.getRetryScaleFactor()); }
Source:
public void whenLogin_thenUseUserCache() throws Exception { assertThat(userCache.size()).isEqualTo(0); ResponseEntity<String> response = restTemplate .withBasicAuth("user", "pass") .getForEntity(getLanguageUrl(), String.class); assertThat(response.getBody()).contains("english"); assertThat(userCache.size()).isEqualTo(1); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.add("Cookie", response.getHeaders().getFirst(HttpHeaders.SET_COOKIE)); response = restTemplate .exchange(getLanguageUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); assertThat(response.getBody()).contains("english"); response = restTemplate.exchange(getLogoutUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); assertThat(response.getStatusCode().value()).isEqualTo(200); }

Target:
public void whenLogin_thenUseUserCache() { assertThat(userCache.size()).isEqualTo(0); ResponseEntity<String> response = restTemplate.withBasicAuth("user", "pass") .getForEntity(getLanguageUrl(), String.class); assertThat(response.getBody()).contains("english"); assertThat(userCache.size()).isEqualTo(1); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.add("Cookie", response.getHeaders() .getFirst(HttpHeaders.SET_COOKIE)); response = restTemplate.exchange(getLanguageUrl(), HttpMethod.GET, new HttpEntity<String>(requestHeaders), String.class); assertThat(response.getBody()).contains("english"); response = restTemplate.exchange(getLogoutUrl(), HttpMethod.GET, new HttpEntity<String>(requestHeaders), String.class); assertThat(response.getStatusCode() .value()).isEqualTo(200); }
Source:
public static MultiTokenSchemaDescriptor multiToken( int[] entityTokens, EntityType entityType, int... propertyIds ) { validatePropertyIds( propertyIds ); IntConsumer validator; if ( entityType == EntityType.NODE ) { validator = SchemaDescriptorFactory::validateLabelId; } else { validator = SchemaDescriptorFactory::validateRelationshipTypeLabelId; } for ( int entityToken : entityTokens ) { validator.accept( entityToken ); } return new MultiTokenSchemaDescriptor( entityTokens, entityType, propertyIds ); }

Target:
public static MultiTokenSchemaDescriptor multiToken( int[] entityTokens, EntityType entityType, int... propertyIds ) { validatePropertyIds( propertyIds ); switch ( entityType ) { case NODE: validateLabelIds( entityTokens ); break; case RELATIONSHIP: validateRelationshipTypeIds( entityTokens ); break; default: throw new IllegalArgumentException( "Cannot create schemadescriptor of type :" + entityType ); } return new MultiTokenSchemaDescriptor( entityTokens, entityType, propertyIds ); }
Source:
public boolean isThisType(String name, boolean open) { String id = new Location(name).getAbsolutePath(); File f = new File(id); boolean dirCheck = f.isDirectory(); if (dirCheck) return false; if (name.endsWith(EXPERIMENT_FILE)) return true; if (!open) return false; try { id = locateExperimentFile(id); } catch (FormatException f) { return false; } catch (IOException f) { return false; } catch (NullPointerException e) { return false; } if (id.endsWith(EXPERIMENT_FILE)) { return true; } return super.isThisType(name, open); }

Target:
public boolean isThisType(String name, boolean open) { Location location = new Location(name); String id = location.getAbsolutePath(); boolean dirCheck = location.isDirectory(); if (dirCheck) return false; if (name.endsWith(EXPERIMENT_FILE)) return true; if (!open) return false; try { id = locateExperimentFile(id); } catch (FormatException f) { return false; } catch (IOException f) { return false; } catch (NullPointerException e) { return false; } if (id.endsWith(EXPERIMENT_FILE)) { return true; } return super.isThisType(name, open); }
Source:
boolean reachedEnd() throws IOException; RowData nextRecord(RowData reuse) throws IOException; default void seekToRow(long rowCount, RowData reuse) throws IOException { for (int i = 0; i < rowCount; i++) { boolean end = reachedEnd(); if (end) { throw new RuntimeException("Seek to many rows."); } nextRecord(reuse); } }

Target:
boolean reachedEnd() throws IOException; RowData nextRecord(RowData reuse) throws IOException; default void seekToRow(long rowCount, RowData reuse) throws IOException { for (int i = 0; i < rowCount; i++) { boolean end = reachedEnd(); if (end) { throw new RuntimeException("Seek too many rows."); } nextRecord(reuse); } }
Source:
private ExecutionResult parseValidateAndExecute(ExecutionInput executionInput) { PreparsedDocumentEntry preparsedDoc = preparsedDocumentProvider.get(executionInput.getQuery(), query -> { ParseResult parseResult = parse(executionInput); if (parseResult.isFailure()) { return new PreparsedDocumentEntry(toInvalidSyntaxError(parseResult.getException())); } else { final Document document = parseResult.getDocument(); final List<ValidationError> errors = validate(executionInput, document); if (!errors.isEmpty()) { return new PreparsedDocumentEntry(errors); } return new PreparsedDocumentEntry(document); } }); if (preparsedDoc.hasErrors()) { return new ExecutionResultImpl(preparsedDoc.getErrors()); } return execute(executionInput, preparsedDoc.getDocument()); }

Target:
private ExecutionResult parseValidateAndExecute(ExecutionInput executionInput) { PreparsedDocumentEntry preparsedDoc = preparsedDocumentProvider.get(executionInput.getQuery(), query -> parseAndValidate(executionInput)); if (preparsedDoc.hasErrors()) { return new ExecutionResultImpl(preparsedDoc.getErrors()); } return execute(executionInput, preparsedDoc.getDocument()); }
Source:
public void test(TestHarness th) { this.th = th; Configuration config = Configuration.getConfiguration(); try { TonePlayer tonePlayer = config.getTonePlayer(); tonePlayer.playTone(ToneControl.C4, 500, 100); Thread.sleep(1000); tonePlayer.playTone(ToneControl.C4, 500, 100); Thread.sleep(400); tonePlayer.playTone(ToneControl.C4 + 2, 500, 100); Thread.sleep(400); tonePlayer.stopTone(); } catch (Exception e) { e.printStackTrace(); th.fail("Unexpected exception: " + e); } }

Target:
public void test(TestHarness th) { Configuration config = Configuration.getConfiguration(); try { TonePlayer tonePlayer = config.getTonePlayer(); tonePlayer.playTone(ToneControl.C4, 500, 100); Thread.sleep(1000); tonePlayer.playTone(ToneControl.C4, 500, 100); Thread.sleep(400); tonePlayer.playTone(ToneControl.C4 + 2, 500, 100); Thread.sleep(400); tonePlayer.stopTone(); th.check(true); } catch (Exception e) { e.printStackTrace(); th.fail("Unexpected exception: " + e); } }
Source:
protected static AggregateLifecycle getInstance() { AggregateLifecycle instance = Scope.getCurrentScope(); if (CurrentUnitOfWork.isStarted()) { UnitOfWork<?> unitOfWork = CurrentUnitOfWork.get(); Set<AggregateLifecycle> managedAggregates = unitOfWork.getResource("ManagedAggregates"); if (managedAggregates != null && managedAggregates.size() == 1) { instance = managedAggregates.iterator().next(); } } return instance; }

Target:
protected static AggregateLifecycle getInstance() { return Scope.getCurrentScope(); }
Source:
public Collection<RegistryObject<T>> getEntries() { if(entriesView.isEmpty()) { return lazyEntriesView.stream().map(LazyRegistryObject::getRegistryObject).collect(Collectors.toSet()); } return entriesView; }

Target:
public Collection<RegistryObject<T>> getEntries() { if(entriesView.isEmpty()) { return Collections.unmodifiableSet(lazyEntries.keySet().stream().map(LazyRegistryObject::getRegistryObject).collect(Collectors.toSet())); } return entriesView; }
Source:
@Test public void deleteCollection() { final List<User> allUsers = putUsers(10); final List<User> usersToDelete = new ArrayList<>(); for (int i = 0; i < allUsers.size(); i += 2) { usersToDelete.add(allUsers.get(i)); } final DeleteCollectionOfObjectsResult<User> deleteResult = storIODb .delete() .objects(usersToDelete) .withMapFunc(User.MAP_TO_DELETE_QUERY) .prepare() .executeAsBlocking(); final List<User> existUsers = storIODb .get() .listOfObjects(User.class) .withMapFunc(User.MAP_FROM_CURSOR) .withQuery(new Query.Builder() .table(User.TABLE) .build()) .prepare() .executeAsBlocking(); for (User user : allUsers) { final boolean deleted = usersToDelete.contains(user); assertEquals(deleteResult.results().containsKey(user), deleted); assertEquals(existUsers.contains(user), !deleted); } }

Target:
@Test public void deleteCollection() { final List<User> allUsers = putUsers(10); final List<User> usersToDelete = new ArrayList<>(); for (int i = 0; i < allUsers.size(); i += 2) { usersToDelete.add(allUsers.get(i)); } final DeleteCollectionOfObjectsResult<User> deleteResult = storIODb .delete() .objects(usersToDelete) .withMapFunc(User.MAP_TO_DELETE_QUERY) .prepare() .executeAsBlocking(); final List<User> existUsers = getAllUsers(); for (User user : allUsers) { final boolean shouldBeDeleted = usersToDelete.contains(user); assertEquals(shouldBeDeleted, deleteResult.wasDeleted(user)); assertEquals(!shouldBeDeleted, existUsers.contains(user)); } }
Source:
protected TemplateInput extractTemplateInputFromXMLNode(Element node) throws DocumentException { String paramName = getNameFromXMLNode(node); InputType paramType = getTypeFromXMLNode(node); String paramDesc = node.getText(); Boolean isReadonly = getIsReadonlyFromXMLNode(node); Boolean isAutoloop = getIsAutoloopFromXMLNode(node); Object paramValue = node.attributeValue("value"); switch (paramType) { case StringValue: case BooleanValue: break; case DateValue: try { SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); paramValue = dateFormat.parse((String) paramValue); } catch (ParseException e) { throw new DocumentException(e); } break; case MapValue: case ListValue: LinkedHashMap<String, TemplateInput> listValue = new LinkedHashMap<>(); for (Element childNode : node.elements()) { TemplateInput childParam = extractTemplateInputFromXMLNode(childNode); if (childNode != null) { listValue.put(childParam.getName(), childParam); } } paramValue = listValue; break; default: paramValue = node.attributeValue("source"); } return TemplateInput.factory(paramName, paramType, paramValue, paramDesc, isReadonly, isAutoloop); }

Target:
protected TemplateInput extractTemplateInputFromXMLNode(Element node) throws DocumentException { String paramName = getNameFromXMLNode(node); InputType paramType = getTypeFromXMLNode(node); String paramDesc = node.getText(); Boolean isReadonly = getIsReadonlyFromXMLNode(node); Boolean isAutoloop = getIsAutoloopFromXMLNode(node); Object paramValue = node.attributeValue("value"); switch (paramType) { case StringValue: case BooleanValue: break; case DateValue: try { SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); paramValue = dateFormat.parse((String) paramValue); } catch (ParseException e) { throw new DocumentException(e); } break; case MapValue: case ListValue: Map<String, TemplateInput> listValue = new LinkedHashMap<>(); for (Element childNode : node.elements()) { TemplateInput childParam = extractTemplateInputFromXMLNode(childNode); if (childNode != null) { listValue.put(childParam.getName(), childParam); } } paramValue = listValue; break; default: paramValue = node.attributeValue("source"); } return TemplateInput.factory(paramName, paramType, paramValue, paramDesc, isReadonly, isAutoloop); }
Source:
IndexMapping(IndexSchemaElement root) { supportedFieldModels = mapSupportedFields( root, "", ignored -> { } ); supportedFieldWithProjectionConverterModels = mapSupportedFields( root, "converted_", c -> c.projectionConverter( ValueWrapper.fromIndexFieldConverter() ) ); string1Field = FieldModel.mapper( String.class, "ccc", "mmm", "xxx" ) .map( root, "string1" ); string2Field = FieldModel.mapper( String.class, "ddd", "nnn", "yyy" ) .map( root, "string2" ); scoreField = FieldModel.mapper( String.class, "scorepattern scorepattern", "scorepattern", "xxx" ) .map( root, "score", c -> ( (StringIndexSchemaFieldTypedContext<?>) c ) .analyzer( DefaultAnalysisDefinitions.ANALYZER_STANDARD.name ) ); flattenedObject = new ObjectMapping( root, "flattenedObject", ObjectFieldStorage.FLATTENED ); nestedObject = new ObjectMapping( root, "nestedObject", ObjectFieldStorage.NESTED ); }

Target:
IndexMapping(IndexSchemaElement root) { supportedFieldModels = mapSupportedFields( root, "", ignored -> { } ); supportedFieldWithProjectionConverterModels = mapSupportedFields( root, "converted_", c -> c.projectionConverter( ValueWrapper.fromIndexFieldConverter() ) ); string1Field = FieldModel.mapper( String.class, "ccc", "mmm", "xxx" ) .map( root, "string1" ); string2Field = FieldModel.mapper( String.class, "ddd", "nnn", "yyy" ) .map( root, "string2" ); scoreField = FieldModel.mapper( String.class, c -> c.asString().analyzer( DefaultAnalysisDefinitions.ANALYZER_STANDARD.name ), "scorepattern scorepattern", "scorepattern", "xxx" ) .map( root, "score" ); flattenedObject = new ObjectMapping( root, "flattenedObject", ObjectFieldStorage.FLATTENED ); nestedObject = new ObjectMapping( root, "nestedObject", ObjectFieldStorage.NESTED ); }
Source:
public void removeParticipantInformation(final ParticipantInformation participantInformation) { if (LOG.isTraceEnabled()) { LOG.trace("RecoveryManager.removeParticipantInformation: participantInformation=" + participantInformation); } final RecoveryStore recoveryStore = StoreManager.getRecoveryStore(); String participantId = participantInformation.getId(); if(committedParticipants.get(participantId) != null) { try { recoveryStore.remove_committed(new Uid(participantId), PARTICIPANT_INFORMATION_RECORD_TYPE); committedParticipants.remove(participantId); } catch (ObjectStoreException e) { LOG.warn("Failure while removing participant information from the object store.", e); } } }

Target:
public void removeParticipantInformation(final ParticipantInformation participantInformation) { if (LOG.isTraceEnabled()) { LOG.trace("RecoveryManager.removeParticipantInformation: participantInformation=" + participantInformation); } final RecoveryStore recoveryStore = StoreManager.getRecoveryStore(); String participantId = participantInformation.getId(); if(persistedParticipants.get(participantId) != null) { try { recoveryStore.remove_committed(new Uid(participantId), PARTICIPANT_INFORMATION_RECORD_TYPE); persistedParticipants.remove(participantId); } catch (ObjectStoreException ose) { LOG.warn("Failure while removing participant information from the object store.", ose); } } }
Source:
private void assertCanReleaseTask(String taskId) { Task task; try { task = task(taskId); } catch (IllegalStateException ex) { throw new IllegalStateException("The authenticated user cannot release task" + taskId + " due it is not a candidate for it"); } if (task.getAssignee() == null || task.getAssignee().isEmpty()) { throw new IllegalStateException("You cannot release a task that is not claimed"); } String authenticatedUserId = securityManager.getAuthenticatedUserId(); if (!task.getAssignee().equals(authenticatedUserId)) { throw new IllegalStateException("You cannot release a task where you are not the assignee"); } }

Target:
private void assertCanReleaseTask(String taskId) { Task task = task(taskId); if (task.getAssignee() == null || task.getAssignee().isEmpty()) { throw new IllegalStateException("You cannot release a task that is not claimed"); } String authenticatedUserId = securityManager.getAuthenticatedUserId(); if (!task.getAssignee().equals(authenticatedUserId)) { throw new IllegalStateException("You cannot release a task where you are not the assignee"); } }
Source:
public Collection<DataSegment> getSegments() { return idToSegmentMap.values(); }

Target:
public Collection<DataSegment> getSegments() { return Collections.unmodifiableCollection(idToSegmentMap.values()); }
Source:
private void updateDetails() { issueDetails.getChildren().clear(); TurboIssue issue = guiElement.getIssue(); if (issue.isPullRequest()) { Label icon = new Label(OCTICON_PULL_REQUEST); icon.getStyleClass().addAll("octicon", "issue-pull-request-icon"); issueDetails.getChildren().add(icon); } if (issue.getCommentCount() > 0){ Label commentIcon = new Label(OCTICON_COMMENT); commentIcon.getStyleClass().addAll("octicon", "comments-label-button"); Label commentCount = new Label(Integer.toString(issue.getCommentCount())); issueDetails.getChildren().add(commentIcon); issueDetails.getChildren().add(commentCount); } for (TurboLabel label : guiElement.getLabels()) { issueDetails.getChildren().add(label.getNode()); } if (issue.getMilestone().isPresent() && guiElement.getMilestone().isPresent()) { TurboMilestone milestone = guiElement.getMilestone().get(); issueDetails.getChildren().add(new Label(milestone.getTitle())); } if (issue.isPullRequest()) { HBox authorBox = createDisplayUserBox(guiElement.getAuthor(), issue.getCreator()); authorAssigneeBox.getChildren().add(authorBox); if (issue.getAssignee().isPresent()) { Label rightArrow = new Label(OCTICON_ARROW_RIGHT); rightArrow.getStyleClass().addAll("octicon", "pull-request-assign-icon"); authorAssigneeBox.getChildren().add(rightArrow); } } if (issue.getAssignee().isPresent()) { HBox assigneeBox = createDisplayUserBox(guiElement.getAssignee(), issue.getAssignee().get()); authorAssigneeBox.getChildren().add(assigneeBox); } }

Target:
private void updateDetails() { issueDetails.getChildren().clear(); TurboIssue issue = guiElement.getIssue(); addPullRequestIcon(issue); addCommentIcon(issue); addLabels(); addMilestoneIcon(issue); createAuthorBox(issue); createAssigneeBox(issue); }
Source:
public String escapeHeader(final String text) { return text.replace("\r", "\\\r").replace("\n", "\\\n").replace("\\", "\\\\").replace("\"", "\\\""); }

Target:
private String escapeHeader(final String text) { return MimeUtility.unfold(text).replace("\\", "\\\\").replace("\"", "\\\""); }
Source:
public synchronized @Nullable PcapNgPacket parseNextPacket() throws IOException, BadPcapFileException, BadPacketException { ByteBuffer pcapPacketHeader; ByteBuffer pcapPacketData; pcapPacketHeader = parsePacketHeader(); int blockType = 0; int blockLength = 0; if (pcapPacketHeader != null) { blockType = pcapPacketHeader.getInt(); blockLength = pcapPacketHeader.getInt(); } else { return null; } switch (blockType) { case PcapFileValues.PCAPNG_IDB: pcapPacketData = parsePacketIDBAndNRB(blockLength); break; case PcapFileValues.PCAPNG_SPB: pcapPacketData = parsePacketSPB(pcapPacketHeader, blockLength); break; case PcapFileValues.PCAPNG_NRB: return null; case PcapFileValues.PCAPNG_ISB: parsePacketISB(pcapPacketHeader, blockLength); return null; case PcapFileValues.PCAPNG_PB: case PcapFileValues.PCAPNG_EPB: pcapPacketData = parsePayLoad(pcapPacketHeader, blockLength); break; default:// Invalid block type found throw new BadPcapFileException(String.format("%04x", blockType) + " is an invalid pcapNg block type."); } ++currentRank; TreeMap<Long, Long> fFileIndex = getFileIndex(); SeekableByteChannel fFileChannel = getFileChannel(); fFileIndex.put(currentRank, fFileChannel.position()); setCurrentRank(currentRank); return new PcapNgPacket(this, null, pcapPacketHeader, pcapPacketData, currentRank - 1); }

Target:
public synchronized @Nullable PcapNgPacket parseNextPacket() throws IOException, BadPcapFileException, BadPacketException { ByteBuffer pcapPacketHeader; ByteBuffer pcapPacketData; pcapPacketHeader = parsePacketHeader(); int blockType = 0; int blockLength = 0; if (pcapPacketHeader != null) { blockType = pcapPacketHeader.getInt(); blockLength = pcapPacketHeader.getInt(); } else { return null; } switch (blockType) { case PcapFileValues.PCAPNG_IDB: pcapPacketData = parsePacketIDBAndNRB(blockLength); break; case PcapFileValues.PCAPNG_SPB: pcapPacketData = parsePacketSPB(pcapPacketHeader, blockLength); break; case PcapFileValues.PCAPNG_NRB: pcapPacketData = parsePacketIDBAndNRB(blockLength); return new PcapNgPacket(this, null, pcapPacketHeader, pcapPacketData, getCurrentRank() - 1); case PcapFileValues.PCAPNG_ISB: pcapPacketData = parsePacketISB(pcapPacketHeader, blockLength); return new PcapNgPacket(this, null, pcapPacketHeader, pcapPacketData, getCurrentRank() - 1); case PcapFileValues.PCAPNG_PB: case PcapFileValues.PCAPNG_EPB: pcapPacketData = parsePayLoad(pcapPacketHeader, blockLength); break; default:// Invalid block type found throw new BadPcapFileException(String.format("%04x", blockType) + " is an invalid pcapNg block type."); } setCurrentRank(getCurrentRank()+1); TreeMap<Long, Long> fileIndex = getFileIndex(); SeekableByteChannel fFileChannel = getFileChannel(); fileIndex.put(getCurrentRank(), fFileChannel.position()); setCurrentRank(getCurrentRank()); return new PcapNgPacket(this, null, pcapPacketHeader, pcapPacketData, getCurrentRank() - 1); }