auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void doStart() throws Exception { super.doStart(); BasicCacheContainer cacheContainer = configuration.getCacheContainer(); cache = InfinispanUtil.getCache(configuration.getCacheContainer(), configuration.getCacheName()); if (configuration.hasQueryBuilder()) { if (InfinispanUtil.isRemote(cache)) { RemoteCache<Object, Object> remoteCache = InfinispanUtil.asRemote(cache); Query query = InfinispanRemoteOperation.buildQuery(configuration.getQueryBuilder(), remoteCache); continuousQuery = Search.getContinuousQuery(remoteCache); continuousQuery.addContinuousQueryListener(query, new ContinuousQueryEventListener(cache.getName())); } else { throw new IllegalArgumentException("Can't run continuous queries against embedded cache (" + cache.getName() + ")"); } } else { if (InfinispanUtil.isEmbedded(cacheContainer)) { consumerHandler = InfinispanConsumerEmbeddedHandler.INSTANCE; } else if (InfinispanUtil.isRemote(cacheContainer)) { consumerHandler = InfinispanConsumerRemoteHandler.INSTANCE; } else { throw new UnsupportedOperationException("Consumer not support for CacheContainer: " + cacheContainer); } listener = consumerHandler.start(this); } }

Target:
protected void doStart() throws Exception { super.doStart(); BasicCacheContainer cacheContainer = configuration.getCacheContainer(); cache = InfinispanUtil.getCache(configuration.getCacheContainer(), configuration.getCacheName()); if (configuration.hasQueryBuilder()) { if (InfinispanUtil.isRemote(cache)) { RemoteCache<Object, Object> remoteCache = InfinispanUtil.asRemote(cache); Query query = InfinispanRemoteOperation.buildQuery(configuration.getQueryBuilder(), remoteCache); continuousQuery = Search.getContinuousQuery(remoteCache); continuousQuery.addContinuousQueryListener(query, new ContinuousQueryEventListener(cache.getName())); } else { throw new IllegalArgumentException("Can't run continuous queries against embedded cache (" + cache.getName() + ")"); } } else { if (InfinispanUtil.isEmbedded(cacheContainer)) { consumerHandler = InfinispanConsumerEmbeddedHandler.INSTANCE; } else if (InfinispanUtil.isRemote(cacheContainer)) { consumerHandler = InfinispanConsumerRemoteHandler.INSTANCE; } else { throw new UnsupportedOperationException("CacheContainer of type " + cacheContainer.getClass().getName() + " not supported"); } listener = consumerHandler.start(this); } }
Source:
public Matrix4 setToRotation(final Axis axis, double angle) { if (angle == 0) return identity(); return setAll(mQuat.fromAngleAxis(axis, angle)); }

Target:
public Matrix4 setToRotation(final Axis axis, double angle) { return angle == 0 ? identity() : setAll(mQuat.fromAngleAxis(axis, angle)); }
Source:
protected boolean validate() { final boolean result = validateImpl(); if (!result && !isInternalExecution() && !getParameters().isRerun()) { logValidationFailed(); } return result; }

Target:
protected final boolean validate() { final boolean result = validateImpl(); if (!result && !isInternalExecution() && !getParameters().isRerun()) { logValidationFailed(); } return result; }
Source:
public void setIndexingPolicy(IndexingPolicy indexingPolicy) { if (indexingPolicy == null) { throw new IllegalArgumentException("IndexingPolicy cannot be null."); } this.indexingPolicy = indexingPolicy; setProperty(this, Constants.Properties.INDEXING_POLICY, this.indexingPolicy); }

Target:
public void setIndexingPolicy(IndexingPolicy indexingPolicy) { if (indexingPolicy == null) { throw new IllegalArgumentException("IndexingPolicy cannot be null."); } this.indexingPolicy = indexingPolicy; }
Source:
public boolean apply(Game game, Ability source) { Player targetPlayer = game.getPlayer(this.getTargetPointer().getFirst(game, source)); if (targetPlayer == null || targetPlayer.getHand().isEmpty()) { return false; } if (targetPlayer.getHand().count(StaticFilters.FILTER_CARD_ARTIFACT, game) < 1 || !targetPlayer.chooseUse(outcome, "Discard an artifact card?", source, game)) { return !targetPlayer.discard(2, false, source, game).isEmpty(); } TargetDiscard target = new TargetDiscard(StaticFilters.FILTER_CARD_ARTIFACT_AN, targetPlayer.getId()); targetPlayer.choose(Outcome.Discard, target, source.getSourceId(), game); Card card = targetPlayer.getHand().get(target.getFirstTarget(), game); if (card != null && targetPlayer.discard(card, source, game)) { return true; } return !targetPlayer.discard(2, false, source, game).isEmpty(); }

Target:
public boolean apply(Game game, Ability source) { Player targetPlayer = game.getPlayer(this.getTargetPointer().getFirst(game, source)); if (targetPlayer == null || targetPlayer.getHand().isEmpty()) { return false; } if (targetPlayer.getHand().count(StaticFilters.FILTER_CARD_ARTIFACT, game) < 1 || !targetPlayer.chooseUse(Outcome.Benefit, "Discard an artifact card?", source, game)) { return !targetPlayer.discard(2, false, source, game).isEmpty(); } TargetDiscard target = new TargetDiscard(StaticFilters.FILTER_CARD_ARTIFACT_AN, targetPlayer.getId()); targetPlayer.choose(Outcome.Discard, target, source.getSourceId(), game); Card card = targetPlayer.getHand().get(target.getFirstTarget(), game); if (card != null && targetPlayer.discard(card, source, game)) { return true; } return !targetPlayer.discard(2, false, source, game).isEmpty(); }
Source:
public Map toMap() { Map map = super.toMap(); map.put(TYPE, type.name()); return map; }

Target:
public Map<String, Object> toMap() { Map map = super.toMap(); map.put(TYPE, type.name()); return map; }
Source:
public Config() { this(null, org.voltdb.VoltDB.DEFAULT_INTERNAL_PORT); acceptor = org.voltdb.probe.MeshProber.builder() .coordinators(":" + internalPort) .build(); }

Target:
public Config() { this(null, org.voltcore.common.Constants.DEFAULT_INTERNAL_PORT); acceptor = org.voltdb.probe.MeshProber.builder() .coordinators(":" + internalPort) .build(); }
Source:
private <T> SortedMap<Cell, T> postFilterRows( TableReference tableRef, List<RowResult<Value>> rangeRows, Function<Value, T> transformer) { ensureUncommitted(); if (rangeRows.isEmpty()) { return ImmutableSortedMap.of(); } Map<Cell, Value> rawResults = Maps.newHashMapWithExpectedSize(estimateSize(rangeRows)); for (RowResult<Value> rowResult : rangeRows) { for (Map.Entry<byte[], Value> e : rowResult.getColumns().entrySet()) { rawResults.put(Cell.create(rowResult.getRowName(), e.getKey()), e.getValue()); } } return getWithPostFiltering( tableRef, rawResults, input -> ImmutableSortedMap.<Cell, T>naturalOrder().putAll(input).build(), transformer); }

Target:
private <T> SortedMap<Cell, T> postFilterRows( TableReference tableRef, List<RowResult<Value>> rangeRows, Function<Value, T> transformer) { ensureUncommitted(); if (rangeRows.isEmpty()) { return ImmutableSortedMap.of(); } Map<Cell, Value> rawResults = Maps.newHashMapWithExpectedSize(estimateSize(rangeRows)); for (RowResult<Value> rowResult : rangeRows) { for (Map.Entry<byte[], Value> e : rowResult.getColumns().entrySet()) { rawResults.put(Cell.create(rowResult.getRowName(), e.getKey()), e.getValue()); } } return ImmutableSortedMap.copyOf(getWithPostFilteringSync(tableRef, rawResults, transformer)); }
Source:
public void run() { if ( !moveToRunningState() ) { return; } try { applicationProcess.pauseApplier( OPERATION_NAME ); while ( keepRunning ) { try { downloader.downloadSnapshot( addressProvider ); break; } catch ( StoreCopyFailedException e ) { log.error( format( "Failed to download snapshot. Retrying in %s ms.", timeout.getMillis() ), e ); } Thread.sleep( timeout.getMillis() ); timeout.increment(); } } catch ( InterruptedException e ) { Thread.interrupted(); log.error( "Persistent snapshot downloader was interrupted" ); } finally { applicationProcess.resumeApplier( OPERATION_NAME ); state = State.COMPLETED; } }

Target:
public void run() { if ( !moveToRunningState() ) { return; } try { applicationProcess.pauseApplier( OPERATION_NAME ); while ( keepRunning && !downloader.downloadSnapshot( addressProvider ) ) { Thread.sleep( timeout.getMillis() ); timeout.increment(); } } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); log.warn( "Persistent snapshot downloader was interrupted" ); } catch ( DatabaseShutdownException e ) { log.warn( "Store copy aborted due to shut down", e ); } catch ( Throwable e ) { log.error( "Unrecoverable error during store copy", e ); dbHealth.get().panic( e ); } finally { applicationProcess.resumeApplier( OPERATION_NAME ); state = State.COMPLETED; } }
Source:
public ResourcesEntry(int quark, LttngKernelTrace trace, String name, long startTime, long endTime, Type type, int id) { super(quark, trace, name, startTime, endTime); fId = id; fType = type; }

Target:
public ResourcesEntry(int quark, LttngKernelTrace trace, String name, long startTime, long endTime, Type type, int id) { super(quark, trace, name, startTime, endTime); fId = id; fType = type; fQuark = quark; }
Source:
private void showListOfPackages(final boolean includeDefaultPackage, final Command packagesLoadedCommand) { final Module activeModule = projectContext.getActiveModule().orElse(null); if (activeModule == null) { return; } else { moduleService.call((Set<Package> pkgs) -> { moduleService.call((Package activePackage) -> { final List<Package> sortedPackages = getPackages(includeDefaultPackage, pkgs); if (sortedPackages.size() == 0) { return; } addPackagesToSelect(sortedPackages, activePackage); if (packagesLoadedCommand != null) { packagesLoadedCommand.execute(); } }).resolveDefaultWorkspacePackage(activeModule); }).resolvePackages(activeModule); } }

Target:
private void showListOfPackages(final boolean includeDefaultPackage, final Command packagesLoadedCommand) { final Module activeModule = projectContext.getActiveModule().orElse(null); if (activeModule == null) { return; } else { moduleService.call((Set<Package> pkgs) -> { moduleService.call((Package activePackage) -> { final List<Package> sortedPackages = getPackages(includeDefaultPackage, pkgs); if (sortedPackages.isEmpty()) { return; } addPackagesToSelect(sortedPackages, activePackage); if (packagesLoadedCommand != null) { packagesLoadedCommand.execute(); } }).resolveDefaultWorkspacePackage(activeModule); }).resolvePackages(activeModule); } }
Source:
public ClientOptions setApplicationId(String applicationId) { if (!CoreUtils.isNullOrEmpty(applicationId)) { if (applicationId.length() > MAX_APPLICATION_ID_LENGTH) { throw logger .logExceptionAsError(new IllegalArgumentException("'applicationId' length cannot be greater than " + MAX_APPLICATION_ID_LENGTH)); } else if (applicationId.contains(" ")) { throw logger .logExceptionAsError(new IllegalArgumentException("'applicationId' must not contain a space.")); } else { this.applicationId = applicationId; } } return this; }

Target:
public ClientOptions setApplicationId(String applicationId) { if (CoreUtils.isNullOrEmpty(applicationId)) { this.applicationId = applicationId; return this; } if (applicationId.length() > MAX_APPLICATION_ID_LENGTH) { throw logger .logExceptionAsError(new IllegalArgumentException("'applicationId' length cannot be greater than " + MAX_APPLICATION_ID_LENGTH)); } else if (applicationId.contains(" ")) { throw logger .logExceptionAsError(new IllegalArgumentException("'applicationId' must not contain a space.")); } else { this.applicationId = applicationId; } return this; }
Source:
public final void init() { preInit(); controls = new LinkedHashMap<SWTGridCell, Control>(); if (getViewModelContext() != null) { listener = new ModelChangeListener() { @Override public void notifyChange(ModelChangeNotification notification) { if (!renderingFinished) { return; } if (notification.getRawNotification().isTouch()) { return; } if (notification.getNotifier() != getVElement()) { return; } if (notification.getStructuralFeature() == VViewPackage.eINSTANCE.getElement_Visible()) { applyVisible(); } if (notification.getStructuralFeature() == VViewPackage.eINSTANCE.getElement_Enabled() && !getVElement().isReadonly()) { applyEnable(); } if (notification.getStructuralFeature() == VViewPackage.eINSTANCE .getElement_Diagnostic()) { applyValidation(); final VDiagnostic newDia = (VDiagnostic) notification.getRawNotification().getNewValue(); final VDiagnostic oldDia = (VDiagnostic) notification.getRawNotification().getOldValue(); final List<Object> diff = new ArrayList<Object>(); if (newDia != null) { diff.addAll(newDia.getDiagnostics()); } if (oldDia != null) { diff.removeAll(oldDia.getDiagnostics()); } final List<Object> diff2 = new ArrayList<Object>(); if (oldDia != null) { diff2.addAll(oldDia.getDiagnostics()); } if (newDia != null) { diff2.removeAll(newDia.getDiagnostics()); } diff.addAll(diff2); final Set<Object> toUpdate = new LinkedHashSet<Object>(); for (final Object o : diff) { final EObject toAdd = (EObject) Diagnostic.class.cast(o).getData().get(0); toUpdate.add(toAdd); EObject parent = toAdd.eContainer(); while (parent != null) { toUpdate.add(parent); parent = parent.eContainer(); } } applyValidation(toUpdate.toArray()); } } }; getViewModelContext().registerViewChangeListener(listener); } getViewModelContext().addContextUser(this); postInit(); }

Target:
public final void init() { preInit(); controls = new LinkedHashMap<SWTGridCell, Control>(); if (getViewModelContext() != null) { listener = new ModelChangeListener() { @Override public void notifyChange(ModelChangeNotification notification) { if (!renderingFinished) { return; } if (notification.getRawNotification().isTouch()) { return; } if (notification.getNotifier() != getVElement()) { return; } if (notification.getStructuralFeature() == VViewPackage.eINSTANCE.getElement_Visible()) { applyVisible(); } if (notification.getStructuralFeature() == VViewPackage.eINSTANCE.getElement_Enabled() && !getVElement().isReadonly()) { applyEnable(); } if (notification.getStructuralFeature() == VViewPackage.eINSTANCE .getElement_Diagnostic()) { applyValidation(); final VDiagnostic newDia = (VDiagnostic) notification.getRawNotification().getNewValue(); final VDiagnostic oldDia = (VDiagnostic) notification.getRawNotification().getOldValue(); applyValidation(oldDia, newDia); } } }; getViewModelContext().registerViewChangeListener(listener); } getViewModelContext().addContextUser(this); postInit(); }
Source:
public static void main(String[] args) { NotificationProperties prop = null; NotificationService notificationService = null; EngineMonitorService engineMonitorService = null; try { prop = NotificationProperties.getInstance(); if (prop.isConfigured(LOG_LEVEL)) { JavaLoggingUtils.setLogLevel(prop.getProperty(LOG_LEVEL)); } prop.validate(); notificationService = new NotificationService(prop); engineMonitorService = new EngineMonitorService(prop); notificationService.registerTransport(new Smtp(prop)); notificationService.registerTransport(new Snmp(prop)); if (!notificationService.hasTransports()) { throw new RuntimeException( "No transport is enabled, please enable at least one of SMTP (using MAIL_SERVER option)" + " or SNMP (using SNMP_MANAGERS option) transports."); } } catch (Exception ex) { log.error("Failed to initialize", ex); System.err.println(ex.getMessage()); System.exit(1); } if (args != null && args.length > 0 && ARG_VALIDATE.equals(args[0])) { System.exit(0); } try { notificationService.run(); engineMonitorService.run(); } catch (Exception e) { log.error("Failed to run the event notification service. ", e); System.exit(1); } }

Target:
public static void main(String[] args) { NotificationProperties prop = null; NotificationService notificationService = null; EngineMonitorService engineMonitorService = null; try { prop = NotificationProperties.getInstance(); JavaLoggingUtils.setLogLevel(prop.getProperty(LOG_LEVEL)); prop.validate(); notificationService = new NotificationService(prop); engineMonitorService = new EngineMonitorService(prop); notificationService.registerTransport(new Smtp(prop)); notificationService.registerTransport(new Snmp(prop)); if (!notificationService.hasTransports()) { throw new RuntimeException( "No transport is enabled, please enable at least one of SMTP (using MAIL_SERVER option)" + " or SNMP (using SNMP_MANAGERS option) transports."); } } catch (Exception ex) { log.error("Failed to initialize", ex); System.err.println(ex.getMessage()); System.exit(1); } if (args != null && args.length > 0 && ARG_VALIDATE.equals(args[0])) { System.exit(0); } try { notificationService.run(); engineMonitorService.run(); } catch (Exception e) { log.error("Failed to run the event notification service. ", e); System.exit(1); } }
Source:
private static void updateStepMessage(CommandBase<?> cmd, Guid vdsForExecution) { StepEnum stepEnum = null; try { stepEnum = StepEnum.valueOf(cmd.getCommandStep().toString() + "_ON_HOST"); } catch (IllegalArgumentException e) { } if (stepEnum != null) { Step step = cmd.getExecutionContext().getStep(); Map<String, String> jobProperties = cmd.getJobMessageProperties(); jobProperties.put("VDS", getVdsDao().get(vdsForExecution).getName()); step.setDescription(ExecutionMessageDirector.resolveStepMessage(stepEnum, jobProperties)); getStepDao().update(step); } }

Target:
private static void updateStepMessage(CommandBase<?> cmd, Guid vdsForExecution) { StepEnum stepEnum = null; try { stepEnum = StepEnum.valueOf(cmd.getCommandStep().toString() + "_ON_HOST"); } catch (IllegalArgumentException e) { log.debug("No StepEnum found for "+cmd.getCommandStep().toString() + "_ON_HOST"); return; } Step step = cmd.getExecutionContext().getStep(); Map<String, String> jobProperties = cmd.getJobMessageProperties(); jobProperties.put("VDS", getVdsDao().get(vdsForExecution).getName()); step.setDescription(ExecutionMessageDirector.resolveStepMessage(stepEnum, jobProperties)); getStepDao().update(step); }
Source:
protected void setUp() throws Exception { super.setUp(); getContext().getCacheDir(); System.setProperty("dexmaker.dexcache", getContext().getCacheDir().getPath()); getContext().getCacheDir(); System.setProperty("dexmaker.dexcache", getContext().getCacheDir().getPath()); }

Target:
protected void setUp() throws Exception { super.setUp(); getContext().getCacheDir(); System.setProperty("dexmaker.dexcache", getContext().getCacheDir().getPath()); }
Source:
public SearchResult search(String catalogId, String field, String term, int rows) { loadOPACConfiguration(catalogId); HashMap<String, String> searchFields = new HashMap<>(); searchFields.put(field, term); return search(catalogId, searchFields, rows); }

Target:
public SearchResult search(String catalogId, String field, String term, int rows) { loadOPACConfiguration(catalogId); HashMap<String, String> searchFields = new HashMap<>(); searchFields.put(field, term); return search(catalogId, searchFields); }
Source:
public void updateVendorThingID(@NonNull String newVendorThingID, @NonNull String newPassword) throws ThingIFException { thingIfApi.updateVendorThingID(newVendorThingID, newPassword); }

Target:
public void updateVendorThingID(@NonNull String newVendorThingID, @NonNull String newPassword) throws ThingIFException { this.thingIfApi.updateVendorThingID(newVendorThingID, newPassword); }
Source:
public void shouldCreateACondition() throws Exception { long originalCount = getAllCount(); SimpleObject conditionSource = new SimpleObject(); conditionSource.add("condition_id", 2); conditionSource.add("additional_detail", ""); conditionSource.add("condition_coded", 1); conditionSource.add("clinical_status", "ACTIVE"); conditionSource.add("verification_status", "CONFIRMED"); conditionSource.add("onset_date", "2018-02-20 00:00:00.0"); String json = new ObjectMapper().writeValueAsString(conditionSource); MockHttpServletRequest req = request(RequestMethod.POST, getURI()); req.setContent(json.getBytes()); SimpleObject newConditionSource = deserialize(handle(req)); Assert.assertNotNull(PropertyUtils.getProperty(newConditionSource, "uuid")); Assert.assertEquals(originalCount + 1, getAllCount()); }

Target:
public void shouldCreateACondition() throws Exception { CodedOrFreeText cond = new CodedOrFreeText(); cond.setNonCoded("Some condition"); SimpleObject conditionSource = new SimpleObject(); conditionSource.add("condition", cond); conditionSource.add("patient", patient.getUuid()); conditionSource.add("clinicalStatus", ConditionClinicalStatus.ACTIVE); conditionSource.add("verificationStatus", ConditionVerificationStatus.CONFIRMED); conditionSource.add("onsetDate", "2017-01-12 00:00:00"); String json = new ObjectMapper().writeValueAsString(conditionSource); MockHttpServletRequest req = request(RequestMethod.POST, getURI()); req.setContent(json.getBytes()); MockHttpServletResponse res = handle(req); SimpleObject newConditionSource = deserialize(res); String uuid = newConditionSource.get("uuid"); LinkedHashMap nonCoded = newConditionSource.get("condition"); LinkedHashMap patient = newConditionSource.get("patient"); Assert.assertNotNull(conditionService.getConditionByUuid(uuid)); Condition condition = conditionService.getConditionByUuid(uuid); Assert.assertEquals(nonCoded.get("nonCoded"), condition.getCondition().getNonCoded()); Assert.assertEquals(patient.get("uuid"), condition.getPatient().getUuid()); Assert.assertEquals(newConditionSource.get("clinicalStatus"), condition.getClinicalStatus().toString()); Assert.assertEquals(newConditionSource.get("verificationStatus"), condition.getVerificationStatus().toString()); Assert.assertNotNull(newConditionSource.get("onsetDate")); }
Source:
private String getDurationTime(IRepositoryElement element) { if (element instanceof IRepositoryQuery) { RepositoryQuery query = (RepositoryQuery) element; long duration_max = parseLongFromString(query.getAttribute("duration_max")); if (duration_max > 2 * 60 * 1000) { long duration_min = parseLongFromString(query.getAttribute("duration_min")); long duration_avg = parseLongFromString(query.getAttribute("duration_avg")); long duration_anz = parseLongFromString(query.getAttribute("duration_anz")); String erg = "Min: " + (duration_min == 0 ? "" : "" + duration_min / 1000 + "s") + " Max: " + (duration_max == 0 ? "" : "" + duration_max / 1000 + "s") + " Anz: " + (duration_anz == 0 ? "" : "" + duration_anz) + " Avg: " + (duration_avg == 0 ? "" : "" + duration_avg / 1000 + "s"); return erg; } } return null; }

Target:
private String getDurationTime(IRepositoryElement element) { if (element instanceof IRepositoryQuery) { RepositoryQuery query = (RepositoryQuery) element; long duration_max = parseLongFromString(query.getAttribute("org.eclipse.mylyn.duration.duration_max")); if (duration_max > 0 && duration_max < 3 * 60 * 1000) { long duration_min = parseLongFromString(query.getAttribute("org.eclipse.mylyn.duration.duration_min")); long duration_avg = parseLongFromString(query.getAttribute("org.eclipse.mylyn.duration.duration_avg")); long duration_count = parseLongFromString(query.getAttribute("org.eclipse.mylyn.duration.duration_count")); String erg = "Min: " + (duration_min == 0 ? "" : (duration_min < 1000 ? "<1" : "" + duration_min / 1000) + "s") + " Max: " + (duration_max == 0 ? "" : (duration_max < 1000 ? "<1" : "" + duration_max / 1000) + "s") + " Count: " + (duration_count == 0 ? "" : "" + duration_count) + " Avg: " + (duration_avg == 0 ? "" : "" + (duration_avg < 1000 ? "<1" : "" + duration_avg / 1000) + "s"); return erg; } } return null; }
Source:
public final void sync(ContentResolver contentResolver, SyncResult syncResult, ContentProviderClient providerClient) throws Throwable { boolean okToProceedSync = beforeSyncStarted(contentResolver, syncResult, providerClient); if(!okToProceedSync) { LOG.w("Skipping synchronization for %s", this.getClass().getName()); return; } String syncToken = SyncAdapter.getLastSyncToken(providerClient, dbTable); IncrementalSyncResponse<T> response; do { RequestFuture<IncrementalSyncResponse<T>> future = RequestFuture.newFuture(); createRequest(syncToken, future, future); response = future.get(); ArrayList<ContentProviderOperation> ops = getUpdateOps(response.results, syncResult); providerClient.applyBatch(ops); LOG.i("Updated page of %s (%d db ops)", resourceType, ops.size()); syncToken = response.syncToken; } while (response.more); SyncAdapter.storeSyncToken(providerClient, dbTable, response.syncToken); afterSyncFinished(contentResolver, syncResult, providerClient); }

Target:
public final void sync(ContentResolver contentResolver, SyncResult syncResult, ContentProviderClient providerClient) throws Throwable { boolean okToProceedSync = beforeSyncStarted(contentResolver, syncResult, providerClient); if(!okToProceedSync) { LOG.w("Skipping synchronization for %s", this.getClass().getSimpleName()); return; } String syncToken = SyncAdapter.getLastSyncToken(providerClient, dbTable); LOG.i("Using sync token `%s`", syncToken); IncrementalSyncResponse<T> response; do { RequestFuture<IncrementalSyncResponse<T>> future = RequestFuture.newFuture(); createRequest(syncToken, future, future); response = future.get(); ArrayList<ContentProviderOperation> ops = getUpdateOps(response.results, syncResult); providerClient.applyBatch(ops); LOG.i("Updated page of %s (%d db ops)", resourceType, ops.size()); syncToken = response.syncToken; } while (response.more); LOG.i("Saving new sync token `%s`", syncToken); SyncAdapter.storeSyncToken(providerClient, dbTable, response.syncToken); afterSyncFinished(contentResolver, syncResult, providerClient); }
Source:
private byte[] makeRequest(byte[] requestPayload) throws TTransportException, IOException { String encoded = Base64.encodeBase64String(requestPayload); StringEntity requestEntity = new StringEntity( encoded, ContentType.create(HttpHeaders.APPLICATION_X_FRUGAL_HEADER, HttpHeaders.CONTENT_TYPE)); HttpPost request = new HttpPost(url); request.setHeader(HttpHeaders.ACCEPT_HEADER, HttpHeaders.APPLICATION_X_FRUGAL_HEADER); request.setHeader(HttpHeaders.CONTENT_TRANSFER_ENCODING_HEADER, HttpHeaders.CONTENT_TRANSFER_ENCODING); if (responseSizeLimit > 0) { request.setHeader(HttpHeaders.X_FRUGAL_PAYLOAD_LIMIT_HEADER, Integer.toString(responseSizeLimit)); } request.setEntity(requestEntity); CloseableHttpResponse response = httpClient.execute(request); String responseBody = ""; try { int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_REQUEST_TOO_LONG) { throw new FMessageSizeException(FTransport.RESPONSE_TOO_LARGE, "response was too large for the transport"); } if (status >= 300) { throw new TTransportException("Error: " + response.getStatusLine().toString()); } HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { responseBody = EntityUtils.toString(responseEntity, "utf-8"); } EntityUtils.consume(responseEntity); } finally { response.close(); } return Base64.decodeBase64(responseBody); }

Target:
private byte[] makeRequest(byte[] requestPayload) throws TTransportException, IOException { String encoded = Base64.encodeBase64String(requestPayload); StringEntity requestEntity = new StringEntity( encoded, ContentType.create(HttpHeaders.APPLICATION_X_FRUGAL_HEADER, HttpHeaders.CONTENT_TYPE)); HttpPost request = new HttpPost(url); request.setHeader(HttpHeaders.ACCEPT_HEADER, HttpHeaders.APPLICATION_X_FRUGAL_HEADER); request.setHeader(HttpHeaders.CONTENT_TRANSFER_ENCODING_HEADER, HttpHeaders.CONTENT_TRANSFER_ENCODING); if (responseSizeLimit > 0) { request.setHeader(HttpHeaders.X_FRUGAL_PAYLOAD_LIMIT_HEADER, Integer.toString(responseSizeLimit)); } request.setEntity(requestEntity); CloseableHttpResponse response = httpClient.execute(request); String responseBody = ""; try { int status = response.getStatusLine().getStatusCode(); if (status >= 300) { throw new TTransportException("Error: " + response.getStatusLine().toString()); } HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { responseBody = EntityUtils.toString(responseEntity, "utf-8"); } EntityUtils.consume(responseEntity); } finally { response.close(); } return Base64.decodeBase64(responseBody); }
Source:
public static SQLContext getSqlContext() { return SparkSession.builder().appName("Java Spark Tests").master("local[2]") .config("spark.ui.showConsoleProgress", false).getOrCreate().sqlContext(); }

Target:
public static SQLContext getSqlContext() { return SparkSession.builder().appName(APP_NAME).master(NUM_EXECUTORS) .config(UI_SHOW_CONSOLE_PROGRESS, false).getOrCreate().sqlContext(); }
Source:
public ValidationResult isDomainWithinThresholds() { StorageDomainDynamic dynamic = storageDomain.getStorageDynamicData(); if (dynamic != null && dynamic.getfreeDiskInGB() > getLowDiskSpaceThreshold()) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_TARGET_STORAGE_DOMAIN, storageName()); } return ValidationResult.VALID; }

Target:
public ValidationResult isDomainWithinThresholds() { StorageDomainDynamic dynamic = storageDomain.getStorageDynamicData(); if (dynamic != null && dynamic.getfreeDiskInGB() < getLowDiskSpaceThreshold()) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_TARGET_STORAGE_DOMAIN, storageName()); } return ValidationResult.VALID; }
Source:
private void assertValueUnchecked(Block rowBlock, int internalPosition, List<Object> row) { requireNonNull(row, "row is null"); assertFalse(rowBlock.isNullUnchecked(internalPosition)); SingleRowBlock singleRowBlock = (SingleRowBlock) rowBlock.getBlockUnchecked(internalPosition); assertEquals(singleRowBlock.getPositionCount(), row.size()); for (int i = 0; i < row.size(); i++) { Object fieldValue = row.get(i); if (fieldValue == null) { assertTrue(singleRowBlock.isNullUnchecked(i + singleRowBlock.getOffsetBase())); } else { if (fieldValue instanceof Long) { assertEquals(BIGINT.getLongUnchecked(singleRowBlock, i + singleRowBlock.getOffsetBase()), ((Long) fieldValue).longValue()); } else if (fieldValue instanceof String) { assertEquals(VARCHAR.getSliceUnchecked(singleRowBlock, i + singleRowBlock.getOffsetBase()), utf8Slice((String) fieldValue)); } else { throw new IllegalArgumentException(); } } } }

Target:
private void assertValueUnchecked(Block rowBlock, int internalPosition, List<Object> row) { requireNonNull(row, "row is null"); assertFalse(rowBlock.isNullUnchecked(internalPosition)); SingleRowBlock singleRowBlock = (SingleRowBlock) rowBlock.getBlockUnchecked(internalPosition); assertEquals(singleRowBlock.getPositionCount(), row.size()); for (int i = 0; i < row.size(); i++) { Object fieldValue = row.get(i); if (fieldValue == null) { assertTrue(singleRowBlock.isNullUnchecked(i + singleRowBlock.getOffsetBase())); } else { if (fieldValue instanceof Long) { assertEquals(BIGINT.getLongUnchecked(singleRowBlock, i + singleRowBlock.getOffsetBase()), ((Long) fieldValue).longValue()); } else if (fieldValue instanceof String) { assertEquals(VARCHAR.getSliceUnchecked(singleRowBlock, i + singleRowBlock.getOffsetBase()), utf8Slice((String) fieldValue)); } else { fail("Unexpected type: " + fieldValue.getClass().getSimpleName()); } } } }
Source:
private Disk getUnregisteredDisk() { QueryReturnValue queryReturnValue = backend.runInternalQuery(QueryType.GetUnregisteredDisk, new GetUnregisteredDiskQueryParameters( getParameters().getDiskId(), getParameters().getStorageDomainId(), getStoragePoolId()) ); if (queryReturnValue.getSucceeded()) { return queryReturnValue.getReturnValue(); } log.error("Failed to find unregistered disk with the following ID '{}' in storage domain '{}'", getParameters().getDiskId(), getParameters().getStorageDomainId()); return null; }

Target:
private Disk getUnregisteredDisk() { QueryReturnValue queryReturnValue = backend.runInternalQuery(QueryType.GetUnregisteredDisk, new GetUnregisteredDiskQueryParameters( getParameters().getDiskId(), getParameters().getStorageDomainId(), getStoragePoolId()) ); if (queryReturnValue.getSucceeded()) { return queryReturnValue.getReturnValue(); } log.error("Failed to find unregistered disk with the following ID '{}' in storage domain '{}'", getParameters().getDiskId(), getStorageDomain().getName()); return null; }
Source:
private com.google.longrunning.Operation snapshotTable(String snapshotName, TableName tableName) throws IOException { BigtableClusterName clusterName = this.connection.getSession().getClusterName(); BigtableInstanceName instanceName = options.getInstanceName(); BigtableTableName btTableName = instanceName.toTableName(tableName.getNameAsString()); return bigtableTableAdminClient.snapshotTable(SnapshotTableRequest.newBuilder() .setCluster(clusterName.getClusterName()) .setSnapshotId(snapshotName) .setName(btTableName.toString()) .build()); }

Target:
private Operation snapshotTable(String snapshotName, TableName tableName) throws IOException { return bigtableTableAdminClient.snapshotTable(SnapshotTableRequest.newBuilder() .setCluster(getClusterName().toString()) .setSnapshotId(snapshotName) .setName(options.getInstanceName().toTableNameStr(tableName.getNameAsString())) .build()); }
Source:
private static boolean isElementIsReferencedInScript(final Expression expr, final EObject element) { if (!expr.getReferencedElements().isEmpty()) { for (final EObject o : expr.getReferencedElements()) { if (EcoreUtil.equals(element, o)) { return true; } if (element instanceof Element && o instanceof Element && ModelHelper.isSameElement(element, o)) { return true && !ModelHelper.isReferencedElementIsInExpression(expr); } else { if (element instanceof Parameter && o instanceof Parameter && ((Parameter) element).getName().equals(((Parameter) o).getName())) { return true && !ModelHelper.isReferencedElementIsInExpression(expr); } } } } return false; }

Target:
private static boolean isElementIsReferencedInScript(final Expression expr, final EObject element) { if (!expr.getReferencedElements().isEmpty()) { for (final EObject o : expr.getReferencedElements()) { if (EcoreUtil.equals(element, o)) { return true; } if (element instanceof Element && o instanceof Element && ModelHelper.isSameElement(element, o)) { return !ModelHelper.isReferencedElementIsInExpression(expr); } else { if (element instanceof Parameter && o instanceof Parameter && ((Parameter) element).getName().equals(((Parameter) o).getName())) { return !ModelHelper.isReferencedElementIsInExpression(expr); } } } } return false; }
Source:
public Datastream get(String name) { Datastream stream = null; try { _dynamicMetricsManager.createOrUpdateMeter(CLASS_NAME, GET_CALL, 1); stream = _store.getDatastream(name); } catch (Exception e) { _dynamicMetricsManager.createOrUpdateMeter(CLASS_NAME, CALL_ERROR, 1); _errorLogger.logAndThrowRestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Get datastream failed for datastream: " + name, e); } if (stream == null) { _errorLogger.logAndThrowRestLiServiceException(HttpStatus.S_404_NOT_FOUND, "Datastream not found: " + name); } return stream; }

Target:
public Datastream get(String name) { Datastream stream = null; try { LOG.info("Get datastream called for datastream {}", name); _dynamicMetricsManager.createOrUpdateMeter(CLASS_NAME, GET_CALL, 1); stream = _store.getDatastream(name); } catch (Exception e) { _dynamicMetricsManager.createOrUpdateMeter(CLASS_NAME, CALL_ERROR, 1); _errorLogger.logAndThrowRestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Get datastream failed for datastream: " + name, e); } if (stream == null) { _errorLogger.logAndThrowRestLiServiceException(HttpStatus.S_404_NOT_FOUND, "Datastream not found: " + name); } return stream; }
Source:
public void cancelStreamedResponseTest() throws Throwable { createClientAndCancelAfterN(0); createClientAndCancelAfterN(1); createClientAndCancelAfterN(10); try (AsyncHttpClient c = asyncHttpClient()) { assertEquals(c.preparePost(getTargetUrl()).setBody("Hello").execute().get().getResponseBody(), "Hello"); } }

Target:
public void cancelStreamedResponseTest() throws Throwable { try (AsyncHttpClient c = asyncHttpClient()) { c.preparePost(getTargetUrl()).setBody(LARGE_IMAGE_BYTES).execute(new CancellingStreamedAsyncProvider(0)).get(); c.preparePost(getTargetUrl()).setBody(LARGE_IMAGE_BYTES).execute(new CancellingStreamedAsyncProvider(1)).get(); c.preparePost(getTargetUrl()).setBody(LARGE_IMAGE_BYTES).execute(new CancellingStreamedAsyncProvider(10)).get(); assertEquals(c.preparePost(getTargetUrl()).setBody("Hello").execute().get().getResponseBody(), "Hello"); } }
Source:
TestOutputTopic(final TopologyTestDriver driver, final String topicName, final Deserializer<K> keyDeserializer, final Deserializer<V> valueDeserializer) { Objects.requireNonNull(driver, "TopologyTestDriver cannot be null"); Objects.requireNonNull(topicName, "topicName cannot be null"); this.driver = driver; this.topic = topicName; this.keyDeserializer = keyDeserializer; this.valueDeserializer = valueDeserializer; }

Target:
TestOutputTopic(final TopologyTestDriver driver, final String topicName, final Deserializer<K> keyDeserializer, final Deserializer<V> valueDeserializer) { Objects.requireNonNull(driver, "TopologyTestDriver cannot be null"); Objects.requireNonNull(topicName, "topicName cannot be null"); Objects.requireNonNull(keyDeserializer, "keyDeserializer cannot be null"); Objects.requireNonNull(valueDeserializer, "valueDeserializer cannot be null"); this.driver = driver; this.topic = topicName; this.keyDeserializer = keyDeserializer; this.valueDeserializer = valueDeserializer; }
Source:
HashSet<ObjectId> listNonHEADIndexObjects() throws NoWorkTreeException, CorruptObjectException, IOException { RevWalk revWalk = null; TreeWalk treeWalk = new TreeWalk(repo); try { if (!repo.isBare()) { DirCache dc = repo.lockDirCache(); treeWalk.addTree(new DirCacheIterator(dc)); ObjectId headID = repo.resolve(Constants.HEAD); if (headID != null) { revWalk = new RevWalk(repo); treeWalk.addTree(revWalk.parseTree(headID)); revWalk.dispose(); } } treeWalk.setFilter(TreeFilter.ANY_DIFF); treeWalk.setRecursive(true); HashSet<ObjectId> ret = new HashSet<ObjectId>(); while (treeWalk.next()) { ObjectId objectId = treeWalk.getObjectId(0); if (objectId != ObjectId.zeroId()) ret.add(objectId); } return ret; } finally { if (revWalk != null) revWalk.dispose(); treeWalk.release(); } }

Target:
HashSet<ObjectId> listNonHEADIndexObjects() throws NoWorkTreeException, CorruptObjectException, IOException { RevWalk revWalk = null; DirCache dc = null; if (repo.isBare()) return ((HashSet<ObjectId>) Collections.EMPTY_SET); TreeWalk treeWalk = new TreeWalk(repo); try { dc = repo.readDirCache(); treeWalk.addTree(new DirCacheIterator(dc)); ObjectId headID = repo.resolve(Constants.HEAD); if (headID != null) { revWalk = new RevWalk(repo); treeWalk.addTree(revWalk.parseTree(headID)); revWalk.dispose(); } treeWalk.setFilter(TreeFilter.ANY_DIFF); treeWalk.setRecursive(true); HashSet<ObjectId> ret = new HashSet<ObjectId>(); while (treeWalk.next()) { ObjectId objectId = treeWalk.getObjectId(0); if (objectId != ObjectId.zeroId()) ret.add(objectId); } return ret; } finally { if (revWalk != null) revWalk.dispose(); treeWalk.release(); } }
Source:
public OptionsBuilder put(String key, Object value) { if (value != null) { options.put(key, value); } return this; }

Target:
public OptionsBuilder put(String key, Object value) { if (value != null) { options.put(key, value); } else { options.remove(key); } return this; }
Source:
private Guid getClusterId() { Guid vdsGroupId; if (Guid.Empty.equals(getParameters().getVdsGroupId())) { vdsGroupId = Guid.createGuidFromStringDefaultEmpty( Config.<String> getValue(ConfigValues.AutoRegistrationDefaultVdsGroupID)); log.debug( "RegisterVdsQuery::ExecuteCommand - VdsGroupId received as -1, using AutoRegistrationDefaultVdsGroupID: '{}'", vdsGroupId); } else { vdsGroupId = getParameters().getVdsGroupId(); } if (vdsGroupId == null || Guid.Empty.equals(vdsGroupId)) { VdsGroupDAO dao = DbFacade.getInstance().getVdsGroupDao(); VDSGroup cluster = dao.getByName("Default"); if (cluster != null) { vdsGroupId = cluster.getId(); } else { List<VDSGroup> clusters = dao.getAll(); if (clusters.size() > 0) { vdsGroupId = clusters.get(0).getId(); } } } return vdsGroupId; }

Target:
private Guid getClusterId() { Guid vdsGroupId = getParameters().getVdsGroupId(); if (Guid.Empty.equals(getParameters().getVdsGroupId())) { vdsGroupId = Guid.createGuidFromStringDefaultEmpty( Config.<String> getValue(ConfigValues.AutoRegistrationDefaultVdsGroupID)); log.debug( "RegisterVdsQuery::ExecuteCommand - VdsGroupId received as -1, using AutoRegistrationDefaultVdsGroupID: '{}'", vdsGroupId); } if (vdsGroupId == null || Guid.Empty.equals(vdsGroupId)) { VdsGroupDAO dao = DbFacade.getInstance().getVdsGroupDao(); VDSGroup cluster = dao.getByName("Default"); if (cluster != null) { vdsGroupId = cluster.getId(); } else { List<VDSGroup> clusters = dao.getAll(); if (clusters.size() > 0) { vdsGroupId = clusters.get(0).getId(); } } } return vdsGroupId; }
Source:
private void execute(List<String> xqFiles) { if (opts.restIpAddress == null) { System.out.println("No REST Ip address given. Creating a local hyracks cluster"); try { restIpAddress = startLocalHyracks(); restPort = opts.restPort; } catch (Exception e) { System.err.println("Unable to start local hyracks cluster due to: " + e.getMessage()); return; } } else { restIpAddress = opts.restIpAddress; restPort = opts.restPort; } System.out.println("Running queries given in: " + Arrays.toString(xqFiles.toArray())); runQueries(xqFiles); if (opts.restIpAddress == null) { try { stopLocalHyracks(); } catch (Exception e) { System.err.println("Error occurred when stopping local hyracks: " + e.getMessage()); } } }

Target:
private void execute(List<String> xqFiles) { if (opts.restIpAddress == null) { System.out.println("No REST Ip address given. Creating a local hyracks cluster"); VXQueryConfig vxqConfig = new VXQueryConfig(); vxqConfig.setAvailableProcessors(opts.availableProcessors); vxqConfig.setFrameSize(opts.frameSize); vxqConfig.setHdfsConf(opts.hdfsConf); vxqConfig.setJoinHashSize(opts.joinHashSize); vxqConfig.setMaximumDataSize(opts.maximumDataSize); localClusterUtil = new LocalClusterUtil(); try { localClusterUtil.init(vxqConfig); restIpAddress = localClusterUtil.getIpAddress(); restPort = localClusterUtil.getRestPort(); } catch (Exception e) { System.err.println("Unable to start local hyracks cluster due to: " + e.getMessage()); e.printStackTrace(); return; } } else { restIpAddress = opts.restIpAddress; restPort = opts.restPort; } System.out.println("Running queries given in: " + Arrays.toString(xqFiles.toArray())); runQueries(xqFiles); if (localClusterUtil != null) { try { localClusterUtil.deinit(); } catch (Exception e) { System.err.println("Error occurred when stopping local hyracks: " + e.getMessage()); } } }
Source:
private static IncrementalIndex makeIncrementalIndex( Bucket theBucket, AggregatorFactory[] aggs, HadoopDruidIndexerConfig config, Iterable<String> oldDimOrder ) { final HadoopTuningConfig tuningConfig = config.getSchema().getTuningConfig(); final IncrementalIndexSchema indexSchema = new IncrementalIndexSchema.Builder() .withMinTimestamp(theBucket.time.getMillis()) .withDimensionsSpec(config.getSchema().getDataSchema().getParser()) .withQueryGranularity(config.getSchema().getDataSchema().getGranularitySpec().getQueryGranularity()) .withMetrics(aggs) .build(); OnheapIncrementalIndex newIndex = new OnheapIncrementalIndex( indexSchema, tuningConfig.getRowFlushBoundary() ); if(oldDimOrder != null) { if (!indexSchema.getDimensionsSpec().hasCustomDimensions()) { newIndex.loadDimensionIterable(oldDimOrder); } } return newIndex; }

Target:
private static IncrementalIndex makeIncrementalIndex( Bucket theBucket, AggregatorFactory[] aggs, HadoopDruidIndexerConfig config, Iterable<String> oldDimOrder ) { final HadoopTuningConfig tuningConfig = config.getSchema().getTuningConfig(); final IncrementalIndexSchema indexSchema = new IncrementalIndexSchema.Builder() .withMinTimestamp(theBucket.time.getMillis()) .withDimensionsSpec(config.getSchema().getDataSchema().getParser()) .withQueryGranularity(config.getSchema().getDataSchema().getGranularitySpec().getQueryGranularity()) .withMetrics(aggs) .build(); OnheapIncrementalIndex newIndex = new OnheapIncrementalIndex( indexSchema, tuningConfig.getRowFlushBoundary() ); if (oldDimOrder != null && !indexSchema.getDimensionsSpec().hasCustomDimensions()) { newIndex.loadDimensionIterable(oldDimOrder); } return newIndex; }
Source:
void dragBegin(long widget, long context) { if (!OS.isX11() && this.control instanceof Text) { DNDEvent event = new DNDEvent(); event.widget = this; event.doit = true; notifyListeners(DND.DragStart, event); if (!event.doit || transferAgents == null || transferAgents.length == 0) return; if (targetList == 0) return; Image image = event.image; if (context != 0 && image != null) { if (OS.GTK3) { OS.gtk_drag_set_icon_surface(context, image.surface); } else { long pixbuf = ImageList.createPixbuf(image); OS.gtk_drag_set_icon_pixbuf(context, pixbuf, 0, 0); OS.g_object_unref(pixbuf); } } } }

Target:
void dragBegin(long widget, long context) { if (!OS.isX11() && this.control instanceof Text) { DNDEvent event = new DNDEvent(); event.widget = this; event.doit = true; notifyListeners(DND.DragStart, event); if (!event.doit || transferAgents == null || transferAgents.length == 0) return; if (targetList == 0) return; Image image = event.image; if (context != 0 && image != null) { OS.gtk_drag_set_icon_surface(context, image.surface); } } }
Source:
void maybeNotifyForBlobCreation() { if (isOperationComplete()) { boolean composite = !getSuccessfullyPutChunkIdsIfComposite().isEmpty(); if (composite) { metadataPutChunk.notifyForFirstChunkCreation(); } if (blobId != null) { notificationSystem.onBlobCreated(getBlobIdString(), getBlobProperties(), getBlobProperties().isEncrypted() ? null : getUserMetadata(), composite ? NotificationBlobType.Composite : NotificationBlobType.Simple); } } }

Target:
void maybeNotifyForBlobCreation() { if (isOperationComplete()) { boolean composite = !getSuccessfullyPutChunkIdsIfComposite().isEmpty(); if (composite) { metadataPutChunk.maybeNotifyForFirstChunkCreation(); } if (blobId != null) { notificationSystem.onBlobCreated(getBlobIdString(), getBlobProperties(), composite ? NotificationBlobType.Composite : NotificationBlobType.Simple); } } }
Source:
public static synchronized AlarmReloadManager getInstance() { if (instance == null) { instance = new AlarmReloadManager(); } UI.getDefault().addStopWaitPropertyChangeListener(instance); return instance; }

Target:
public static synchronized AlarmReloadManager getInstance() { if (instance == null) { instance = new AlarmReloadManager(); } return instance; }
Source:
@Test public void observeCreatePersistable() { TestObserver<BundleBundle> testObserver = new TestObserver<>(); RxNavi.observe(emitter, Event.CREATE_PERSISTABLE).subscribe(testObserver); testObserver.assertNoValues(); Bundle bundle = new Bundle(); PersistableBundle persistableBundle = mock(PersistableBundle.class); emitter.onCreate(bundle, persistableBundle); testObserver.dispose(); emitter.onCreate(bundle, persistableBundle); testObserver.assertValue(BundleBundle.create(bundle, persistableBundle)); testObserver.assertNotTerminated(); }

Target:
@Test public void observeCreatePersistable() { TestObserver<BundleBundle> testObserver = RxNavi.observe(emitter, Event.CREATE_PERSISTABLE).test(); testObserver.assertNoValues(); Bundle bundle = new Bundle(); PersistableBundle persistableBundle = mock(PersistableBundle.class); emitter.onCreate(bundle, persistableBundle); testObserver.dispose(); emitter.onCreate(bundle, persistableBundle); testObserver.assertValue(BundleBundle.create(bundle, persistableBundle)); testObserver.assertNotTerminated(); }