auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void run() { long lastRpcTs = 0; while (!Thread.interrupted()) { try { synchronized (refreshMasters) { refreshMasters.wait(periodicRefreshMs); } long currentTs = EnvironmentEdgeManager.currentTime(); if (lastRpcTs != 0 && currentTs - lastRpcTs <= timeBetweenRefreshesMs) { continue; } lastRpcTs = currentTs; LOG.debug("Attempting to refresh master address end points."); Set<ServerName> newMasters = new HashSet<>(registry.getMasters().get()); registry.populateMasterStubs(newMasters); LOG.debug("Finished refreshing master end points. {}", newMasters); } catch (InterruptedException e) { LOG.debug("Interrupted during wait, aborting refresh-masters-thread.", e); break; } catch (ExecutionException | IOException e) { LOG.debug("Error populating latest list of masters.", e); } } }

Target:
public void run() { long lastRpcTs = 0; while (!Thread.interrupted()) { try { synchronized (refreshMasters) { refreshMasters.wait(periodicRefreshMs); } long currentTs = EnvironmentEdgeManager.currentTime(); if (lastRpcTs != 0 && currentTs - lastRpcTs <= timeBetweenRefreshesMs) { continue; } lastRpcTs = currentTs; LOG.debug("Attempting to refresh master address end points."); Set<ServerName> newMasters = new HashSet<>(registry.getMasters().get()); registry.populateMasterStubs(newMasters); LOG.debug("Finished refreshing master end points. {}", newMasters); } catch (InterruptedException e) { LOG.debug("Interrupted during wait, aborting refresh-masters-thread.", e); break; } catch (ExecutionException | IOException e) { LOG.debug("Error populating latest list of masters.", e); } } LOG.info("Master end point refresher loop exited."); }
Source:
private boolean updatePostObject() { if (mEditorFragment == null) { AppLog.e(AppLog.T.POSTS, "Fragment not initialized"); return false; } try { UpdateResult updateResult = mViewModel .updatePostObject(this, mShowAztecEditor, mEditPostRepository, (String) mEditorFragment.getTitle(), oldContent -> { try { return (String) mEditorFragment.getContent(oldContent); } catch (EditorFragmentNotAddedException e) { return null; } }); return updateResult instanceof UpdateResult.Success; } catch (EditorFragmentNotAddedException e) { AppLog.e(T.EDITOR, "Impossible to save the post, we weren't able to update it."); return false; } }

Target:
private boolean updatePostObject() { if (mEditorFragment == null) { AppLog.e(AppLog.T.POSTS, "Fragment not initialized"); return false; } UpdateResult updateResult = mViewModel .updatePostObject(this, mShowAztecEditor, mEditPostRepository, oldContent -> { try { String title = (String) mEditorFragment.getTitle(); String content = (String) mEditorFragment.getContent(oldContent); return new PostFields(title, content); } catch (EditorFragmentNotAddedException e) { AppLog.e(T.EDITOR, "Impossible to save the post, we weren't able to update it."); return new UpdateFromEditor.Failed(e); } }); return updateResult instanceof UpdateResult.Success; }
Source:
public Map<Integer,Error> commit() { Map<Integer,Error> results=new HashMap<>(); if(!idsInBatch.isEmpty()) { BulkWriteResult writeResult; LOGGER.debug("attempToUpdate={}",idsInBatch.size()); try { if(writeConcern==null) { writeResult=bwo.execute(); } else { writeResult=bwo.execute(writeConcern); } LOGGER.debug("writeResult={}",writeResult); if(idsInBatch.size()==writeResult.getMatchedCount()) { LOGGER.debug("Successful update"); } else { LOGGER.debug("notUpdated={}",idsInBatch.size()-writeResult.getMatchedCount()); findConcurrentModifications(results); } } catch (BulkWriteException e) { List<BulkWriteError> writeErrors=e.getWriteErrors(); if(writeErrors!=null) { for(BulkWriteError we:writeErrors) { if (we.getCode() == 11000 || we.getCode() == 11001) { results.put(we.getIndex(), Error.get("update", MongoCrudConstants.ERR_DUPLICATE, we.getMessage())); } else { results.put(we.getIndex(), Error.get("update", MongoCrudConstants.ERR_SAVE_ERROR, we.getMessage())); } } } findConcurrentModifications(results); } } reset(); return results; }

Target:
public Map<Integer,Error> commit() { Map<Integer,Error> results=new HashMap<>(); if(!idsInBatch.isEmpty()) { BulkWriteResult writeResult; LOGGER.debug("attemptToUpdate={}",idsInBatch.size()); try { if(writeConcern==null) { writeResult=bwo.execute(); } else { writeResult=bwo.execute(writeConcern); } LOGGER.debug("writeResult={}",writeResult); if(idsInBatch.size()==writeResult.getMatchedCount()) { LOGGER.debug("Successful update"); } else { LOGGER.debug("notUpdated={}",idsInBatch.size()-writeResult.getMatchedCount()); findConcurrentModifications(results); } } catch (BulkWriteException e) { List<BulkWriteError> writeErrors=e.getWriteErrors(); if(writeErrors!=null) { for(BulkWriteError we:writeErrors) { if (MongoCrudConstants.isDuplicate(we.getCode())) { results.put(we.getIndex(), Error.get("update", MongoCrudConstants.ERR_DUPLICATE, we.getMessage())); } else { results.put(we.getIndex(), Error.get("update", MongoCrudConstants.ERR_SAVE_ERROR, we.getMessage())); } } } findConcurrentModifications(results); } } reset(); return results; }
Source:
public void seek(long position) throws IOException { if (position >= 0 && position < count) { pos = position; } }

Target:
public void seek(long position) throws IOException { if (pos < 0) { throw new IOException("Negative seek offset"); } else if (position >= 0 && position < count) { pos = position; } else { pos = count; } }
Source:
public boolean removeAcl(OzoneObj obj, OzoneAcl acl) throws IOException { Map<String, String> auditMap = obj.toAuditMap(); auditMap.put(OzoneConsts.ACLS, acl.toString()); boolean auditSuccess = true; try{ if(isAclEnabled) { checkAcls(obj.getResourceType(), obj.getStoreType(), ACLType.WRITE_ACL, obj.getVolumeName(), obj.getBucketName(), obj.getKeyName()); } switch (obj.getResourceType()) { case VOLUME: return volumeManager.removeAcl(obj, acl); case BUCKET: return bucketManager.removeAcl(obj, acl); case KEY: return keyManager.removeAcl(obj, acl); case PREFIX: return prefixManager.removeAcl(obj, acl); default: throw new OMException("Unexpected resource type: " + obj.getResourceType(), INVALID_REQUEST); } } catch(Exception ex) { auditSuccess = false; AUDIT.logWriteFailure( buildAuditMessageForFailure(OMAction.REMOVE_ACL, auditMap, ex)); throw ex; } finally { if(auditSuccess){ AUDIT.logWriteSuccess( buildAuditMessageForSuccess(OMAction.REMOVE_ACL, auditMap)); } } }

Target:
public boolean removeAcl(OzoneObj obj, OzoneAcl acl) throws IOException { boolean auditSuccess = true; try{ if(isAclEnabled) { checkAcls(obj.getResourceType(), obj.getStoreType(), ACLType.WRITE_ACL, obj.getVolumeName(), obj.getBucketName(), obj.getKeyName()); } switch (obj.getResourceType()) { case VOLUME: return volumeManager.removeAcl(obj, acl); case BUCKET: return bucketManager.removeAcl(obj, acl); case KEY: return keyManager.removeAcl(obj, acl); case PREFIX: return prefixManager.removeAcl(obj, acl); default: throw new OMException("Unexpected resource type: " + obj.getResourceType(), INVALID_REQUEST); } } catch(Exception ex) { auditSuccess = false; auditAcl(obj, Arrays.asList(acl), OMAction.REMOVE_ACL, ex); throw ex; } finally { if(auditSuccess){ auditAcl(obj, Arrays.asList(acl), OMAction.REMOVE_ACL, null); } } }
Source:
public static <T> T service(final T instance, @SuppressWarnings("rawtypes") final Map<String,ProcessFunction<T,? extends TBase>> processorView) { final Method isOnewayMethod; try { isOnewayMethod = ProcessFunction.class.getDeclaredMethod("isOneway"); } catch (NoSuchMethodException e) { throw new RuntimeException("Could not access isOneway method", e); } catch (SecurityException e) { throw new RuntimeException("Could not access isOneway method", e); } isOnewayMethod.setAccessible(true); final Set<String> onewayMethods = new HashSet<String>(); for (@SuppressWarnings("rawtypes") Entry<String,ProcessFunction<T,? extends TBase>> entry : processorView.entrySet()) { try { if ((Boolean) isOnewayMethod.invoke(entry.getValue())) { onewayMethods.add(entry.getKey()); } } catch (Exception e) { throw new RuntimeException(e); } } log.debug("Found oneway Thrift methods: " + onewayMethods); InvocationHandler handler = new RpcServerInvocationHandler<T>(instance) { private final Logger log = LoggerFactory.getLogger(instance.getClass()); @Override public Object invoke(Object obj, Method method, Object[] args) throws Throwable { try { return super.invoke(obj, method, args); } catch (RuntimeException e) { if (onewayMethods.contains(method.getName())) { throw e; } String msg = e.getMessage(); log.error(msg, e); throw new TException(msg); } catch (Error e) { if (onewayMethods.contains(method.getName())) { throw e; } String msg = e.getMessage(); log.error(msg, e); throw new TException(msg); } } }; @SuppressWarnings("unchecked") T proxiedInstance = (T) Proxy.newProxyInstance(instance.getClass().getClassLoader(), instance.getClass().getInterfaces(), handler); return proxiedInstance; }

Target:
public static <T> T service(final T instance, @SuppressWarnings("rawtypes") final Map<String,ProcessFunction<T,? extends TBase>> processorView) { final Set<String> onewayMethods = getOnewayMethods(processorView); log.debug("Found oneway Thrift methods: " + onewayMethods); InvocationHandler handler = getInvocationHandler(instance, onewayMethods); @SuppressWarnings("unchecked") T proxiedInstance = (T) Proxy.newProxyInstance(instance.getClass().getClassLoader(), instance.getClass().getInterfaces(), handler); return proxiedInstance; }
Source:
public Long deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException { switch (jsonParser.currentToken()) { case VALUE_NUMBER_INT: return jsonParser.getLongValue(); case VALUE_STRING: return Long.valueOf(jsonParser.getValueAsString()); } throw new IOException("Expected a long value"); }

Target:
public Long deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException { switch (jsonParser.currentToken()) { case VALUE_NUMBER_INT: return jsonParser.getLongValue(); case VALUE_STRING: return parseLong(jsonParser); case VALUE_NULL: return null; } throw new IOException("Expected a long value"); }
Source:
private GetVmConfigurationBySnapshotQuery<GetVmConfigurationBySnapshotQueryParams> setupQueryBySnapshotId(Guid snapshotId) { GetVmConfigurationBySnapshotQueryParams queryParams = getQueryParameters(); when(queryParams.getSnapshotId()).thenReturn(snapshotId); GetVmConfigurationBySnapshotQuery<GetVmConfigurationBySnapshotQueryParams> executeQuery = getQuery(); return executeQuery; }

Target:
private GetVmConfigurationBySnapshotQuery<GetVmConfigurationBySnapshotQueryParams> setupQueryBySnapshotId(Guid snapshotId) { GetVmConfigurationBySnapshotQueryParams queryParams = getQueryParameters(); when(queryParams.getSnapshotId()).thenReturn(snapshotId); GetVmConfigurationBySnapshotQuery<GetVmConfigurationBySnapshotQueryParams> query = getQuery(); return query; }
Source:
DataContextImpl(CalciteConnectionImpl connection, Map<String, Object> parameters, CalciteSchema rootSchema) { this.queryProvider = connection; this.typeFactory = connection.getTypeFactory(); this.rootSchema = rootSchema; final Holder<Long> timeHolder = Holder.of(System.currentTimeMillis()); Hook.CURRENT_TIME.run(timeHolder); final long time = timeHolder.get(); final TimeZone timeZone = connection.getTimeZone(); final long localOffset = timeZone.getOffset(time); final long currentOffset = localOffset; final Holder<Object[]> streamHolder = Holder.of(new Object[] {System.in, System.out, System.err}); Hook.STANDARD_STREAMS.run(streamHolder); ImmutableMap.Builder<Object, Object> builder = ImmutableMap.builder(); builder.put(Variable.UTC_TIMESTAMP.camelName, time) .put(Variable.CURRENT_TIMESTAMP.camelName, time + currentOffset) .put(Variable.LOCAL_TIMESTAMP.camelName, time + localOffset) .put(Variable.TIME_ZONE.camelName, timeZone) .put(Variable.STDIN.camelName, streamHolder.get()[0]) .put(Variable.STDOUT.camelName, streamHolder.get()[1]) .put("#DELTA#", new LinkedList<>()) .put(Variable.STDERR.camelName, streamHolder.get()[2]); for (Map.Entry<String, Object> entry : parameters.entrySet()) { Object e = entry.getValue(); if (e == null) { e = AvaticaSite.DUMMY_VALUE; } builder.put(entry.getKey(), e); } map = builder.build(); }

Target:
DataContextImpl(CalciteConnectionImpl connection, Map<String, Object> parameters, CalciteSchema rootSchema) { this.queryProvider = connection; this.typeFactory = connection.getTypeFactory(); this.rootSchema = rootSchema; final Holder<Long> timeHolder = Holder.of(System.currentTimeMillis()); Hook.CURRENT_TIME.run(timeHolder); final long time = timeHolder.get(); final TimeZone timeZone = connection.getTimeZone(); final long localOffset = timeZone.getOffset(time); final long currentOffset = localOffset; final Holder<Object[]> streamHolder = Holder.of(new Object[] {System.in, System.out, System.err}); Hook.STANDARD_STREAMS.run(streamHolder); ImmutableMap.Builder<Object, Object> builder = ImmutableMap.builder(); builder.put(Variable.UTC_TIMESTAMP.camelName, time) .put(Variable.CURRENT_TIMESTAMP.camelName, time + currentOffset) .put(Variable.LOCAL_TIMESTAMP.camelName, time + localOffset) .put(Variable.TIME_ZONE.camelName, timeZone) .put(Variable.STDIN.camelName, streamHolder.get()[0]) .put(Variable.STDOUT.camelName, streamHolder.get()[1]) .put(Variable.STDERR.camelName, streamHolder.get()[2]); for (Map.Entry<String, Object> entry : parameters.entrySet()) { Object e = entry.getValue(); if (e == null) { e = AvaticaSite.DUMMY_VALUE; } builder.put(entry.getKey(), e); } map = builder.build(); }
Source:
public Response<CommentInfo> apply(RevisionResource rsrc, Input in) throws AuthException, BadRequestException, ResourceConflictException, OrmException { if (Strings.isNullOrEmpty(in.path)) { throw new BadRequestException("path must be non-empty"); } else if (in.message == null || in.message.trim().isEmpty()) { throw new BadRequestException("message must be non-empty"); } else if (in.line != null && in.line <= 0) { throw new BadRequestException("line must be > 0"); } else if (in.line != null && in.range != null && in.line != in.range.getEndLine()) { throw new BadRequestException("range endLine must be on the same line as the comment"); } else if ((in.line == null || in.line == 0) && in.range != null) { throw new BadRequestException("range must be null if line is null or 0"); } int line; if (in.range != null || in.line != null) { line = in.range != null ? in.range.getEndLine() : in.line; } else { line = 0; } PatchLineComment c = new PatchLineComment( new PatchLineComment.Key( new Patch.Key(rsrc.getPatchSet().getId(), in.path), ChangeUtil.messageUUID(db.get())), line, rsrc.getAccountId(), Url.decode(in.inReplyTo)); c.setSide(in.side == Side.PARENT ? (short) 0 : (short) 1); c.setMessage(in.message.trim()); c.setRange(in.range); db.get().patchComments().insert(Collections.singleton(c)); return Response.created(new CommentInfo(c, null)); }

Target:
public Response<CommentInfo> apply(RevisionResource rsrc, Input in) throws AuthException, BadRequestException, ResourceConflictException, OrmException { if (Strings.isNullOrEmpty(in.path)) { throw new BadRequestException("path must be non-empty"); } else if (in.message == null || in.message.trim().isEmpty()) { throw new BadRequestException("message must be non-empty"); } else if (in.line != null && in.line <= 0) { throw new BadRequestException("line must be > 0"); } else if (in.line != null && in.range != null && in.line != in.range.getEndLine()) { throw new BadRequestException("range endLine must be on the same line as the comment"); } int line = in.line != null ? in.line : in.range != null ? in.range.getEndLine() : 0; PatchLineComment c = new PatchLineComment( new PatchLineComment.Key( new Patch.Key(rsrc.getPatchSet().getId(), in.path), ChangeUtil.messageUUID(db.get())), line, rsrc.getAccountId(), Url.decode(in.inReplyTo)); c.setSide(in.side == Side.PARENT ? (short) 0 : (short) 1); c.setMessage(in.message.trim()); c.setRange(in.range); db.get().patchComments().insert(Collections.singleton(c)); return Response.created(new CommentInfo(c, null)); }
Source:
public static JSONArray arrayToArray(org.json.JSONArray ar){ assert(ar instanceof JSONArray); return (JSONArray) ar; }

Target:
public static JSONArray arrayToArray(org.json.JSONArray ar){ Assert.that(ar == null || ar instanceof JSONArray, "Object "+ar+" should have been an instance of our JSONArray."); return (JSONArray) ar; }
Source:
public BinaryCodec(final Path path, final boolean writing) { this(); try { this.isWriting = writing; if (this.isWriting) { this.outputStream = IOUtil.maybeBufferOutputStream(Files.newOutputStream(path)); this.outputFileName = path.toString(); } else { this.inputStream = IOUtil.maybeBufferInputStream(Files.newInputStream(path)); this.inputFileName = path.toString(); } } catch (FileNotFoundException e) { throw new RuntimeIOException("File not found: " + path, e); } catch (IOException e) { throw new RuntimeIOException("Error opening: " + path, e); } }

Target:
public BinaryCodec(final Path path, final boolean writing) { this(); try { this.isWriting = writing; if (this.isWriting) { this.outputStream = IOUtil.maybeBufferOutputStream(Files.newOutputStream(path)); this.outputFileName = path.getFileName().toString(); } else { this.inputStream = IOUtil.maybeBufferInputStream(Files.newInputStream(path)); this.inputFileName = path.getFileName().toString(); } } catch (FileNotFoundException e) { throw new RuntimeIOException("File not found: " + path, e); } catch (IOException e) { throw new RuntimeIOException("Error opening: " + path, e); } }
Source:
public PackageRepository getPackageRepository(String repoId) { return goConfigService.getConfigForEditing().getPackageRepositories().find(repoId); }

Target:
public PackageRepository getPackageRepository(String repoId) { return goConfigService.getPackageRepository(repoId); }
Source:
protected Object call() throws Exception { WanSyncType wanSyncType = WanSyncType.getByType(parameters.wanSyncType); if (wanSyncType == null) { throw new IllegalArgumentException( String.format("Invalid wanSyncType: %s", parameters.wanSyncType)); } switch (wanSyncType) { case ALL_MAPS: return syncAllMaps(); case SINGLE_MAP: return syncSingleMap(); default: return isNullOrEmptyAfterTrim(parameters.mapName) ? syncAllMaps() : syncSingleMap(); } }

Target:
protected Object call() throws Exception { WanSyncType wanSyncType = WanSyncType.getByType(parameters.wanSyncType); if (wanSyncType == null) { throw new IllegalArgumentException( String.format("Invalid wanSyncType: %s", parameters.wanSyncType)); } switch (wanSyncType) { case ALL_MAPS: return syncAllMaps(); case SINGLE_MAP: return syncSingleMap(); default: throw new IllegalArgumentException( String.format("Unsupported wanSyncType: %s", parameters.wanSyncType)); } }
Source:
private static void assertEventsMatchLoosely(List<Event> events, Condition<? super Event>... conditions) { SoftAssertions softly = new SoftAssertions(); for (Condition<? super Event> condition : conditions) checkCondition(events, softly, condition); softly.assertAll(); }

Target:
private static void assertEventsMatchLoosely(List<Event> events, Condition<? super Event>... conditions) { SoftAssertions softly = new SoftAssertions(); for (Condition<? super Event> condition : conditions) { checkCondition(events, softly, condition); } softly.assertAll(); }
Source:
public void handlePost(ActionParameters params) throws ActionException { params.requireLoggedInUser(); JSONObject jsonObject = params.getHttpParamAsJSON("featureData"); OskariLayer layer = getLayer(jsonObject.optString("layerId")); if (!canEdit(layer, params.getUser())) { throw new ActionDeniedException("User doesn't have edit permission for layer: " + layer.getId()); } try { String payload = createPayload(jsonObject); String layerName = layer.getName(); String url = layer.getUrl(); url = movePrefixFromNameToURL(layerName,url); String responseString = postPayload(layer, payload, url); flushLayerTilesCache(layer.getId()); if (responseString.indexOf("Exception") > -1) { throw new ActionException("Cannot delete feature"); } else if (responseString.indexOf("<wfs:totalDeleted>1</wfs:totalDeleted>") > -1) { ResponseHelper.writeResponse(params, "Feature deleted"); } else { throw new ActionException("Unexpected response from service: " + responseString); } } catch (JSONException e) { LOG.error(e, "JSON processing error"); throw new ActionException("JSON processing error", e); } catch (XMLStreamException e) { LOG.error(e, "Failed to create WFS-T request"); throw new ActionException("Failed to create WFS-T request", e); } catch (FactoryException e) { LOG.error(e, "Failed to create WFS-T request (crs)"); throw new ActionException("Failed to create WFS-T request (crs)", e); } }

Target:
public void handlePost(ActionParameters params) throws ActionException { params.requireLoggedInUser(); JSONObject jsonObject = params.getHttpParamAsJSON("featureData"); OskariLayer layer = getLayer(jsonObject.optString("layerId")); if (!canEdit(layer, params.getUser())) { throw new ActionDeniedException("User doesn't have edit permission for layer: " + layer.getId()); } try { String payload = createPayload(jsonObject); String responseString = postPayload(layer.getUsername(), layer.getPassword(), payload, getURLForNamespace(layer.getName(), layer.getUrl())); flushLayerTilesCache(layer.getId()); if (responseString.indexOf("Exception") > -1) { throw new ActionException("Cannot delete feature"); } else if (responseString.indexOf("<wfs:totalDeleted>1</wfs:totalDeleted>") > -1) { ResponseHelper.writeResponse(params, "Feature deleted"); } else { throw new ActionException("Unexpected response from service: " + responseString); } } catch (JSONException e) { LOG.error(e, "JSON processing error"); throw new ActionException("JSON processing error", e); } catch (XMLStreamException e) { LOG.error(e, "Failed to create WFS-T request"); throw new ActionException("Failed to create WFS-T request", e); } catch (FactoryException e) { LOG.error(e, "Failed to create WFS-T request (crs)"); throw new ActionException("Failed to create WFS-T request (crs)", e); } }
Source:
public void testParseLongEmpty() throws EvaluationException { try { PARSE_LONG.evaluate(s("")); } catch (EvaluationException e){ assertThat("parse_Long(\"\") throws", true, instanceOf(Boolean.class)); } }

Target:
public void testParseLongEmpty() throws EvaluationException { PARSE_LONG.evaluate(s("")); }
Source:
protected final List<IMergeViewerItem> createMergeViewerItemFrom(Collection<?> values) { List<IMergeViewerItem> ret = newArrayListWithCapacity(values.size()); for (EObject value : filter(values, EObject.class)) { if (!value.eIsProxy()) { IMergeViewerItem valueToAdd = createMergeViewerItemFrom(value); if (valueToAdd != null) { ret.add(valueToAdd); } } } return ret; }

Target:
protected final List<IMergeViewerItem> createMergeViewerItemFrom(Collection<?> values) { List<IMergeViewerItem> ret = newArrayListWithCapacity(values.size()); for (EObject value : filter(values, EObject.class)) { IMergeViewerItem valueToAdd = createMergeViewerItemFrom(value); if (valueToAdd != null) { ret.add(valueToAdd); } } return ret; }
Source:
public void shouldParsePushPayload() throws Exception { GitHubPushTrigger trigger = mock(GitHubPushTrigger.class); FreeStyleProject prj = jenkins.createFreeStyleProject(); prj.addTrigger(trigger); prj.setScm(GIT_SCM_FROM_RESOURCE); GHSubscriberEvent subscriberEvent = new GHSubscriberEvent("shouldParsePushPayload", GHEvent.PUSH, classpath("payloads/push.json")); new DefaultPushGHEventSubscriber().onEvent(subscriberEvent); verify(trigger).onPost(GitHubTriggerEvent.create() .withTimestamp(subscriberEvent.getTimestamp()) .withOrigin("shouldParsePushPayload") .withTriggeredByUser(TRIGGERED_BY_USER_FROM_RESOURCE) .build() ); }

Target:
public void shouldParsePushPayload() throws Exception { GitHubPushTrigger trigger = mock(GitHubPushTrigger.class); FreeStyleProject prj = jenkins.createFreeStyleProject(); prj.addTrigger(trigger); prj.setScm(GIT_SCM_FROM_RESOURCE); GHSubscriberEvent subscriberEvent = new GHSubscriberEvent("shouldParsePushPayload", GHEvent.PUSH, classpath("payloads/push.json")); new DefaultPushGHEventSubscriber().onEvent(subscriberEvent); verify(trigger).onPost(eq(GitHubTriggerEvent.create() .withTimestamp(subscriberEvent.getTimestamp()) .withOrigin("shouldParsePushPayload") .withTriggeredByUser(TRIGGERED_BY_USER_FROM_RESOURCE) .build() )); }
Source:
public String tSnePlotWithMetadata( @PathVariable String experimentAccession, @PathVariable int perplexity, @PathVariable String metadata, @RequestParam(defaultValue = "") String accessKey) { Experiment experiment = experimentTrader.getExperiment(experimentAccession, accessKey); if(getTSnePlotMetadata(experiment.getAccession()).equalsIgnoreCase("[]")) { return GSON.toJson(ImmutableMap.of( "series", new ArrayList<Map<String, Object>>() )); } else { return GSON.toJson( ImmutableMap.of( "series", modelForHighcharts( "", new TreeMap<>( tSnePlotService.fetchTSnePlotWithMetadata( experiment.getAccession(), perplexity, metadata))))); } }

Target:
public String tSnePlotWithMetadata( @PathVariable String experimentAccession, @PathVariable int perplexity, @PathVariable String metadata, @RequestParam(defaultValue = "") String accessKey) { Experiment experiment = experimentTrader.getExperiment(experimentAccession, accessKey); if(isNullOrEmpty(getTSnePlotMetadata(experiment.getAccession()))) { return GSON.toJson(ImmutableMap.of( "series", new ArrayList<Map<String, Object>>() )); } else { return GSON.toJson( ImmutableMap.of( "series", modelForHighcharts( "", new TreeMap<>( tSnePlotService.fetchTSnePlotWithMetadata( experiment.getAccession(), perplexity, metadata))))); } }
Source:
public void serverLeavingAndJoiningWhilePutAndClear() throws Exception { int locatorPort = ClusterStartupRule.getDUnitLocatorPort(); Future<Void> startStopServer = executor.submit(() -> { for (int i = 0; i < 3; i++) { MemberVM server3 = cluster.startServerVM(3, s -> s.withConnectionToLocator(locatorPort) .withProperty(SERIALIZABLE_OBJECT_FILTER, "org.apache.geode.cache.query.data.*") .withRegion(RegionShortcut.PARTITION, "cities")); server3.stop(false); } }); Future<Void> putAndClear = executor.submit(() -> { for (int i = 0; i < 30; i++) { IntStream.range(0, 100).forEach(j -> cities.put(j, new City(j))); try { cities.clear(); } catch (ServerOperationException e) { assertThat(e.getCause().getMessage()) .contains("Unable to clear all the buckets from the partitioned region cities") .contains("either data (buckets) moved or member departed"); } QueryService queryService = clientCache.getQueryService(); Query query = queryService.newQuery(MUMBAI_QUERY); Query query2 = queryService.newQuery(ID_10_QUERY); assertThat(((SelectResults) query.execute()).size()).isEqualTo(0); assertThat(((SelectResults) query2.execute()).size()).isEqualTo(0); } }); startStopServer.get(60, TimeUnit.SECONDS); putAndClear.get(60, TimeUnit.SECONDS); }

Target:
public void serverLeavingAndJoiningWhilePutAndClear() throws Exception { int locatorPort = ClusterStartupRule.getDUnitLocatorPort(); Future<Void> startStopServer = executor.submit(() -> { for (int i = 0; i < 3; i++) { MemberVM server3 = cluster.startServerVM(3, s -> s.withConnectionToLocator(locatorPort) .withProperty(SERIALIZABLE_OBJECT_FILTER, "org.apache.geode.cache.query.data.*") .withRegion(RegionShortcut.PARTITION, "cities")); server3.stop(false); } }); Future<Void> putAndClear = executor.submit(() -> { for (int i = 0; i < 30; i++) { IntStream.range(0, 100).forEach(j -> cities.put(j, new City(j))); try { cities.clear(); QueryService queryService = clientCache.getQueryService(); Query query = queryService.newQuery(MUMBAI_QUERY); Query query2 = queryService.newQuery(ID_10_QUERY); assertThat(((SelectResults) query.execute()).size()).isEqualTo(0); assertThat(((SelectResults) query2.execute()).size()).isEqualTo(0); } catch (ServerOperationException e) { assertThat(e.getCause().getMessage()) .contains("Unable to clear all the buckets from the partitioned region cities") .contains("either data (buckets) moved or member departed"); } } }); startStopServer.get(60, TimeUnit.SECONDS); putAndClear.get(60, TimeUnit.SECONDS); }
Source:
public void testGenerateClass() throws CarbonToolsIntegrationTestException, XPathExpressionException { boolean fileCreated = false; Process process = null; String commandDirectory; try { serviceUrl = automationContext.getContextUrls().getServiceUrl() + "/Version?wsdl"; log.info("Service URL -" + serviceUrl); String[] cmdArrayToWsdl2Java; if (CarbonCommandToolsUtil.isCurrentOSWindows()) { throw new SkipException("Issue with wsdl2java.bat"); } else { cmdArrayToWsdl2Java = new String[]{"sh", "wsdl2java.sh", "-uri", serviceUrl}; commandDirectory = System.getProperty(ServerConstants.CARBON_HOME) + "/bin"; } process = CarbonCommandToolsUtil.runScript(commandDirectory, cmdArrayToWsdl2Java); fileCreated = CarbonCommandToolsUtil.waitForFileCreation( System.getProperty(ServerConstants.CARBON_HOME) + File.separator + "bin" + File.separator + "src/org/wso2/carbon/core/services/version/VersionStub.java"); } finally { if (process != null) { process.destroy(); } } Assert.assertTrue(fileCreated, "Java file not created successfully"); }

Target:
public void testGenerateClass() throws CarbonToolsIntegrationTestException, XPathExpressionException { boolean fileCreated = false; Process process = null; String commandDirectory; try { serviceUrl = automationContext.getContextUrls().getServiceUrl() + "/Version?wsdl"; log.info("Service URL -" + serviceUrl); String[] cmdArrayToWsdl2Java; if ((CarbonCommandToolsUtil.getCurrentOperatingSystem(). contains(OperatingSystems.WINDOWS.name().toLowerCase())) ) { throw new SkipException("Issue with wsdl2java.bat"); } else { cmdArrayToWsdl2Java = new String[]{"sh", "wsdl2java.sh", "-uri", serviceUrl}; commandDirectory = System.getProperty(ServerConstants.CARBON_HOME) + "/bin"; } process = CarbonCommandToolsUtil.runScript(commandDirectory, cmdArrayToWsdl2Java); fileCreated = CarbonCommandToolsUtil.waitForFileCreation( System.getProperty(ServerConstants.CARBON_HOME) + File.separator + "bin" + File.separator + "src/org/wso2/carbon/core/services/version/VersionStub.java"); } finally { if (process != null) { process.destroy(); } } Assert.assertTrue(fileCreated, "Java file not created successfully"); }
Source:
public long getQueueSize() { return executorQueue.size() * batchSize + (openBatch == null ? 0 : openBatch.size()); }

Target:
public long getQueueSize() { Batch snapshot = openBatch; return executorQueue.size() * batchSize + (snapshot == null ? 0 : snapshot.size()); }
Source:
protected AndroidDriver createBrowser() { try { return new AndroidDriver(new URL(getAndroidDriverUrl()), createCapabilities()); } catch (MalformedURLException e) { throw new RuntimeException(e); } }

Target:
protected AndroidDriver createBrowser() { try { return new AndroidDriver(new URL(getAndroidDriverUrl()), createCapabilities()); } catch (MalformedURLException e) { LOGGER.error("Invalid URL: " + getAndroidDriverUrl(), e); return null; } }
Source:
private void assertTetherStatesNotNullButEmpty(final TetherStatesParcel parcel) { assertFalse(parcel == null); assertEquals(0, parcel.availableList.length); assertEquals(0, parcel.tetheredList.length); assertEquals(0, parcel.localOnlyList.length); assertEquals(0, parcel.erroredIfaceList.length); assertEquals(0, parcel.lastErrorList.length); }

Target:
private void assertTetherStatesNotNullButEmpty(final TetherStatesParcel parcel) { assertFalse(parcel == null); assertEquals(0, parcel.availableList.length); assertEquals(0, parcel.tetheredList.length); assertEquals(0, parcel.localOnlyList.length); assertEquals(0, parcel.erroredIfaceList.length); assertEquals(0, parcel.lastErrorList.length); MiscAssertsKt.assertFieldCountEquals(5, TetherStatesParcel.class); }
Source:
public void fireUpdated(RegistrationUpdate update, Registration registration) { for (RegistrationListener l : listeners) { l.updated(update, registration); } clientStatusTracker.setClientOnline(registration); }

Target:
public void fireUpdated(RegistrationUpdate update, Registration registration) { for (RegistrationListener l : listeners) { l.updated(update, registration); } }
Source:
public void shouldBuildProperTriggerEventRequests() { List<TriggerEventRequest> triggerEventRequests = triggerBuilder.buildTriggers(); assertFalse(triggerEventRequests.isEmpty()); assertEquals(3, triggerEventRequests.get(0).getEventParameters().size()); assertEquals(DisplayNameHelper.buildDisplayName(DisplayNames.COHORT_GOTMEMBER, CONFIG_NAME), triggerEventRequests.get(0).getDisplayName()); assertEquals(EventKeys.BASE_SUBJECT + "Cohort.GotMember", triggerEventRequests.get(0).getSubject()); }

Target:
public void shouldBuildProperTriggerEventRequests() { List<TriggerEventRequest> triggerEventRequests = triggerBuilder.buildTriggers(); assertFalse(triggerEventRequests.isEmpty()); assertEquals(3, triggerEventRequests.get(0).getEventParameters().size()); assertEquals(Keys.PATIENT_UUID, triggerEventRequests.get(0).getEventParameters().get(0).getEventKey()); assertEquals(Keys.PATIENT_DISPLAY, triggerEventRequests.get(0).getEventParameters().get(1).getEventKey()); assertEquals(Keys.COHORT_QUERY_UUID, triggerEventRequests.get(0).getEventParameters().get(2).getEventKey()); assertEquals(DisplayNameHelper.buildDisplayName(DisplayNames.COHORT_QUERY_REPORTMEMBER, CONFIG_NAME), triggerEventRequests.get(0).getDisplayName()); assertEquals(EventSubjects.GET_COHORT_QUERY_MEMBER_EVENT, triggerEventRequests.get(0).getSubject()); }
Source:
private Xpp3Dom stripConfigElements(Xpp3Dom config, ArrayList<String> goalParams) { for (int i=0; i<config.getChildCount(); i++) { if (!goalParams.contains(config.getChild(i).getName().trim())) { config.removeChild(i); stripConfigElements(config, goalParams); } } return config; }

Target:
private Xpp3Dom stripConfigElements(Xpp3Dom config, ArrayList<String> goalParams) { List<Integer> removeChildren = new ArrayList<Integer>(); for (int i=0; i<config.getChildCount(); i++) { if (!goalParams.contains(config.getChild(i).getName().trim())) { removeChildren.add(i); } } Collections.reverse(removeChildren); for (int child : removeChildren) { config.removeChild(child); } return config; }
Source:
private Method getRequestMethod(RequestMethod req) { Map<RequestMethod, Method> map = new HashMap<>(8); map.put(RequestMethod.GET, Method.GET); map.put(RequestMethod.POST, Method.POST); map.put(RequestMethod.PUT, Method.PUT); map.put(RequestMethod.DELETE, Method.DELETE); map.put(RequestMethod.PATCH, Method.PATCH); map.put(RequestMethod.OPTIONS, Method.OPTIONS); map.put(RequestMethod.HEAD, Method.HEAD); map.put(RequestMethod.TRACE, Method.TRACE); return map.get(req); }

Target:
private Method getRequestMethod(RequestMethod req) { Map<RequestMethod, Method> map = new HashMap<>(); map.put(RequestMethod.GET, Method.GET); map.put(RequestMethod.POST, Method.POST); map.put(RequestMethod.PUT, Method.PUT); map.put(RequestMethod.DELETE, Method.DELETE); map.put(RequestMethod.PATCH, Method.PATCH); map.put(RequestMethod.OPTIONS, Method.OPTIONS); map.put(RequestMethod.HEAD, Method.HEAD); map.put(RequestMethod.TRACE, Method.TRACE); return map.get(req); }
Source:
public List<String> values(String name) { return headers == null ? null : headers.get("Request-Id"); }

Target:
public List<String> values(String name) { return headers == null ? null : headers.get(name); }
Source:
private ExternalParamCollection createExternalParamCollection(DataEntry dataEntry, InternalParamCollection queryParams) { ExternalParamCollection pc = new ExternalParamCollection(); if(!dataService.getConfig(configId).isCaseSensitive()) { for (String name : dataEntry.getNames()) { pc.addParam(new org.wso2.carbon.dataservices.core.engine.ExternalParam(name.toLowerCase(), dataEntry.getValue(name), DBSFields.COLUMN)); } for (InternalParam iParam : queryParams.getParams()) { pc.addParam(new org.wso2.carbon.dataservices.core.engine.ExternalParam(iParam.getName().toLowerCase(), iParam.getValue(), DBSFields.QUERY_PARAM)); } } else { for (String name : dataEntry.getNames()) { pc.addParam(new org.wso2.carbon.dataservices.core.engine.ExternalParam(name, dataEntry.getValue(name), DBSFields.COLUMN)); } for (InternalParam iParam : queryParams.getParams()) { pc.addParam(new org.wso2.carbon.dataservices.core.engine.ExternalParam(iParam.getName(), iParam.getValue(), DBSFields.QUERY_PARAM)); } } return pc; }

Target:
private ExternalParamCollection createExternalParamCollection(DataEntry dataEntry, InternalParamCollection queryParams) { ExternalParamCollection pc = new ExternalParamCollection(); if (!dataService.getConfig(configId).isResultSetFieldsCaseSensitive()) { for (String name : dataEntry.getNames()) { pc.addParam(new org.wso2.carbon.dataservices.core.engine.ExternalParam(name.toLowerCase(), dataEntry.getValue(name), DBSFields.COLUMN)); } for (InternalParam iParam : queryParams.getParams()) { pc.addParam(new org.wso2.carbon.dataservices.core.engine.ExternalParam(iParam.getName().toLowerCase(), iParam.getValue(), DBSFields.QUERY_PARAM)); } } else { for (String name : dataEntry.getNames()) { pc.addParam(new org.wso2.carbon.dataservices.core.engine.ExternalParam(name, dataEntry.getValue(name), DBSFields.COLUMN)); } for (InternalParam iParam : queryParams.getParams()) { pc.addParam( new org.wso2.carbon.dataservices.core.engine.ExternalParam(iParam.getName(), iParam.getValue(), DBSFields.QUERY_PARAM)); } } return pc; }
Source:
public String maskSensitiveElements( final Message message, final String originalLogString) { if (sensitiveElementNames.isEmpty() || message == null) { return originalLogString; } final String contentType = (String) message.get(Message.CONTENT_TYPE); if (contentType.toLowerCase().contains(XML_CONTENT) || contentType.toLowerCase().contains(HTML_CONTENT)) { return applyMasks(originalLogString, MATCH_PATTERN_XML, REPLACEMENT_PATTERN_XML); } else if (contentType.toLowerCase().contains(JSON_CONTENT)) { return applyMasks(originalLogString, MATCH_PATTERN_JSON, REPLACEMENT_PATTERN_JSON); } return originalLogString; }

Target:
public String maskSensitiveElements( final Message message, final String originalLogString) { if (replacementsXML.isEmpty() && replacementsJSON.isEmpty() || message == null || originalLogString == null) { return originalLogString; } final String contentType = (String) message.get(Message.CONTENT_TYPE); if (contentType.toLowerCase().contains(XML_CONTENT) || contentType.toLowerCase().contains(HTML_CONTENT)) { return applyMasks(originalLogString, replacementsXML); } else if (contentType.toLowerCase().contains(JSON_CONTENT)) { return applyMasks(originalLogString, replacementsJSON); } return originalLogString; }
Source:
public void beginTree(DetailAST rootAST) { final Map<Integer, TextBlock> cppComments = getFileContents() .getSingleLineComments(); final Map<Integer, List<TextBlock>> cComments = getFileContents() .getBlockComments(); final Set<Integer> lines = new HashSet<>(); lines.addAll(cppComments.keySet()); lines.addAll(cComments.keySet()); for (Integer lineNo : lines) { final String line = getLines()[lineNo - 1]; final String lineBefore; final TextBlock comment; final int commentColNo; if (cppComments.containsKey(lineNo)) { comment = cppComments.get(lineNo); lineBefore = line.substring(0, comment.getStartColNo()); commentColNo = comment.getStartColNo(); } else { final List<TextBlock> commentList = cComments.get(lineNo); comment = commentList.get(commentList.size() - 1); lineBefore = line.substring(0, comment.getStartColNo()); commentColNo = comment.getStartColNo(); if (comment.getText().length == 1 && !CommonUtil.isBlank(line .substring(comment.getEndColNo() + 1))) { continue; } } if (!format.matcher(lineBefore).find() && !isLegalComment(comment)) { illegalLines.put(lineNo, commentColNo); } } }

Target:
public void beginTree(DetailAST rootAST) { final Map<Integer, TextBlock> cppComments = getFileContents() .getSingleLineComments(); final Map<Integer, List<TextBlock>> cComments = getFileContents() .getBlockComments(); final Set<Integer> lines = new HashSet<>(); lines.addAll(cppComments.keySet()); lines.addAll(cComments.keySet()); for (Integer lineNo : lines) { final String line = getLines()[lineNo - 1]; final String lineBefore; final TextBlock comment; if (cppComments.containsKey(lineNo)) { comment = cppComments.get(lineNo); lineBefore = line.substring(0, comment.getStartColNo()); } else { final List<TextBlock> commentList = cComments.get(lineNo); comment = commentList.get(commentList.size() - 1); lineBefore = line.substring(0, comment.getStartColNo()); if (comment.getText().length == 1 && !CommonUtil.isBlank(line .substring(comment.getEndColNo() + 1))) { continue; } } if (!format.matcher(lineBefore).find() && !isLegalComment(comment)) { illegalLines.put(lineNo, comment.getStartColNo()); } } }
Source:
private List<Header> getPropagatedHeaders(Exchange exchange, HeaderFilterStrategy headerFilterStrategy) { return exchange.getIn().getHeaders().entrySet().stream() .filter(entry -> !headerFilterStrategy.applyFilterToExternalHeaders(entry.getKey(), entry.getValue(), exchange)) .map(entry -> new RecordHeader(entry.getKey(), getHeaderValue(entry.getValue()))) .collect(Collectors.toList()); }

Target:
private List<Header> getPropagatedHeaders(Exchange exchange, HeaderFilterStrategy headerFilterStrategy) { return exchange.getIn().getHeaders().entrySet().stream() .filter(entry -> shouldBeFiltered(entry, exchange, headerFilterStrategy)) .map(this::getRecordHeader) .filter(Objects::nonNull) .collect(Collectors.toList()); }
Source:
public boolean equals(Object that) { return (that instanceof NumberRange) ? equals((NumberRange) that) : super.equals(that); }

Target:
public boolean equals(Object that) { return super.equals(that); }
Source:
public T get() { Provider<T> p = item.get(); T t = null; if( p != null ) { t = p.get(); } return t; }

Target:
public T get() { ItemAndPluginName myItem = item.get(); return myItem != null ? myItem.provider.get() : null; }
Source:
public JsonConverter() { final Set<DeserializationFeature> deserializationFeatures = new HashSet<>(); deserializationFeatures.add(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS); deserializer = new JsonDeserializer(deserializationFeatures, true); }

Target:
public JsonConverter() { serializer = new JsonSerializer( mkSet(), JSON_NODE_FACTORY ); deserializer = new JsonDeserializer( mkSet( DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS ), JSON_NODE_FACTORY ); }
Source:
public String toString() { return "WorkspaceServiceImpl{" + "securityService=" + securityService + ", catalogFramework=" + catalogFramework + ", workspaceTransformer=" + workspaceTransformer + ", maxSubscriptions=" + maxSubscriptions.get() + '}'; }

Target:
public String toString() { return String.format( "WorkspaceServiceImpl{securityService=%s, catalogFramework=%s, workspaceTransformer=%s, maxSubscriptions=%d}", securityService, catalogFramework, workspaceTransformer, maxSubscriptions); }
Source:
public <T> Mono<FeedResponse<T>> readMany( List<Pair<String, PartitionKey>> itemKeyList, String sessionToken, Class<T> classType) { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); if (!StringUtils.isNotBlank(sessionToken)) { options = options.setSessionToken(sessionToken); } options.setMaxDegreeOfParallelism(-1); return CosmosBridgeInternal .getAsyncDocumentClient(this.getDatabase()) .readMany(itemKeyList, BridgeInternal.getLink(this), options, classType); }

Target:
public <T> Mono<FeedResponse<T>> readMany( List<Pair<String, PartitionKey>> itemKeyList, String sessionToken, Class<T> classType) { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); if (!StringUtils.isNotEmpty(sessionToken)) { options = options.setSessionToken(sessionToken); } options.setMaxDegreeOfParallelism(-1); return CosmosBridgeInternal .getAsyncDocumentClient(this.getDatabase()) .readMany(itemKeyList, BridgeInternal.getLink(this), options, classType); }
Source:
public List<String> getParameters() { return new ArrayList<>(parameters); }

Target:
public List<String> getParameters() { return unmodifiableList(parameters); }
Source:
public boolean sourceStatus(String servicePID) { try { List<ServiceReference<? extends Source>> sourceReferences = getServiceReferences(); for (ServiceReference<? extends Source> ref : sourceReferences) { Source service = bundleContext.getService(ref); if (service instanceof ConfiguredService) { ConfiguredService cs = (ConfiguredService) service; try { Configuration config = configurationAdmin .getConfiguration(cs.getConfigurationPid()); if (config.getProperties().get("service.pid").equals(servicePID)) { return service.isAvailable(); } } catch (IOException e) { LOGGER.warn("Couldn't find configuration for source '{}'", service.getId()); } } else { LOGGER.warn("Source '{}' not a configured service", service.getId()); } } } catch (InvalidSyntaxException e) { LOGGER.error("Could not get service reference list"); } return false; }

Target:
public boolean sourceStatus(String servicePID) { try { List<Source> sources = helper.getSources(); for (Source source : sources) { if (source instanceof ConfiguredService) { ConfiguredService cs = (ConfiguredService) source; try { Configuration config = helper.getConfiguration(cs); if (config != null && config.getProperties().get("service.pid") .equals(servicePID)) { try { return source.isAvailable(); } catch (Exception e) { LOGGER.warn("Couldn't get availability on source {}: {}", servicePID, e); } } } catch (IOException e) { LOGGER.warn("Couldn't find configuration for source '{}'", source.getId()); } } else { LOGGER.warn("Source '{}' not a configured service", source.getId()); } } } catch (InvalidSyntaxException e) { LOGGER.error("Could not get service reference list"); } return false; }
Source:
public void testAnswerCard(){ Collection col; col = getCol(); long deckId = mTestDeckIds[0]; col.getDecks().select(deckId); col.getSched().reset(); Card card = col.getSched().getCard(); long cardId = card.getId(); assertEquals("card is initial new", Consts.CARD_TYPE_NEW, card.getQueue()); ContentResolver cr = InstrumentationRegistry.getInstrumentation().getTargetContext().getContentResolver(); Uri reviewInfoUri = FlashCardsContract.ReviewInfo.CONTENT_URI; ContentValues values = new ContentValues(); long noteId = card.note().getId(); int cardOrd = card.getOrd(); int ease = AbstractFlashcardViewer.EASE_3; long timeTaken = 5000; values.put(FlashCardsContract.ReviewInfo.NOTE_ID, noteId); values.put(FlashCardsContract.ReviewInfo.CARD_ORD, cardOrd); values.put(FlashCardsContract.ReviewInfo.EASE, ease); values.put(FlashCardsContract.ReviewInfo.TIME_TAKEN, timeTaken); int updateCount = cr.update(reviewInfoUri, values, null, null); assertEquals("Check if update returns 1", 1, updateCount); try { Thread.currentThread().wait(500); } catch (Exception e) { } col.getSched().reset(); Card newCard = col.getSched().getCard(); if(newCard != null){ if(newCard.note().getId() == card.note().getId() && newCard.getOrd() == card.getOrd()){ fail("Next scheduled card has not changed"); } } Card cardAfterReview = col.getCard(cardId); assertEquals("card is now type rev", Card.TYPE_REV, cardAfterReview.getQueue()); }

Target:
public void testAnswerCard(){ Collection col = getCol(); Card card = getFirstCardFromScheduler(col); long cardId = card.getId(); assertEquals("card is initial new", Consts.CARD_TYPE_NEW, card.getQueue()); ContentResolver cr = InstrumentationRegistry.getInstrumentation().getTargetContext().getContentResolver(); Uri reviewInfoUri = FlashCardsContract.ReviewInfo.CONTENT_URI; ContentValues values = new ContentValues(); long noteId = card.note().getId(); int cardOrd = card.getOrd(); int ease = AbstractFlashcardViewer.EASE_3; long timeTaken = 5000; values.put(FlashCardsContract.ReviewInfo.NOTE_ID, noteId); values.put(FlashCardsContract.ReviewInfo.CARD_ORD, cardOrd); values.put(FlashCardsContract.ReviewInfo.EASE, ease); values.put(FlashCardsContract.ReviewInfo.TIME_TAKEN, timeTaken); int updateCount = cr.update(reviewInfoUri, values, null, null); assertEquals("Check if update returns 1", 1, updateCount); try { Thread.currentThread().wait(500); } catch (Exception e) { } col.getSched().reset(); Card newCard = col.getSched().getCard(); if(newCard != null){ if(newCard.note().getId() == card.note().getId() && newCard.getOrd() == card.getOrd()){ fail("Next scheduled card has not changed"); } } Card cardAfterReview = col.getCard(cardId); assertEquals("card is now type rev", Card.TYPE_REV, cardAfterReview.getQueue()); }