auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); preferencesManager = new PreferencesManager(this); newListInput.setHint(R.string.add_list_hint); noContent.setText(R.string.no_lists_message); plus.setImageDrawable(new IconDrawable(this, IoniconsIcons.ion_android_add).colorRes(R.color.white)); importFile.setImageDrawable(new IconDrawable( this, IoniconsIcons.ion_android_upload).colorRes(R.color.white)); nameListsAdapter = new NameListsAdapter(this,this, noContent); recyclerView.setAdapter(nameListsAdapter); if (preferencesManager.getFirstTimeUser()) { preferencesManager.setFirstTimeUser(false); new MaterialDialog.Builder(this) .title(R.string.view_tutorial) .content(R.string.tutorial_prompt) .positiveText(R.string.accept_tutorial) .negativeText(R.string.no_im_good) .onPositive((dialog, which) -> showTutorial(true)) .show(); } if (preferencesManager.rememberAppOpen() == 5) { showPleaseRateDialog(); } }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); preferencesManager = new PreferencesManager(this); plus.setImageDrawable(new IconDrawable(this, IoniconsIcons.ion_android_add).colorRes(R.color.white)); importFile.setImageDrawable(new IconDrawable( this, IoniconsIcons.ion_android_upload).colorRes(R.color.white)); nameListsAdapter = new NameListsAdapter(this, this, noContent); recyclerView.setAdapter(nameListsAdapter); if (preferencesManager.getFirstTimeUser()) { preferencesManager.setFirstTimeUser(false); new MaterialDialog.Builder(this) .title(R.string.view_tutorial) .content(R.string.tutorial_prompt) .positiveText(R.string.accept_tutorial) .negativeText(R.string.no_im_good) .onPositive((dialog, which) -> showTutorial(true)) .show(); } if (preferencesManager.rememberAppOpen() == 5) { showPleaseRateDialog(); } }
Source:
public void shouldMapListToCollection() { Source source = new Source(); source.setIntegerList( Arrays.asList( 1, 2 ).stream() ); Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source ); assertThat( target ).isNotNull(); assertThat( target.getIntegerCollection() ).containsOnly( 1, 2 ); }

Target:
public void shouldMapListToCollection() { Source source = new Source(); source.setIntegerStream( Arrays.asList( 1, 2 ).stream() ); Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source ); assertThat( target ).isNotNull(); assertThat( target.getIntegerCollection() ).containsOnly( 1, 2 ); }
Source:
public void registerContribution(Object contribution, String extensionPoint, ComponentInstance contributor) { if (extensionPoint.equals(CODEC_XP)) { CodecDescriptor descriptor = (CodecDescriptor) contribution; configs.put(descriptor.getName(), descriptor); log.debug(String.format("Register Codec contribution: %s", descriptor)); codecs.put(descriptor.getName(), descriptor.getInstance()); } }

Target:
public void registerContribution(Object contribution, String extensionPoint, ComponentInstance contributor) { if (extensionPoint.equals(CODEC_XP)) { CodecDescriptor descriptor = (CodecDescriptor) contribution; configs.put(descriptor.getName(), descriptor); log.debug(String.format("Register Codec contribution: %s", descriptor)); codecFactories.put(descriptor.getName(), descriptor.getInstance()); } }
Source:
protected void initialize(final IResource resource, final String path, final Class<? extends ITmfEvent> type) throws TmfTraceException { if (path == null) { throw new TmfTraceException("Invalid trace path"); } fPath = path; fResource = resource; String traceName = getName(); if (traceName.isEmpty()) { traceName = (resource != null) ? resource.getName() : new Path(path).lastSegment(); } if (fParser == null) { if (this instanceof ITmfEventParser) { fParser = (ITmfEventParser) this; } else { throw new TmfTraceException("Invalid trace parser"); } } super.init(traceName, type); @SuppressWarnings("null") @NonNull Class<? extends TmfTrace> className = this.getClass(); Map<String, IAnalysisModuleHelper> modules = TmfAnalysisManager.getAnalysisModules(className); for (IAnalysisModuleHelper helper : modules.values()) { try { IAnalysisModule module = helper.newModule(this); fAnalysisModules.put(module.getId(), module); } catch (TmfAnalysisException e) { Activator.logWarning("Could not initialize analysis module " + e.getMessage()); } } TmfSignalManager.registerVIP(this); if (fIndexer != null) { fIndexer.dispose(); } fIndexer = createIndexer(fCacheSize); }

Target:
protected void initialize(final IResource resource, final String path, final Class<? extends ITmfEvent> type) throws TmfTraceException { if (path == null) { throw new TmfTraceException("Invalid trace path"); } fPath = path; fResource = resource; String traceName = getName(); if (traceName.isEmpty()) { traceName = (resource != null) ? resource.getName() : new Path(path).lastSegment(); } if (fParser == null) { if (this instanceof ITmfEventParser) { fParser = (ITmfEventParser) this; } else { throw new TmfTraceException("Invalid trace parser"); } } super.init(traceName, type); Class<? extends TmfTrace> className = checkNotNull(this.getClass()); Map<String, IAnalysisModuleHelper> modules = TmfAnalysisManager.getAnalysisModules(className); for (IAnalysisModuleHelper helper : modules.values()) { try { IAnalysisModule module = helper.newModule(this); fAnalysisModules.put(module.getId(), module); } catch (TmfAnalysisException e) { Activator.logWarning("Could not initialize analysis module " + e.getMessage()); } } TmfSignalManager.registerVIP(this); if (fIndexer != null) { fIndexer.dispose(); } fIndexer = createIndexer(fCacheSize); }
Source:
CorrelationAttributeInstance( Type type, String value, int instanceId, CorrelationCase eamCase, CorrelationDataSource eamDataSource, String filePath, String comment, TskData.FileKnown knownStatus ) throws EamDbException { if (filePath == null) { throw new EamDbException("file path is null"); } if (value == null) { throw new EamDbException("md5 value is null"); } this.correlationType = type; this.correlationValue = value; this.ID = instanceId; this.correlationCase = eamCase; this.correlationDataSource = eamDataSource; this.filePath = filePath.toLowerCase(); this.comment = comment; this.knownStatus = knownStatus; }

Target:
CorrelationAttributeInstance( Type type, String value, int instanceId, CorrelationCase eamCase, CorrelationDataSource eamDataSource, String filePath, String comment, TskData.FileKnown knownStatus ) throws EamDbException { if (filePath == null) { throw new EamDbException("file path is null"); } if (value == null) { throw new EamDbException("correlation value is null"); } this.correlationType = type; this.correlationValue = value; this.ID = instanceId; this.correlationCase = eamCase; this.correlationDataSource = eamDataSource; this.filePath = filePath.toLowerCase(); this.comment = comment; this.knownStatus = knownStatus; }
Source:
public static double similarityValue(double[] referenceEIC, double[] gaussianValues, int leftBound, int rightBound) { double diffArea = 0.0; for (int j = 0; j < rightBound - leftBound; j++) { diffArea += Math.abs(0.5 * ((referenceEIC[j] - gaussianValues[j]) + (referenceEIC[j + 1] - gaussianValues[j + 1]))); } final double exponentFactor = 0.2; final double exponentShift = Math.exp(-1 / exponentFactor); final double exponentHeight = 1.0 / (1.0 - exponentShift); double curSimilarity = ((Math.exp(-diffArea / exponentFactor)) - exponentShift) * exponentHeight; return curSimilarity; }

Target:
public static double similarityValue(double[] referenceEIC, double[] gaussianValues, int leftBound, int rightBound) { double diffArea = 0.0; for (int j = 0; j < rightBound - leftBound; j++) { diffArea += Math.abs(0.5 * ((referenceEIC[j] - gaussianValues[j]) + (referenceEIC[j + 1] - gaussianValues[j + 1]))); } double curSimilarity = ((Math.exp(-diffArea / EXPONENT_FACTOR)) - EXPONENT_SHIFT) * EXPONENT_HEIGHT; return curSimilarity; }
Source:
private static <T, S> void completeAllExceptionally( Map<T, CompletableFuture<S>> futuresByValue, Queue<T> valueQueue) { runUntilEmpty(valueQueue, value -> futuresByValue.get(value).completeExceptionally( new RuntimeException("Task terminated early due to another concurrent request failing"))); }

Target:
private static <T, S> void completeAllExceptionally( Map<T, CompletableFuture<S>> futuresByValue, Queue<T> valueQueue) { runUntilEmpty(valueQueue, value -> futuresByValue.get(value).completeExceptionally(TASK_CANCELED_EXCEPTION)); }
Source:
public QueryRequest getGazetteerFilter() { return new QueryRequestImpl( new QueryImpl( filterBuilder.attribute(Core.METACARD_TAGS).like().text("gazetteer"), 1, PARTITION_SIZE, new SortByImpl(Core.ID, SortOrder.ASCENDING), true, TimeUnit.MINUTES.toMillis(3))); }

Target:
public QueryRequest getGazetteerFilter() { return new QueryRequestImpl( new QueryImpl( filterBuilder.attribute(Core.METACARD_TAGS).like().text(GAZETTEER_METACARD_TAG), 1, PARTITION_SIZE, new SortByImpl(Core.ID, SortOrder.ASCENDING), true, TimeUnit.MINUTES.toMillis(3))); }
Source:
private void performRequestedAction(){ if (mNote != null) { if (mActionType != null) { switch (mActionType) { case ARG_ACTION_LIKE: likeComment(); case ARG_ACTION_APPROVE: approveComment(); case ARG_ACTION_REPLY: replyToComment(); } } else { requestFailed(null); } } else { requestFailed(null); } }

Target:
private void performRequestedAction(){ if (mNote != null) { if (mActionType != null) { switch (mActionType) { case ARG_ACTION_LIKE: likeComment(); break; case ARG_ACTION_APPROVE: approveComment(); break; case ARG_ACTION_REPLY: replyToComment(); break; default: requestFailed(null); break; } } else { requestFailed(null); } } else { requestFailed(null); } }
Source:
public void isGreaterThan() { assertTrue(V3_0.isGreaterThan(of(2, 0))); assertFalse(V3_0.isGreaterThan(of(3, 0))); assertFalse(V3_0.isGreaterThan(of(4, 0))); assertTrue(V3_0.isGreaterThan(NEGATIVE_VERSION_1)); assertTrue(NEGATIVE_VERSION_1.isGreaterThan(NEGATIVE_VERSION_2)); }

Target:
public void isGreaterThan() throws Exception { assertTrue(V3_0.isGreaterThan(of(2, 0))); assertFalse(V3_0.isGreaterThan(of(3, 0))); assertFalse(V3_0.isGreaterThan(of(4, 0))); }
Source:
public void testGroupByLongColumnWithExFn() { String jsFn = "function(str) { return 'super-' + str; }"; ExtractionFn jsExtractionFn = new JavaScriptExtractionFn(jsFn, false, JavaScriptConfig.getDefault()); GroupByQuery query = GroupByQuery .builder() .setDataSource(QueryRunnerTestHelper.dataSource) .setQuerySegmentSpec(QueryRunnerTestHelper.firstToThird) .setDimensions(Lists.<DimensionSpec>newArrayList(new ExtractionDimensionSpec("__time", "time_alias", jsExtractionFn))) .setDimFilter(new SelectorDimFilter("quality", "entertainment", null)) .setAggregatorSpecs( Arrays.asList( QueryRunnerTestHelper.rowsCount, new LongSumAggregatorFactory("idx", "index") ) ) .setGranularity(QueryRunnerTestHelper.dayGran) .build(); List<Row> expectedResults = Arrays.asList( GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-01", "time_alias", "super-1301616000000", "rows", 1L, "idx", 158L ), GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-02", "time_alias", "super-1301702400000", "rows", 1L, "idx", 166L ) ); Iterable<Row> results = GroupByQueryRunnerTestHelper.runQuery(factory, runner, query); TestHelper.assertExpectedObjects(expectedResults, results, ""); }

Target:
public void testGroupByLongColumnWithExFn() { if (config.getDefaultStrategy().equals(GroupByStrategySelector.STRATEGY_V1)) { expectedException.expect(UnsupportedOperationException.class); expectedException.expectMessage("GroupBy v1 does not support dimension selectors with unknown cardinality."); } String jsFn = "function(str) { return 'super-' + str; }"; ExtractionFn jsExtractionFn = new JavaScriptExtractionFn(jsFn, false, JavaScriptConfig.getDefault()); GroupByQuery query = GroupByQuery .builder() .setDataSource(QueryRunnerTestHelper.dataSource) .setQuerySegmentSpec(QueryRunnerTestHelper.firstToThird) .setDimensions(Lists.<DimensionSpec>newArrayList(new ExtractionDimensionSpec("qualityLong", "ql_alias", jsExtractionFn))) .setDimFilter(new SelectorDimFilter("quality", "entertainment", null)) .setAggregatorSpecs( Arrays.asList( QueryRunnerTestHelper.rowsCount, new LongSumAggregatorFactory("idx", "index") ) ) .setGranularity(QueryRunnerTestHelper.dayGran) .build(); List<Row> expectedResults = Arrays.asList( GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-01", "ql_alias", "super-1200", "rows", 1L, "idx", 158L ), GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-02", "ql_alias", "super-1200", "rows", 1L, "idx", 166L ) ); Iterable<Row> results = GroupByQueryRunnerTestHelper.runQuery(factory, runner, query); TestHelper.assertExpectedObjects(expectedResults, results, ""); }
Source:
private void notifyListeners(Repository repository, IndexDiffData indexDiffData) { IndexDiffChangedListener[] tmpListeners; synchronized (listeners) { tmpListeners = listeners .toArray(new IndexDiffChangedListener[0]); } for (int i = 0; i < tmpListeners.length; i++) { try { tmpListeners[i].indexDiffChanged(repository, indexDiffData); } catch (RuntimeException e) { Activator.logError( "Exception occurred in an IndexDiffChangedListener", e); } } }

Target:
private void notifyListeners(Repository repository, IndexDiffData indexDiffData) { for (IndexDiffChangedListener listener : listeners) { SafeRunner.run(new ISafeRunnable() { @Override public void run() throws Exception { listener.indexDiffChanged(repository, indexDiffData); } @Override public void handleException(Throwable exception) { } }); } }
Source:
public void testThatTaskKillerInterruptsThreadImmediatelyWhenSetToNegativeNumber() { KilledThread testThreadToBeInterrupted = new KilledThread(); testThreadToBeInterrupted.start(); System.setProperty(this.taskKillerCleanupTimePropertyName, "-20"); TaskKiller taskKiller = new TaskKiller(testThreadToBeInterrupted); assertThat("Task Killer must not interrupt thread before kill() is called", testThreadToBeInterrupted.isInterruptedOnce, is(false)); assertThat("Task Killer must not interrupt thread before kill() is called", testThreadToBeInterrupted.isInterruptedMoreThanOnce, is(false)); startKilling(taskKiller); waitOrFailTest(100); assertThat("Task Killer must must interrupt once if kill() is called and then wait for the timeout which is set to 10 seconds.", testThreadToBeInterrupted.isInterruptedOnce, is(true)); assertThat("Task Killer must only interrupt once (not twice) after kill() is called and then wait for the timeout which is set to 10 seconds.", testThreadToBeInterrupted.isInterruptedMoreThanOnce, is(true)); System.clearProperty(this.taskKillerCleanupTimePropertyName); }

Target:
public void testThatTaskKillerInterruptsThreadImmediatelyWhenSetToNegativeNumber() { KilledThread testThreadToBeInterrupted = new KilledThread(); testThreadToBeInterrupted.start(); System.setProperty(this.taskKillerCleanupTimePropertyName, "-20"); TaskKiller taskKiller = new TaskKiller(testThreadToBeInterrupted); assertThat("Task Killer must not interrupt thread before kill() is called", testThreadToBeInterrupted.isInterruptedOnce, is(false)); assertThat("Task Killer must not interrupt thread before kill() is called", testThreadToBeInterrupted.isInterruptedMoreThanOnce, is(false)); startKilling(taskKiller); waitOrFailTest(100); assertThat("Task Killer must interrupt once if kill() is called and then wait for the timeout which is set to 10 seconds.", testThreadToBeInterrupted.isInterruptedOnce, is(true)); assertThat("Task Killer must only interrupt once (not twice) after kill() is called and then wait for the timeout which is set to 10 seconds.", testThreadToBeInterrupted.isInterruptedMoreThanOnce, is(true)); System.clearProperty(this.taskKillerCleanupTimePropertyName); }
Source:
public ClassicUpload(String bucket, @Nullable UploadModule module, String pattern, String metadata, @Deprecated @Nullable String bucketNameWithVars, @Deprecated @Nullable String sourceGlobWithVars) { super(Objects.firstNonNull(bucket, bucketNameWithVars), module); this.sourceGlobWithVars = Objects.firstNonNull(pattern, sourceGlobWithVars); this.metadata = Objects.firstNonNull(metadata, sourceGlobWithVars); }

Target:
public ClassicUpload(String bucket, @Nullable UploadModule module, String pattern, String metadata, @Deprecated @Nullable String bucketNameWithVars, @Deprecated @Nullable String sourceGlobWithVars) { super(firstNonNull(bucket, bucketNameWithVars), module); this.sourceGlobWithVars = firstNonNull(pattern, sourceGlobWithVars); this.metadata = metadata; }
Source:
public void shutdown() { forkJoinPool.shutdownNow(); }

Target:
public void shutdown() { forkJoinPool.shutdownNow(); try { forkJoinPool.awaitTermination(60, TimeUnit.SECONDS); } catch (Exception e) { LOG.error("Unexpected exception occurred during shutdown of " + "RatisPipelineProvider", e); } }
Source:
protected int getExpectedNumEntries() { return getNumEntries() * (backupValueGenerator != null ? backupCacheInstances.length + 1 : 1); }

Target:
protected int getExpectedNumEntries() { return getNumEntries() * (backupCacheInstances != null ? backupCacheInstances.length + 1 : 1); }
Source:
public ValueMatcher makeValueMatcher(String dimension, final Comparable value) { final DimensionSelector selector = cursor.makeDimensionSelector( new DefaultDimensionSpec(dimension, dimension) ); final boolean matchNull = isComparableNullOrEmpty(value); final int id = selector.lookupId((String) value); if (id < 0) { return new BooleanValueMatcher(false); } else { return new ValueMatcher() { @Override public boolean matches() { IndexedInts row = selector.getRow(); if(row.size() == 0) { return matchNull; } for (int rowVal : row) { if (rowVal == id) { return true; } } return false; } }; } }

Target:
public ValueMatcher makeValueMatcher(String dimension, final Comparable value) { final DimensionSelector selector = cursor.makeDimensionSelector( new DefaultDimensionSpec(dimension, dimension) ); final boolean matchNull = isComparableNullOrEmpty(value); final int id = selector.lookupId((String) value); if (id < 0) { return new BooleanValueMatcher(false); } else { return new ValueMatcher() { @Override public boolean matches() { IndexedInts row = selector.getRow(); if (row.size() == 0) { return matchNull; } for (int i = 0; i < row.size(); i++) { if (row.get(i) == id) { return true; } } return false; } }; } }
Source:
protected void render0(FunctionRenderContext context) { context.addChunk("jsonb_set("); context.addArgument(0); context.addChunk("::jsonb,"); context.addChunk("'{"); addUnquotedArgument(context, 2); for (int i = 3; i < context.getArgumentsSize(); i++) { context.addChunk(","); addUnquotedArgument(context, i); } context.addChunk("}',"); context.addArgument(1); context.addChunk(")"); }

Target:
protected void render0(FunctionRenderContext context) { context.addChunk("jsonb_set(cast("); context.addArgument(0); context.addChunk(" as jsonb),"); context.addChunk("'{"); addUnquotedArgument(context, 2); for (int i = 3; i < context.getArgumentsSize(); i++) { context.addChunk(","); addUnquotedArgument(context, i); } context.addChunk("}',"); context.addArgument(1); context.addChunk(")"); }
Source:
private static @BinaryName String basenamePart(@BinaryName String className) { int lastdot = className.lastIndexOf('.'); return (lastdot == -1) ? className : className.substring(lastdot + 1); }

Target:
private static @BinaryName String basenamePart(@BinaryName String className) { int lastdot = className.lastIndexOf('.'); return className.substring(lastdot + 1); }
Source:
public String render(Number number) { if (number != null) { NumberFormat format = NumberFormat.getDecimalFormat(); return format.format(number); } else { return null; } }

Target:
public String render(Number number) { if (number != null) { NumberFormat format = NumberFormat.getDecimalFormat(); return format.format(number); } else { return ""; } }
Source:
public void onClick(View v) { if (v == mCancelBtn) { finish(); } else if (v == mChooseBtn) { Intent i = getIntent(); OCFile targetFile = (OCFile) i.getParcelableExtra(FolderPickerActivity.EXTRA_TARGET_FILE); Intent data = new Intent(); data.putExtra(EXTRA_CURRENT_FOLDER, getCurrentFolder()); data.putExtra(EXTRA_TARGET_FILE, targetFile); setResult(RESULT_OK, data); finish(); } }

Target:
public void onClick(View v) { if (v == mCancelBtn) { finish(); } else if (v == mChooseBtn) { Intent i = getIntent(); Parcelable targetFile = i.getParcelableExtra(FolderPickerActivity.EXTRA_FILE); Intent data = new Intent(); data.putExtra(EXTRA_FOLDER, getCurrentFolder()); if (targetFile != null) { data.putExtra(EXTRA_FILE, targetFile); } setResult(RESULT_OK, data); finish(); } }
Source:
private boolean shouldCancelBecauseOfRunningLaunches() { if (mode == MODE_CHECKOUT) return false; final IPreferenceStore store = Activator.getDefault().getPreferenceStore(); if (!store .getBoolean(UIPreferences.SHOW_RUNNING_LAUNCH_ON_CHECKOUT_WARNING)) return false; final ILaunchConfiguration launchConfiguration = getRunningLaunchConfiguration(); if (launchConfiguration != null) { final Boolean[] dialogResult = new Boolean[1]; PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { dialogResult[0] = showContinueDialogInUI(store, launchConfiguration); } }); return dialogResult[0].booleanValue(); } return false; }

Target:
private boolean shouldCancelBecauseOfRunningLaunches() { if (mode == MODE_CHECKOUT) return false; final IPreferenceStore store = Activator.getDefault().getPreferenceStore(); if (!store .getBoolean(UIPreferences.SHOW_RUNNING_LAUNCH_ON_CHECKOUT_WARNING)) return false; final ILaunchConfiguration launchConfiguration = getRunningLaunchConfiguration(); if (launchConfiguration != null) { final boolean[] dialogResult = new boolean[1]; PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { dialogResult[0] = showContinueDialogInUI(store, launchConfiguration); } }); return dialogResult[0]; } return false; }
Source:
public void removeType( final String typeName ) { final Short adapterId = internalAdapterStore.getAdapterId(typeName); if (adapterId != -1) { final AdapterToIndexMapping mapping = indexMappingStore.getIndicesForAdapter(adapterId); final String[] indexNames = mapping.getIndexNames(); for (int i = 0; i < indexNames.length; i++) { baseOperations.deleteAll( indexNames[i], "", adapterId); } statisticsStore.removeAllStatistics(adapterId); indexMappingStore.remove(adapterId); internalAdapterStore.remove(adapterId); adapterStore.removeAdapter(adapterId); } }

Target:
public void removeType( final String typeName ) { final Short adapterId = internalAdapterStore.getAdapterId(typeName); if (adapterId != -1) { final AdapterToIndexMapping mapping = indexMappingStore.getIndicesForAdapter(adapterId); final String[] indexNames = mapping.getIndexNames(); for (int i = 0; i < indexNames.length; i++) { baseOperations.deleteAll( indexNames[i], typeName, adapterId); } statisticsStore.removeAllStatistics(adapterId); indexMappingStore.remove(adapterId); internalAdapterStore.remove(adapterId); adapterStore.removeAdapter(adapterId); } }
Source:
public Pair<Boolean, Guid> getSelectedLease() { boolean haveLeases = getSnapshots().getItems() .stream() .anyMatch(model -> model.getLease() != null); SnapshotModel selectedLeaseSnapshotModel = getSnapshots().getItems() .stream() .filter(model -> model.getLease() != null) .filter(model -> model.getLease().getEntity()) .findFirst() .orElse(null); if (selectedLeaseSnapshotModel == null && haveLeases) { return new Pair<>(false, null); } return selectedLeaseSnapshotModel == null ? new Pair<>(true, null) : new Pair<>(true, getSnapshotLeaseDomainsMap().get(selectedLeaseSnapshotModel.getEntity().getId())); }

Target:
public Guid getSelectedLease() { SnapshotModel selectedLeaseSnapshotModel = getSnapshots().getItems() .stream() .filter(model -> model.getLease() != null) .filter(model -> model.getLease().getEntity()) .findFirst() .orElse(null); return selectedLeaseSnapshotModel != null ? getSnapshotLeaseDomainsMap().get(selectedLeaseSnapshotModel.getEntity().getId()) : null; }
Source:
protected Collection<String> getInAppFrames(Dsn dsn) { Collection<String> inAppFrames = super.getInAppFrames(dsn); if (inAppFrames.isEmpty()) { PackageInfo info = null; try { info = this.ctx.getPackageManager().getPackageInfo(this.ctx.getPackageName(), 0); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Error getting package information.", e); } if (info != null && !Util.isNullOrEmpty(info.packageName)) { List<String> newPackages = new ArrayList<>(1); newPackages.add(info.packageName); return newPackages; } } return inAppFrames; }

Target:
protected Collection<String> getInAppFrames(Dsn dsn) { Collection<String> inAppFrames = super.getInAppFrames(dsn); if (inAppFrames.isEmpty()) { PackageInfo info = null; try { info = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Error getting package information.", e); } if (info != null && !Util.isNullOrEmpty(info.packageName)) { List<String> newPackages = new ArrayList<>(1); newPackages.add(info.packageName); return newPackages; } } return inAppFrames; }
Source:
public void getRequiredMemberResourceGroupAttributesFromOneServiceWorkWithUser() throws Exception { System.out.println(CLASS_NAME + "getRequiredMemberResourceGroupAttributesFromOneServiceWorkWithUser"); vo = setUpVo(); member = setUpMember(); group = setUpGroup(); facility = setUpFacility(); resource = setUpResource(); service = setUpService(); attributes = setUpRequiredAttributes(); perun.getResourcesManager().assignService(sess, resource, service); List<Attribute> reqAttr = attributesManager.getRequiredAttributes(sess, service, resource, group, member, true); assertNotNull("unable to get required resource-member attributes for one service",reqAttr); assertTrue("should have at least 5 req attribute",reqAttr.size() >= 5); }

Target:
public void getRequiredMemberResourceGroupAttributesFromOneServiceWorkWithUser() throws Exception { System.out.println(CLASS_NAME + "getRequiredMemberResourceGroupAttributesFromOneServiceWorkWithUser"); vo = setUpVo(); member = setUpMember(); group = setUpGroup(); facility = setUpFacility(); resource = setUpResource(); service = setUpService(); attributes = setUpRequiredAttributes(); perun.getResourcesManager().assignService(sess, resource, service); List<Attribute> reqAttr = attributesManager.getRequiredAttributes(sess, service, resource, group, member, true); assertNotNull("unable to get required attributes for one service",reqAttr); assertTrue("should have at least 5 req attributes",reqAttr.size() >= 5); }
Source:
protected boolean isMigrationNeeded(Key<Instructor> key) throws Exception { Instructor instructor = ofy().load().key(key).now(); if (!SanitizationHelper.sanitizeForHtml(instructor.getName()).equals(instructor.getName())) { System.err.println(String.format("Instructor %s has unsanitized name %s, this should not happen", instructor.getUniqueId(), instructor.getName())); } return SanitizationHelper.isSanitizedHtml(instructor.getName()); }

Target:
protected boolean isMigrationNeeded(Key<Instructor> key) throws Exception { Instructor instructor = ofy().load().key(key).now(); return SanitizationHelper.isSanitizedHtml(instructor.getName()); }
Source:
protected Type union(Type toMerge, boolean strict) { if (!toMerge.isPrimitive()) { reportSchemaMergeError(toMerge); } if (strict) { if (!primitive.equals(toMerge.asPrimitiveType().getPrimitiveTypeName())) { reportSchemaMergeError(toMerge); } if (getOriginalType() == null && toMerge.getOriginalType() != null || getOriginalType() != null && !getOriginalType().equals(toMerge.getOriginalType())) { reportSchemaMergeError(toMerge); } int toMergeLength = toMerge.asPrimitiveType().getTypeLength(); if (primitive == PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY && length != toMergeLength) { reportSchemaMergeError(toMerge); } } Types.PrimitiveBuilder<PrimitiveType> builder = Types.primitive(primitive, toMerge.getRepetition()); if (PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY == primitive) { builder.length(length); } return builder.as(getOriginalType()).named(getName()); }

Target:
protected Type union(Type toMerge, boolean strict) { if (!toMerge.isPrimitive()) { reportSchemaMergeError(toMerge); } if (strict) { if (!primitive.equals(toMerge.asPrimitiveType().getPrimitiveTypeName()) || getOriginalType() != toMerge.getOriginalType()) { reportSchemaMergeError(toMerge); } int toMergeLength = toMerge.asPrimitiveType().getTypeLength(); if (primitive == PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY && length != toMergeLength) { reportSchemaMergeError(toMerge); } } Types.PrimitiveBuilder<PrimitiveType> builder = Types.primitive(primitive, toMerge.getRepetition()); if (PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY == primitive) { builder.length(length); } return builder.as(getOriginalType()).named(getName()); }
Source:
private static int getGapForNextGridStep(int currentCoordinate, int gridSpacing, int levelToPass) { int gap = ((currentCoordinate + gridSpacing) % gridSpacing); if (gap >= 0) { gap = gridSpacing - gap; } if (levelToPass != Integer.MIN_VALUE && currentCoordinate + gap < levelToPass) { return gap + getGapForNextGridStep(currentCoordinate + gap, gridSpacing, levelToPass); } return gap; }

Target:
private static int getGapForNextGridStep(int currentCoordinate, int gridSpacing, int levelToPass) { int gap = Math.abs(((currentCoordinate + gridSpacing) % gridSpacing)); if (gap >= 0) { gap = gridSpacing - gap; } if (levelToPass != Integer.MIN_VALUE && currentCoordinate + gap < levelToPass) { return gap + getGapForNextGridStep(currentCoordinate + gap, gridSpacing, levelToPass); } return gap; }
Source:
private void addAuthorities(String[] params, Set<GrantedAuthority> authorities, String root, String filter, String authorityPrefix, boolean hierarchical, int level) { String formattedFilter = MessageFormat.format(filter, params); List ldapAuthorities = ldapTemplate.search(root, formattedFilter, new AbstractContextMapper() { @Override protected Object doMapFromContext(DirContextOperations ctx) { return new Authority(ctx.getStringAttribute(groupRoleAttribute), ctx.getNameInNamespace()); } }); if (logger.isDebugEnabled()) { logger.debug("Authorities from search: " + ldapAuthorities); } for (Object authority : ldapAuthorities) { Authority ldapAuthority = (Authority)authority; addAuthority(authorities, authorityPrefix, ldapAuthority.getName()); if (hierarchical && level < maxLevelGroupsSearch) { String[] searchParams = new String[] {ldapAuthority.getDn(), ldapAuthority.getName()}; addAuthorities(searchParams, authorities, root, groupInGroupSearchFilter, authorityPrefix, hierarchical, level + 1); } } }

Target:
private void addAuthorities(String[] params, Set<GrantedAuthority> authorities, String root, String filter, String authorityPrefix, boolean hierarchical, int level) { String formattedFilter = MessageFormat.format(filter, params); List ldapAuthorities = ldapTemplate.search(root, formattedFilter, new AbstractContextMapper() { @Override protected Object doMapFromContext(DirContextOperations ctx) { return new Authority(ctx.getStringAttribute(groupRoleAttribute), ctx.getNameInNamespace()); } }); if (logger.isDebugEnabled()) { logger.debug("Authorities from search: " + ldapAuthorities); } for (Object authority : ldapAuthorities) { Authority ldapAuthority = (Authority)authority; boolean added = addAuthority(authorities, authorityPrefix, ldapAuthority.getName()); if (added && hierarchical && level < maxLevelGroupsSearch) { String[] searchParams = new String[] {ldapAuthority.getDn(), ldapAuthority.getName()}; addAuthorities(searchParams, authorities, root, groupInGroupSearchFilter, authorityPrefix, hierarchical, level + 1); } } }
Source:
public static ICalendar createIcalEventList(List<Event> events){ ICalendar iCal = new ICalendar(); events.forEach(event -> {iCal.addEvent(createICalEvent(event));}); iCal.addName("CH Event Calendar"); iCal.setColor("turquoise"); return iCal; }

Target:
public static ICalendar createIcalEventList(List<Event> events){ ICalendar iCal = new ICalendar(); events.forEach(event -> iCal.addEvent(createICalEvent(event))); iCal.addName("CH Event Calendar"); return iCal; }
Source:
public void process() { if (renderingConfig.isBloom()) { PerformanceMonitor.startActivity("rendering/bloompasses"); sceneBloom0 = frameBuffersManager.getFBO("sceneBloom0"); sceneBloom1 = frameBuffersManager.getFBO("sceneBloom1"); sceneBloom2 = frameBuffersManager.getFBO("sceneBloom2"); sceneHighPass = frameBuffersManager.getFBO("sceneHighPass"); sceneOpaque = frameBuffersManager.getFBO("sceneOpaque"); generateHighPass(); generateBloom(sceneBloom0); generateBloom(sceneBloom1); generateBloom(sceneBloom2); PerformanceMonitor.endActivity(); } }

Target:
public void process() { if (renderingConfig.isBloom()) { PerformanceMonitor.startActivity("rendering/bloomPasses"); sceneBloom0 = frameBuffersManager.getFBO("sceneBloom0"); sceneBloom1 = frameBuffersManager.getFBO("sceneBloom1"); sceneBloom2 = frameBuffersManager.getFBO("sceneBloom2"); sceneHighPass = frameBuffersManager.getFBO("sceneHighPass"); sceneOpaque = frameBuffersManager.getFBO("sceneOpaque"); generateHighPass(); generateBloom(sceneBloom0); generateBloom(sceneBloom1); generateBloom(sceneBloom2); PerformanceMonitor.endActivity(); } }
Source:
public void tearDown(ITestDevice device, IBuildInfo buildInfo, Throwable e) { File reportFile = buildInfo.getFile(TEST_PLAN_REPORT_FILE); String repotFilePath = reportFile.getAbsolutePath(); try (BufferedReader br = new BufferedReader(new FileReader(repotFilePath))) { DashboardPostMessage postMessage = new DashboardPostMessage(); String currentLine; while ((currentLine = br.readLine()) != null) { String[] splited = currentLine.split("\\s+"); if (splited.length != 2) { CLog.e(String.format("Invalid keys %s", currentLine)); continue; } TestPlanReportMessage testPlanMessage = new TestPlanReportMessage(); testPlanMessage.addTestModuleName(splited[0]); testPlanMessage.addTestModuleStartTimestamp(Long.parseLong(splited[1])); postMessage.addTestPlanReport(testPlanMessage); } Upload(postMessage); } catch (IOException ex) { CLog.d(String.format("Can't read the test plan result file %s", repotFilePath)); return; } }

Target:
public void tearDown(ITestDevice device, IBuildInfo buildInfo, Throwable e) { File reportFile = buildInfo.getFile(TEST_PLAN_REPORT_FILE); String repotFilePath = reportFile.getAbsolutePath(); try (BufferedReader br = new BufferedReader(new FileReader(repotFilePath))) { DashboardPostMessage postMessage = new DashboardPostMessage(); String currentLine; while ((currentLine = br.readLine()) != null) { String[] lineWords = currentLine.split("\\s+"); if (lineWords.length != 2) { CLog.e(String.format("Invalid keys %s", currentLine)); continue; } TestPlanReportMessage testPlanMessage = new TestPlanReportMessage(); testPlanMessage.addTestModuleName(lineWords[0]); testPlanMessage.addTestModuleStartTimestamp(Long.parseLong(lineWords[1])); postMessage.addTestPlanReport(testPlanMessage); } Upload(postMessage); } catch (IOException ex) { CLog.d(String.format("Can't read the test plan result file %s", repotFilePath)); return; } }
Source:
public void detectCorruptionIfLearnedValueIsNotTheGreatestAcceptedValue() { helper.writeLogsOnDefaultLocalAndRemote(1, 10); helper.induceGreaterAcceptedValueCorruptionOnDefaultLocalServer(5); List<CompletePaxosHistoryForNamespaceAndUseCase> historyForAll = helper.getHistory(); assertThat(HistoryAnalyzer.divergedLearners(Iterables.getOnlyElement(historyForAll))) .isEqualTo(CorruptionCheckViolation.NONE); assertThat(HistoryAnalyzer.learnedValueWithoutQuorum(Iterables.getOnlyElement(historyForAll))) .isEqualTo(CorruptionCheckViolation.NONE); assertThat(HistoryAnalyzer.greatestAcceptedValueNotLearned(Iterables.getOnlyElement(historyForAll))) .isEqualTo(CorruptionCheckViolation.ACCEPTED_VALUE_GREATER_THAN_LEARNED); helper.assertViolationDetected(CorruptionCheckViolation.ACCEPTED_VALUE_GREATER_THAN_LEARNED); }

Target:
public void detectCorruptionIfLearnedValueIsNotTheGreatestAcceptedValue() { helper.writeLogsOnDefaultLocalAndRemote(9, 453); helper.induceGreaterAcceptedValueCorruptionOnDefaultLocalServer(432); List<CompletePaxosHistoryForNamespaceAndUseCase> historyForAll = helper.getHistory(); assertThat(HistoryAnalyzer.divergedLearners(Iterables.getOnlyElement(historyForAll))) .isEqualTo(CorruptionCheckViolation.NONE); assertThat(HistoryAnalyzer.learnedValueWithoutQuorum(Iterables.getOnlyElement(historyForAll))) .isEqualTo(CorruptionCheckViolation.NONE); assertThat(HistoryAnalyzer.greatestAcceptedValueNotLearned(Iterables.getOnlyElement(historyForAll))) .isEqualTo(CorruptionCheckViolation.ACCEPTED_VALUE_GREATER_THAN_LEARNED); helper.assertViolationDetected(CorruptionCheckViolation.ACCEPTED_VALUE_GREATER_THAN_LEARNED); }
Source:
public void testInterrupt() throws Exception { Pipelining<String> pipelining = new Pipelining<String>(1); pipelining.add(mock(ICompletableFuture.class)); TestThread t = new TestThread() { @Override public void doRun() throws Throwable { pipelining.add(mock(ICompletableFuture.class)); } }; t.start(); t.interrupt(); t.assertFailsEventually(InterruptedException.class); }

Target:
public void testInterrupt() throws Exception { final Pipelining<String> pipelining = new Pipelining<String>(1); pipelining.add(mock(ICompletableFuture.class)); TestThread t = new TestThread() { @Override public void doRun() throws Throwable { pipelining.add(mock(ICompletableFuture.class)); } }; t.start(); t.interrupt(); t.assertFailsEventually(InterruptedException.class); }
Source:
protected Spreadsheet buildIndividualCandidacyReport(final Spreadsheet spreadsheet, final IndividualCandidacyProcess individualCandidacyProcess) { DegreeChangeIndividualCandidacyProcess degreeChangeIndividualCandidacyProcess = (DegreeChangeIndividualCandidacyProcess) individualCandidacyProcess; final Row row = spreadsheet.addRow(); row.setCell(degreeChangeIndividualCandidacyProcess.getProcessCode()); row.setCell(degreeChangeIndividualCandidacyProcess.getPersonalDetails().getName()); row.setCell(degreeChangeIndividualCandidacyProcess.getPersonalDetails().getIdDocumentType().getLocalizedName()); row.setCell(degreeChangeIndividualCandidacyProcess.getPersonalDetails().getDocumentIdNumber()); if (degreeChangeIndividualCandidacyProcess.getPersonalDetails().getCountry().getCountryNationality().getContent() != null) row.setCell(degreeChangeIndividualCandidacyProcess.getPersonalDetails().getCountry().getCountryNationality().getContent()); else row.setCell("-"); row.setCell(degreeChangeIndividualCandidacyProcess.getPrecedentDegreeInformation().getPrecedentInstitution().getName()); row.setCell(degreeChangeIndividualCandidacyProcess.getPrecedentDegreeInformation().getPrecedentDegreeDesignation()); row.setCell(degreeChangeIndividualCandidacyProcess.getCandidacy().getSelectedDegree().getName()); row.setCell(BundleUtil.getString(Bundle.ENUMERATION, individualCandidacyProcess.getCandidacyState().getQualifiedName())); row.setCell(BundleUtil.getString(Bundle.CANDIDATE, degreeChangeIndividualCandidacyProcess.getProcessChecked() != null && degreeChangeIndividualCandidacyProcess.getProcessChecked() ? MESSAGE_YES : MESSAGE_NO)); return spreadsheet; }

Target:
protected Spreadsheet buildIndividualCandidacyReport(final Spreadsheet spreadsheet, final IndividualCandidacyProcess individualCandidacyProcess) { DegreeChangeIndividualCandidacyProcess degreeChangeIndividualCandidacyProcess = (DegreeChangeIndividualCandidacyProcess) individualCandidacyProcess; final Row row = spreadsheet.addRow(); row.setCell(degreeChangeIndividualCandidacyProcess.getProcessCode()); row.setCell(degreeChangeIndividualCandidacyProcess.getPersonalDetails().getName()); row.setCell(degreeChangeIndividualCandidacyProcess.getPersonalDetails().getIdDocumentType().getLocalizedName()); row.setCell(degreeChangeIndividualCandidacyProcess.getPersonalDetails().getDocumentIdNumber()); row.setCell(degreeChangeIndividualCandidacyProcess.getPersonalDetails().getCountry().getCountryNationality().getContent()); row.setCell(degreeChangeIndividualCandidacyProcess.getPrecedentDegreeInformation().getPrecedentInstitution().getName()); row.setCell(degreeChangeIndividualCandidacyProcess.getPrecedentDegreeInformation().getPrecedentDegreeDesignation()); row.setCell(degreeChangeIndividualCandidacyProcess.getCandidacy().getSelectedDegree().getName()); row.setCell(BundleUtil.getString(Bundle.ENUMERATION, individualCandidacyProcess.getCandidacyState().getQualifiedName())); row.setCell(BundleUtil.getString(Bundle.CANDIDATE, degreeChangeIndividualCandidacyProcess.getProcessChecked() != null && degreeChangeIndividualCandidacyProcess.getProcessChecked() ? MESSAGE_YES : MESSAGE_NO)); return spreadsheet; }
Source:
public void testShowErrorAndRejectWithRejection() { persistencePresenter.showErrorAndReject("Test message").then(i -> { Assert.fail("Promise should've not been resolved!"); return promises.resolve(); }).catch_(e -> { verify(view).showError(eq("Test message")); Assert.assertEquals(e, persistencePresenter); return promises.resolve(); }); }

Target:
public void testShowErrorAndRejectWithRejection() { showErrorAndRejectFn(persistencePresenter.showErrorAndReject("Test message")); }
Source:
public static double[] nearestNeighborUniform1DInterpolate(@Nonnull final double[] data, final int newLength) throws IllegalArgumentException { if (data.length == 0) throw new IllegalArgumentException("The input array is empty."); ParamUtils.isPositive(newLength - 1, "The new length of the array must be >= 2"); final double fact = (double)(data.length - 1)/(newLength - 1); return IntStream.range(0, newLength).mapToDouble(i -> data[(int) FastMath.floor(i*fact + 0.5)]).toArray(); }

Target:
public static double[] nearestNeighborUniform1DInterpolate(@Nonnull final double[] data, final int newLength) throws IllegalArgumentException { Utils.validateArg(data.length > 0, "The input array is empty."); Utils.validateArg(newLength >= 2, "The new length of the array must be >= 2"); final double fact = (double)(data.length - 1)/(newLength - 1); return IntStream.range(0, newLength).mapToDouble(i -> data[(int) FastMath.floor(i*fact + 0.5)]).toArray(); }
Source:
public void testIllegalImageReturnedByQuery() throws Exception { GetVmConfigurationBySnapshotQuery<GetVmConfigurationBySnapshotQueryParams> executeQuery = setupQueryBySnapshotId(existingSnapshotId); existingVm.getDiskMap().put(existingDiskImage.getinternal_drive_mapping(), existingDiskImage); existingVm.getImages().add(existingDiskImage); doReturn(existingVm).when(executeQuery).getVmFromConfiguration(anyString()); executeQuery.Execute(); VdcQueryReturnValue returnValue = executeQuery.getQueryReturnValue(); assertNotNull("Return value from query cannot be null", returnValue); VM vm = (VM) returnValue.getReturnValue(); for (DiskImage diskImage : vm.getDiskMap().values()) { assertEquals(diskImage.getimageStatus(), ImageStatus.ILLEGAL); } }

Target:
public void testIllegalImageReturnedByQuery() throws Exception { GetVmConfigurationBySnapshotQuery<GetVmConfigurationBySnapshotQueryParams> query = setupQueryBySnapshotId(existingSnapshotId); existingVm.getDiskMap().put(existingDiskImage.getinternal_drive_mapping(), existingDiskImage); existingVm.getImages().add(existingDiskImage); doReturn(existingVm).when(query).getVmFromConfiguration(anyString()); query.Execute(); VdcQueryReturnValue returnValue = query.getQueryReturnValue(); assertNotNull("Return value from query cannot be null", returnValue); VM vm = (VM) returnValue.getReturnValue(); for (DiskImage diskImage : vm.getDiskMap().values()) { assertEquals(diskImage.getimageStatus(), ImageStatus.ILLEGAL); } }
Source:
private void doMain() throws Exception { start(); while (true) { try { Thread.sleep(5); } catch (Exception e) { log.info("shutting down", e); break; } } unregisterMBeans(); }

Target:
private void doMain() throws Exception { this.start(); while (true) { try { Thread.sleep(5); } catch (Exception e) { log.info("shutting down", e); break; } } this.unregisterMBeans(); }
Source:
public void hashRow(DimensionSelector dimSelector, Hasher hasher) { final IndexedInts row = dimSelector.getRow(); final int size = row.size(); if (size == 1) { final String value = dimSelector.lookupName(row.get(0)); if (NullHandling.replaceWithDefault() || value != null) { hasher.putUnencodedChars(nullToSpecial(value)); } } else if (size != 0) { boolean hasNonNullValue = false; final String[] values = new String[size]; for (int i = 0; i < size; ++i) { final String value = dimSelector.lookupName(row.get(i)); if (!NullHandling.replaceWithDefault() && !hasNonNullValue && value != null) { hasNonNullValue = true; } values[i] = nullToSpecial(value); } if (NullHandling.replaceWithDefault() || hasNonNullValue) { Arrays.sort(values); for (int i = 0; i < size; ++i) { if (i != 0) { hasher.putChar(CARDINALITY_AGG_SEPARATOR); } hasher.putUnencodedChars(values[i]); } } } }

Target:
public void hashRow(DimensionSelector dimSelector, Hasher hasher) { final IndexedInts row = dimSelector.getRow(); final int size = row.size(); if (size == 1) { final String value = dimSelector.lookupName(row.get(0)); if (NullHandling.replaceWithDefault() || value != null) { hasher.putUnencodedChars(nullToSpecial(value)); } } else if (size != 0) { boolean hasNonNullValue = false; final String[] values = new String[size]; for (int i = 0; i < size; ++i) { final String value = dimSelector.lookupName(row.get(i)); if (NullHandling.sqlCompatible() && !hasNonNullValue && value != null) { hasNonNullValue = true; } values[i] = nullToSpecial(value); } if (NullHandling.replaceWithDefault() || hasNonNullValue) { Arrays.sort(values); for (int i = 0; i < size; ++i) { if (i != 0) { hasher.putChar(CARDINALITY_AGG_SEPARATOR); } hasher.putUnencodedChars(values[i]); } } } }
Source:
public void shouldWrapExceptionIntoStorIOExceptionCompletable() { final StorIOSQLite storIOSQLite = mock(StorIOSQLite.class); final StorIOSQLite.Internal internal = mock(StorIOSQLite.Internal.class); when(storIOSQLite.lowLevel()).thenReturn(internal); final DeleteResolver<DeleteQuery> deleteResolver = mock(DeleteResolver.class); when(deleteResolver.performDelete(same(storIOSQLite), any(DeleteQuery.class))) .thenThrow(new IllegalStateException("test exception")); final TestSubscriber<DeleteResult> testSubscriber = new TestSubscriber<DeleteResult>(); new PreparedDeleteByQuery.Builder(storIOSQLite, DeleteQuery.builder().table("test_table").build()) .withDeleteResolver(deleteResolver) .prepare() .asRxComleatable() .subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); testSubscriber.assertNoValues(); testSubscriber.assertError(StorIOException.class); StorIOException expected = (StorIOException) testSubscriber.getOnErrorEvents().get(0); IllegalStateException cause = (IllegalStateException) expected.getCause(); assertThat(cause).hasMessage("test exception"); verify(deleteResolver).performDelete(same(storIOSQLite), any(DeleteQuery.class)); verifyNoMoreInteractions(storIOSQLite, internal, deleteResolver); }

Target:
public void shouldWrapExceptionIntoStorIOExceptionCompletable() { final StorIOSQLite storIOSQLite = mock(StorIOSQLite.class); final StorIOSQLite.Internal internal = mock(StorIOSQLite.Internal.class); when(storIOSQLite.lowLevel()).thenReturn(internal); final DeleteResolver<DeleteQuery> deleteResolver = mock(DeleteResolver.class); when(deleteResolver.performDelete(same(storIOSQLite), any(DeleteQuery.class))) .thenThrow(new IllegalStateException("test exception")); final TestSubscriber<DeleteResult> testSubscriber = new TestSubscriber<DeleteResult>(); new PreparedDeleteByQuery.Builder(storIOSQLite, DeleteQuery.builder().table("test_table").build()) .withDeleteResolver(deleteResolver) .prepare() .asRxComletable() .subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); testSubscriber.assertNoValues(); testSubscriber.assertError(StorIOException.class); StorIOException expected = (StorIOException) testSubscriber.getOnErrorEvents().get(0); IllegalStateException cause = (IllegalStateException) expected.getCause(); assertThat(cause).hasMessage("test exception"); verify(deleteResolver).performDelete(same(storIOSQLite), any(DeleteQuery.class)); verifyNoMoreInteractions(storIOSQLite, internal, deleteResolver); }