auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void validateUnion(GraphQLUnionType type, SchemaValidationErrorCollector errorCollector) { assertTypeName(type.getName(), errorCollector); UnionTypeDefinition definition = type.getDefinition(); if (definition == null) { return; } List<Type> memberTypes = definition.getMemberTypes(); if (memberTypes == null || memberTypes.size() == 0) { SchemaValidationError validationError = new SchemaValidationError(SchemaValidationErrorType.UnionTypeLackOfTypeError, String.format("Union type \"%s\" must include one or more unique member types.", type.getName())); errorCollector.addError(validationError); } List<String> typeNames = new ArrayList<>(); for (Type memberType : memberTypes) { String typeName = ((TypeName) memberType).getName(); GraphQLNamedType graphQLNamedType = schemaTypeHolder.get(typeName); if (!(graphQLNamedType instanceof GraphQLObjectType)) { SchemaValidationError validationError = new SchemaValidationError(SchemaValidationErrorType.InvalidUnionMemberTypeError, String.format("The member types of a Union type must all be Object base types. member type \"%s\" in Union \"%s\" is invalid.", ((TypeName) memberType).getName(), type.getName())); errorCollector.addError(validationError); } if (typeNames.contains(typeName)) { SchemaValidationError validationError = new SchemaValidationError(SchemaValidationErrorType.RepetitiveElementError, String.format("The member types of a Union type must be unique. member type \"%s\" in Union \"%s\" is not unique.", ((TypeName) memberType).getName(), type.getName())); errorCollector.addError(validationError); } typeNames.add(typeName); } }

Target:
private void validateUnion(GraphQLUnionType type, SchemaValidationErrorCollector errorCollector) { assertTypeName(type.getName(), errorCollector); List<GraphQLNamedOutputType> memberTypes = type.getTypes(); if (memberTypes == null || memberTypes.size() == 0) { SchemaValidationError validationError = new SchemaValidationError(SchemaValidationErrorType.UnionTypeLackOfTypeError, String.format("Union type \"%s\" must include one or more unique member types.", type.getName())); errorCollector.addError(validationError); } Set<String> typeNames = new HashSet<>(); for (GraphQLNamedOutputType memberType : memberTypes) { String typeName = memberType.getName(); GraphQLNamedType graphQLNamedType = schemaTypeHolder.get(typeName); if (!(graphQLNamedType instanceof GraphQLObjectType)) { SchemaValidationError validationError = new SchemaValidationError(SchemaValidationErrorType.InvalidUnionMemberTypeError, String.format("The member types of a Union type must all be Object base types. member type \"%s\" in Union \"%s\" is invalid.", ((TypeName) memberType).getName(), type.getName())); errorCollector.addError(validationError); } if (typeNames.contains(typeName)) { SchemaValidationError validationError = new SchemaValidationError(SchemaValidationErrorType.RepetitiveElementError, String.format("The member types of a Union type must be unique. member type \"%s\" in Union \"%s\" is not unique.", ((TypeName) memberType).getName(), type.getName())); errorCollector.addError(validationError); } typeNames.add(typeName); } }
Source:
public Route getRoute( final Territory start, final Territory end, final Predicate<Territory> cond) { checkNotNull(start); checkNotNull(end); return new RouteFinder(this, Matches.territoryIs(end).or(cond)) .findRoute(start, end) .orElse(null); }

Target:
public Route getRoute( final Territory start, final Territory end, final Predicate<Territory> cond) { checkNotNull(start); checkNotNull(end); return new RouteFinder(this, Matches.territoryIs(end).or(cond)) .findRouteByDistance(start, end) .orElse(null); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMapView = findViewById(R.id.mapView); List<String> subDomains = Arrays.asList("a", "b", "c", "d"); mWebTiledLayer = new WebTiledLayer(getString(R.string.template_uri_stamen), subDomains); mWebTiledLayer.loadAsync(); mWebTiledLayer.addDoneLoadingListener(() -> { if (mWebTiledLayer.getLoadStatus() == LoadStatus.LOADED) { ArcGISMap map = new ArcGISMap(new Basemap(mWebTiledLayer)); mMapView.setMap(map); mWebTiledLayer.setAttribution(getString(R.string.stamen_attribution)); } }); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMapView = findViewById(R.id.mapView); List<String> subDomains = Arrays.asList("a", "b", "c", "d"); WebTiledLayer webTiledLayer = new WebTiledLayer(getString(R.string.template_uri_stamen), subDomains); ArcGISMap map = new ArcGISMap(new Basemap(webTiledLayer)); mMapView.setMap(map); webTiledLayer.setAttribution(getString(R.string.stamen_attribution)); }
Source:
public void killContainer(String container, int signal) throws IOException { final List<Pair<String, ?>> headers = new ArrayList<>(2); headers.add(Pair.of("Content-Type", "text/plain")); headers.add(Pair.of("Content-Length", 0)); try (DockerConnection connection = openConnection(dockerDaemonUri).method("POST") .path("/containers/" + container + "/kill") .query("signal", signal) .headers(headers)) { final DockerResponse response = connection.request(); final int status = response.getStatus(); if (204 != status) { throw new DockerException(getDockerExceptionMessage(response), status); } } }

Target:
public void killContainer(String container, int signal) throws IOException { final List<Pair<String, ?>> headers = new ArrayList<>(2); headers.add(Pair.of("Content-Type", MediaType.TEXT_PLAIN)); headers.add(Pair.of("Content-Length", 0)); try (DockerConnection connection = openConnection(dockerDaemonUri).method("POST") .path("/containers/" + container + "/kill") .query("signal", signal) .headers(headers)) { final DockerResponse response = connection.request(); final int status = response.getStatus(); if (NO_CONTENT.getStatusCode() != status) { throw new DockerException(getDockerExceptionMessage(response), status); } } }
Source:
public static void main(String[] args) { Options options = handleOptions(Options.class, args); WikibaseRepository wikibaseRepository; if (options.entityNamespaces() == null) { wikibaseRepository = new WikibaseRepository(options.wikibaseScheme(), options.wikibaseHost()); } else { String[] strEntityNamespaces = options.entityNamespaces().split(","); long[] longEntityNamespaces = new long[strEntityNamespaces.length]; try { for (int i = 0; i < strEntityNamespaces.length; i++) { longEntityNamespaces[i] = Long.parseLong(strEntityNamespaces[i]); } } catch (NumberFormatException e) { log.error("Invalid value for --entityNamespaces. Namespace index should be an integer.", e); return; } wikibaseRepository = new WikibaseRepository(options.wikibaseScheme(), options.wikibaseHost(), 0, longEntityNamespaces); } URI sparqlUri; try { sparqlUri = new URI(options.sparqlUrl()); } catch (URISyntaxException e) { log.error("Invalid url: " + options.sparqlUrl() + " caused by " + e.getMessage()); return; } WikibaseUris uris = new WikibaseUris(options.wikibaseHost()); RdfRepository rdfRepository = new RdfRepository(sparqlUri, uris); Change.Source<? extends Change.Batch> changeSource = buildChangeSource(options, rdfRepository, wikibaseRepository); if (changeSource == null) { return; } int threads = options.threadCount(); ThreadFactoryBuilder threadFactory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("update %s"); ExecutorService executor = new ThreadPoolExecutor(threads, threads, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory.build()); Munger munger = mungerFromOptions(options); new Update<>(changeSource, wikibaseRepository, rdfRepository, munger, executor, options.pollDelay(), uris, options.verify()).run(); }

Target:
public static void main(String[] args) { Options options = handleOptions(Options.class, args); WikibaseRepository wikibaseRepository = buildWikibaseRepository(options); if (wikibaseRepository == null) { return; } URI sparqlUri; try { sparqlUri = new URI(options.sparqlUrl()); } catch (URISyntaxException e) { log.error("Invalid url: " + options.sparqlUrl() + " caused by " + e.getMessage()); return; } WikibaseUris uris = new WikibaseUris(options.wikibaseHost()); RdfRepository rdfRepository = new RdfRepository(sparqlUri, uris); Change.Source<? extends Change.Batch> changeSource = buildChangeSource(options, rdfRepository, wikibaseRepository); if (changeSource == null) { return; } int threads = options.threadCount(); ThreadFactoryBuilder threadFactory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("update %s"); ExecutorService executor = new ThreadPoolExecutor(threads, threads, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory.build()); Munger munger = mungerFromOptions(options); new Update<>(changeSource, wikibaseRepository, rdfRepository, munger, executor, options.pollDelay(), uris, options.verify()).run(); }
Source:
public FEELFnResult<BigDecimal> invoke(@ParameterName( "number" ) BigDecimal number) { if ( number == null ) { return FEELFnResult.ofError( new InvalidParametersEvent( FEELEvent.Severity.ERROR, "number", "cannot be null" ) ); } return FEELFnResult.ofResult( new BigDecimal( Math.log( number.doubleValue() ) ) ); }

Target:
public FEELFnResult<BigDecimal> invoke(@ParameterName( "number" ) BigDecimal number) { if ( number == null ) { return FEELFnResult.ofError( new InvalidParametersEvent( FEELEvent.Severity.ERROR, "number", "cannot be null" ) ); } return FEELFnResult.ofResult( new BigDecimal( Math.log( number.doubleValue() ), MathContext.DECIMAL128 ) ); }
Source:
public byte[] getCacheKey() { return new CacheKeyBuilder(PostAggregatorIds.THETA_SKETCH_CONSTANT).appendInt(hashCode()).build(); }

Target:
public byte[] getCacheKey() { return new CacheKeyBuilder(PostAggregatorIds.THETA_SKETCH_CONSTANT) .appendString(DigestUtils.sha1Hex(value)).build(); }
Source:
private void completeNetworkAttachmentsByLabels() { for (NicLabel nicLabel : params.getLabels()) { List<Network> labelNetworks = labelToNetworks.get(nicLabel.getLabel()); if (labelNetworks == null) { continue; } for (Network network : labelNetworks) { NetworkAttachment newOrModifiedNetworkAttachment = attachmentsByNetworkId.get(network.getId()); NetworkAttachment existingNetworkAttachment = existingNetworkAttachmentsByNetworkId.get(network.getId()); boolean existingAttachmentRemoved = existingNetworkAttachment == null ? false : params.getRemovedNetworkAttachments() .contains(existingNetworkAttachment.getId()); NetworkAttachment attachmentToConfigure = newOrModifiedNetworkAttachment == null && !existingAttachmentRemoved ? existingNetworkAttachment : newOrModifiedNetworkAttachment; if (attachmentToConfigure == null) { params.getNetworkAttachments().add(createNetworkAttachment(nicLabel.getNicId(), nicLabel.getNicName(), network.getId(), network.getName())); } else if (!Objects.equals(attachmentToConfigure.getNicName(), nicLabel.getNicName())) { if (newOrModifiedNetworkAttachment == null) { NetworkAttachment updatedNetworkAttachment = new NetworkAttachment(existingNetworkAttachment); updatedNetworkAttachment.setNicId(nicLabel.getNicId()); updatedNetworkAttachment.setNicName(nicLabel.getNicName()); params.getNetworkAttachments().add(updatedNetworkAttachment); } } } } }

Target:
private void completeNetworkAttachmentsByLabels() { for (NicLabel nicLabel : params.getLabels()) { List<Network> labelNetworks = labelToNetworks.get(nicLabel.getLabel()); if (labelNetworks == null) { continue; } for (Network network : labelNetworks) { NetworkAttachment newOrModifiedNetworkAttachment = attachmentsByNetworkId.get(network.getId()); NetworkAttachment existingNetworkAttachment = existingNetworkAttachmentsByNetworkId.get(network.getId()); boolean existingAttachmentRemoved = existingNetworkAttachment == null ? false : params.getRemovedNetworkAttachments() .contains(existingNetworkAttachment.getId()); boolean noNewOrModifiedNetworkAttachment = newOrModifiedNetworkAttachment == null; NetworkAttachment attachmentToConfigure = noNewOrModifiedNetworkAttachment && !existingAttachmentRemoved ? existingNetworkAttachment : newOrModifiedNetworkAttachment; if (attachmentToConfigure == null) { params.getNetworkAttachments().add(createNetworkAttachment(nicLabel.getNicId(), nicLabel.getNicName(), network.getId(), network.getName())); } else if (!Objects.equals(attachmentToConfigure.getNicName(), nicLabel.getNicName()) && noNewOrModifiedNetworkAttachment) { NetworkAttachment updatedNetworkAttachment = new NetworkAttachment(existingNetworkAttachment); updatedNetworkAttachment.setNicId(nicLabel.getNicId()); updatedNetworkAttachment.setNicName(nicLabel.getNicName()); params.getNetworkAttachments().add(updatedNetworkAttachment); } } } }
Source:
default void doBuild(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay) throws IOException, ServletException { getParameterizedJobMixIn().doBuild(req, rsp, delay); }

Target:
public final void doBuild(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay) throws IOException, ServletException { if (delay == null) { delay = new TimeDuration(asJob().getQuietPeriod()); } if (!asJob().isBuildable()) { throw HttpResponses.error(SC_CONFLICT, new IOException(asJob().getFullName() + " is not buildable")); } ParametersDefinitionProperty pp = asJob().getProperty(ParametersDefinitionProperty.class); if (pp != null && !req.getMethod().equals("POST")) { req.getView(pp, "index.jelly").forward(req, rsp); return; } hudson.model.BuildAuthorizationToken.checkPermission(asJob(), asJob().getAuthToken(), req, rsp); if (pp != null) { pp._doBuild(req, rsp, delay); return; } Queue.Item item = Jenkins.getInstance().getQueue().schedule2(asJob(), delay.getTime(), getBuildCause(asJob(), req)).getItem(); if (item != null) { rsp.sendRedirect(SC_CREATED, req.getContextPath() + '/' + item.getUrl()); } else { rsp.sendRedirect("."); } }
Source:
private void primaryAction() { switch (getPrimaryAction()) { case UPDATE: showUpdateConfirmationDialogAndUploadPost(); return; case PUBLISH_NOW: if (AppPrefs.isAsyncPromoRequired()) { showAsyncPromoDialog(mPost.isPage(), false); } else { showPublishConfirmationDialogAndPublishPost(); } return; case SCHEDULE: if (AppPrefs.isAsyncPromoRequired()) { showAsyncPromoDialog(mPost.isPage(), true); } else { uploadPost(false); } return; case SUBMIT_FOR_REVIEW: case SAVE: uploadPost(false); } }

Target:
private void primaryAction() { switch (getPrimaryAction()) { case UPDATE: showUpdateConfirmationDialogAndUploadPost(); return; case PUBLISH_NOW: if (AppPrefs.isAsyncPromoRequired()) { showAsyncPromoDialog(mPost.isPage(), false); } else { showPublishConfirmationDialogAndPublishPost(); } return; case SCHEDULE: if (AppPrefs.isAsyncPromoRequired()) { showAsyncPromoDialog(mPost.isPage(), true); } else { uploadPost(false); } return; case SUBMIT_FOR_REVIEW: case SAVE: uploadPost(false); break; } }
Source:
private String getToolTipText(boolean attachKeybinding) { String text = getModel().getLocalizedTooltip(); if (!attachKeybinding) { return text; } ParameterizedCommand parmCmd = getModel().getWbCommand(); if (parmCmd == null) { generateCommand(); parmCmd = getModel().getWbCommand(); } if (parmCmd != null && text == null) { try { text = parmCmd.getName(); } catch (NotDefinedException e) { return null; } } TriggerSequence sequence = bindingService.getBestSequenceFor(parmCmd); if (sequence != null) { text = text + " (" + sequence.format() + ')'; } return text; }

Target:
private String getToolTipText(boolean attachKeybinding) { String text = getModel().getLocalizedTooltip(); ParameterizedCommand parmCmd = getModel().getWbCommand(); if (parmCmd == null) { generateCommand(); parmCmd = getModel().getWbCommand(); } if (parmCmd != null && text == null) { try { text = parmCmd.getName(); } catch (NotDefinedException e) { return null; } } TriggerSequence sequence = bindingService.getBestSequenceFor(parmCmd); if (attachKeybinding && sequence != null) { text = text + " (" + sequence.format() + ')'; } return text; }
Source:
private boolean compatible(Alloc pred, Alloc succ) { return pred != null && pred.getObs().getInstrumentString().equals(succ.getObs().getInstrumentString()) && pred.getObs().getCoords(pred.getMiddlePoint()).equals(succ.getMiddlePoint()); }

Target:
private boolean compatible(Alloc pred, Alloc succ) { return pred != null && pred.getObs().getInstrumentString().equals(succ.getObs().getInstrumentString()) && pred.getObs().getCoords(pred.getEnd()).equals(succ.getObs().getCoords((pred.getEnd()))); }
Source:
protected void onEvent(GHEvent event, String payload) { try { GitHub gh = GitHub.connectAnonymously(); PullRequestInfo info = extractPullRequestInfo(event, payload, gh); for (AbstractProject job : getJobs(info.getRepo())) { GitHubPRTrigger trigger = triggerFrom(job, GitHubPRTrigger.class); GitHubPRTriggerMode triggerMode = trigger.getTriggerMode(); switch (triggerMode) { case HEAVY_HOOKS_CRON: case HEAVY_HOOKS: { LOGGER.debug("Queued check for (PR #{}) after heavy hook", job.getName(), info.getNum()); trigger.queueRun(job, info.getNum()); break; } case LIGHT_HOOKS: { LOGGER.warn("Unsupported LIGHT_HOOKS trigger mode"); break; } default: break; } } } catch (Exception e) { LOGGER.error("Can't process hook", event, e); } }

Target:
protected void onEvent(GHEvent event, String payload) { try { GitHub gh = GitHub.connectAnonymously(); PullRequestInfo info = extractPullRequestInfo(event, payload, gh); for (Job job : getJobs(info.getRepo())) { GitHubPRTrigger trigger = triggerFrom(job, GitHubPRTrigger.class); GitHubPRTriggerMode triggerMode = trigger.getTriggerMode(); switch (triggerMode) { case HEAVY_HOOKS_CRON: case HEAVY_HOOKS: { LOGGER.debug("Queued check for (PR #{}) after heavy hook", job.getName(), info.getNum()); trigger.queueRun(job, info.getNum()); break; } case LIGHT_HOOKS: { LOGGER.warn("Unsupported LIGHT_HOOKS trigger mode"); break; } default: break; } } } catch (Exception e) { LOGGER.error("Can't process hook", event, e); } }
Source:
public static <R> R parsePemContent(CodePointIterator pemContent, BiFunction<String, ByteIterator, R> contentFunction) throws IllegalArgumentException { Assert.checkNotNullParam("pemContent", pemContent); Assert.checkNotNullParam("contentFunction", contentFunction); if (! pemContent.limitedTo(11).contentEquals("-----BEGIN ")) { throw log.malformedPemContent(pemContent.offset()); } String type = pemContent.delimitedBy('-').drainToString().trim(); final Matcher matcher = VALID_LABEL.matcher(type); if (matcher.find()) { throw log.malformedPemContent(matcher.start() + 11); } if (! pemContent.limitedTo(5).contentEquals("-----")) { throw log.malformedPemContent(pemContent.offset()); } String encodedKey = pemContent.delimitedBy('-').drainToString(); encodedKey = encodedKey.replaceAll("\r\n", ""); encodedKey = encodedKey.replaceAll("\n", ""); encodedKey = encodedKey.trim(); final ByteIterator byteIterator = ByteIterator.ofBytes(encodedKey.getBytes()).base64Decode(); final R result = contentFunction.apply(type, byteIterator); if (! pemContent.limitedTo(9).contentEquals("-----END ")) { throw log.malformedPemContent(pemContent.offset()); } if (! pemContent.limitedTo(type.length()).contentEquals(type)) { throw log.malformedPemContent(pemContent.offset()); } if (! pemContent.limitedTo(5).contentEquals("-----")) { throw log.malformedPemContent(pemContent.offset()); } return result; }

Target:
public static <R> R parsePemContent(CodePointIterator pemContent, BiFunction<String, ByteIterator, R> contentFunction) throws IllegalArgumentException { Assert.checkNotNullParam("pemContent", pemContent); Assert.checkNotNullParam("contentFunction", contentFunction); pemContent = pemContent.skipCrLf(); if (! pemContent.limitedTo(11).contentEquals("-----BEGIN ")) { throw log.malformedPemContent(pemContent.offset()); } String type = pemContent.delimitedBy('-').drainToString().trim(); final Matcher matcher = VALID_LABEL.matcher(type); if (matcher.find()) { throw log.malformedPemContent(matcher.start() + 11); } if (! pemContent.limitedTo(5).contentEquals("-----")) { throw log.malformedPemContent(pemContent.offset()); } final ByteIterator byteIterator = pemContent.delimitedBy('-').base64Decode(); final R result = contentFunction.apply(type, byteIterator); if (! pemContent.limitedTo(9).contentEquals("-----END ")) { throw log.malformedPemContent(pemContent.offset()); } if (! pemContent.limitedTo(type.length()).contentEquals(type)) { throw log.malformedPemContent(pemContent.offset()); } if (! pemContent.limitedTo(5).contentEquals("-----")) { throw log.malformedPemContent(pemContent.offset()); } return result; }
Source:
private static void loadIdentity(final JSch sch, final File priv) { if (priv.isFile()) { try { sch.addIdentity(priv.getAbsolutePath()); } catch (final JSchException e) { } } }

Target:
private static void loadIdentity(final JSch sch, final File priv) { if (priv.isFile()) { try { sch.addIdentity(priv.getAbsolutePath()); } catch (JSchException e) { } } }
Source:
public Optional<Serde> getKeySerde() { return keySerdeOptional; }

Target:
public Serde getKeySerde() { return keySerde; }
Source:
private void getTimeToFistByteData(String series, LineGraph lineGraph) { for (Map.Entry<Integer, SummaryStatistics> entry : mTimeToFirstByte.entrySet()) { lineGraph.addDataSeries( series + ", thread " + entry.getKey(), entry.getValue().computeTimeData()); } }

Target:
private void getTimeToFistByteData(String series, LineGraph lineGraph) { for (Map.Entry<Integer, SummaryStatistics> entry : mTimeToFirstByte.entrySet()) { lineGraph.addDataSeries( series + ", thread: " + entry.getKey(), entry.getValue().computeTimeData()); } }
Source:
public Block readBlock(Type type, int batchSize) throws IOException { checkArgument(type == DOUBLE); BlockBuilder builder = type.createBlockBuilder(null, batchSize); for (int i = 0; i < batchSize; ++i) { type.writeDouble(builder, valueSelector.getDouble()); } return builder.build(); }

Target:
public Block readBlock(Type type, int batchSize) { checkArgument(type == DOUBLE); BlockBuilder builder = type.createBlockBuilder(null, batchSize); for (int i = 0; i < batchSize; i++) { type.writeDouble(builder, valueSelector.getDouble()); } return builder.build(); }
Source:
public void setCorrelatedSubqueryExpression() { BlazeCriteriaBuilder cb = BlazeCriteria.get(cbf); BlazeCriteriaUpdate<Document> query = cb.createCriteriaUpdate(Document.class, "d"); BlazeRoot<Document> root = query.getRoot(); BlazeSubquery<Integer> subquery = query.subquery(Integer.class); BlazeRoot<Document> subqueryRoot = subquery.correlate(root); BlazeJoin<Document, Person> owner = subqueryRoot.join(Document_.owner, "owner"); subquery.select(cb.count(owner).as(Integer.class)); query.set(Document_.idx, cb.sum(subquery, 1)); UpdateCriteriaBuilder<Document> criteriaBuilder = query.createCriteriaBuilder(em); assertEquals("UPDATE Document d SET d.idx = (SELECT " + function("CAST_INTEGER", "COUNT(owner)") + " FROM d.owner owner) + 1", criteriaBuilder.getQueryString()); criteriaBuilder.getQuery().executeUpdate(); }

Target:
public void setCorrelatedSubqueryExpression() { BlazeCriteriaBuilder cb = BlazeCriteria.get(cbf); BlazeCriteriaUpdate<Document> query = cb.createCriteriaUpdate(Document.class, "d"); BlazeRoot<Document> root = query.getRoot(); BlazeSubquery<Integer> subquery = query.subquery(Integer.class); BlazeRoot<Document> subqueryRoot = subquery.correlate(root); BlazeJoin<Document, Person> owner = subqueryRoot.join(Document_.owner, "owner"); subquery.select(cb.count(owner).as(Integer.class)); query.set(Document_.idx, cb.sum(subquery, 1)); UpdateCriteriaBuilder<Document> criteriaBuilder = query.createCriteriaBuilder(em); assertEquals("UPDATE Document d SET d.idx = (SELECT " + function("CAST_INTEGER", "COUNT(owner)") + " FROM d.owner owner) + 1", criteriaBuilder.getQueryString()); criteriaBuilder.getQuery(); }
Source:
public URL getTileUrl(final Tile tile) throws MalformedURLException { return new URL("https", this.getHostName(), this.port, "/cycle/" + tile.zoomLevel + '/' + tile.tileX + '/' + tile.tileY + ".png?apikey=d6866308a6e24783822338c9a49ceb6c"); }

Target:
public URL getTileUrl(final Tile tile) throws MalformedURLException { return new URL("https", this.getHostName(), this.port, "/cycle/" + tile.zoomLevel + '/' + tile.tileX + '/' + tile.tileY + ".png?apikey=" + apiKey); }
Source:
private synchronized void resetSequenceForPartition(TopicPartition topicPartition) { topicPartitionBookkeeper.topicPartitionBookkeeping.remove(topicPartition); this.partitionsWithUnresolvedSequences.remove(topicPartition); }

Target:
private void resetSequenceForPartition(TopicPartition topicPartition) { topicPartitionBookkeeper.topicPartitions.remove(topicPartition); this.partitionsWithUnresolvedSequences.remove(topicPartition); }
Source:
public boolean selectChange(final int flag) { contentProvider.runWhenReady(IN_UI_ASYNC, new Runnable() { public void run() { TreeItem[] selection = viewer.getTree().getSelection(); TreeItem firstSelectedItem = selection.length > 0 ? selection[0] : null; Object newSelection = calculateNextSelection(firstSelectedItem, flag); if (newSelection != null) { fireOpen(newSelection); } } }); return false; }

Target:
public boolean selectChange(final int flag) { contentProvider.runWhenReady(IN_UI_ASYNC, new Runnable() { public void run() { TreeItem[] selection = viewer.getTree().getSelection(); TreeItem firstSelectedItem = firstOrNull(selection); Object newSelection = calculateNextSelection(firstSelectedItem, flag); if (newSelection != null) { fireOpen(newSelection); } } }); return false; }
Source:
public ItemBoundTool(String name, float damage, Set<Block> effectiveBlocks) { super(damage, 1, RegistrarBloodMagicItems.BOUND_TOOL_MATERIAL, effectiveBlocks); setUnlocalizedName(BloodMagic.MODID + ".bound." + name); setCreativeTab(BloodMagic.TAB_BM); setHarvestLevel(name, 4); addPropertyOverride(new ResourceLocation("bloodmagic", "activated"), new IItemPropertyGetter() { @SideOnly(Side.CLIENT) public float apply(ItemStack stack, @Nullable World worldIn, @Nullable EntityLivingBase entityIn) { return getActivated(stack) ? 1F : 0F; } }); addPropertyOverride(new ResourceLocation("bloodmagic", "charge"), new IItemPropertyGetter() { @SideOnly(Side.CLIENT) public float apply(ItemStack stack, @Nullable World worldIn, @Nullable EntityLivingBase entityIn) { return entityIn != null && getActivated(stack) && entityIn.isHandActive() && entityIn.getActiveItemStack() == stack ? MathHelper.clamp((float)Math.min(getCharge(stack), MAX_CHARGE_TIME) / (float)MAX_CHARGE_TIME, 0.0F, 1.0F) : 0; } }); this.name = name; this.tooltipBase = "tooltip.bloodmagic.bound." + name + "."; }

Target:
public ItemBoundTool(String name, float damage, Set<Block> effectiveBlocks) { super(damage, 1, RegistrarBloodMagicItems.BOUND_TOOL_MATERIAL, effectiveBlocks); setUnlocalizedName(BloodMagic.MODID + ".bound." + name); setCreativeTab(BloodMagic.TAB_BM); setHarvestLevel(name, 4); addPropertyOverride(new ResourceLocation(BloodMagic.MODID, "activated"), new IItemPropertyGetter() { @SideOnly(Side.CLIENT) public float apply(ItemStack stack, @Nullable World worldIn, @Nullable EntityLivingBase entityIn) { return getActivated(stack) ? 1F : 0F; } }); addPropertyOverride(new ResourceLocation(BloodMagic.MODID, "charge"), new IItemPropertyGetter() { @SideOnly(Side.CLIENT) public float apply(ItemStack stack, @Nullable World worldIn, @Nullable EntityLivingBase entityIn) { return entityIn != null && getActivated(stack) && entityIn.isHandActive() && entityIn.getActiveItemStack() == stack ? MathHelper.clamp((float)Math.min(getCharge(stack), MAX_CHARGE_TIME) / (float)MAX_CHARGE_TIME, 0.0F, 1.0F) : 0; } }); this.name = name; this.tooltipBase = "tooltip.bloodmagic.bound." + name + "."; }
Source:
@Override public void onBindViewHolder(ViewHolderImpl holder) { holder.title.setText(extra.getTitle()); holder.desc.setText(extra.getCardDesc()); holder.icon.setImageResource(extra.getIcon()); int color = ContextCompat.getColor(holder.card.getContext(), extra.getColor()); holder.card.setCardBackgroundColor(color); holder.run.setTextColor(color); holder.run.setOnClickListener(onClickListener); holder.itemView.setOnClickListener(onClickListener); holder.run.setTag(extra); holder.itemView.setTag(extra); Integer runTime = extra.getRuntime(pm); if (runTime.equals(PreferenceManager.MAX_RUNTIME_DISABLED)) runTime = 3600; holder.runtime.setText(holder.runtime.getContext().getString(R.string.Dashboard_Card_Seconds, runTime.toString())); }

Target:
@Override public void onBindViewHolder(ViewHolderImpl holder) { holder.title.setText(extra.getTitle()); holder.desc.setText(extra.getCardDesc()); holder.icon.setImageResource(extra.getIcon()); int color = ContextCompat.getColor(holder.card.getContext(), extra.getColor()); holder.card.setCardBackgroundColor(color); holder.run.setTextColor(color); holder.run.setOnClickListener(onClickListener); holder.itemView.setOnClickListener(onClickListener); holder.run.setTag(extra); holder.itemView.setTag(extra); holder.runtime.setText(holder.runtime.getContext().getString(R.string.Dashboard_Card_Seconds, extra.getRuntime(pm).toString())); }
Source:
public synchronized void deleteFile() { closeFile(); File historyTreeFile = fConfig.getStateFile(); try { if (!historyTreeFile.delete()) { Activator.getDefault().logError("Failed to delete" + historyTreeFile.getName()); } } catch (SecurityException e) { Activator.getDefault().logError(e.getMessage(), e); } }

Target:
public synchronized void deleteFile() { closeFile(); File historyTreeFile = fConfig.getStateFile(); if (!historyTreeFile.delete()) { Activator.getDefault().logError("Failed to delete" + historyTreeFile.getName()); } }
Source:
private static void checkEntries(LedgerEntries entries, byte[] data) throws InterruptedException, BKException { Iterator<LedgerEntry> iterator = entries.retainIterator(); while(iterator.hasNext()) { LedgerEntry entry = iterator.next(); assertArrayEquals(data, entry.getEntry()); } }

Target:
private static void checkEntries(LedgerEntries entries, byte[] data) throws InterruptedException, BKException { Iterator<LedgerEntry> iterator = entries.iterator(); while(iterator.hasNext()) { LedgerEntry entry = iterator.next(); assertArrayEquals(data, entry.getEntryBytes()); } }
Source:
public void sendDeleteEvent(final boolean ignoreUnmanaged) { final Event event = getContext().createEvent(EventConstants.DELETE_SERVICE_EVENT_UEI, getNodeId(), getAddress(), getSvcName(), new Date(), getStatus().getReason()); if (ignoreUnmanaged) { final Parm parm = new Parm(); parm.setParmName("ignoreUnmanaged"); parm.setValue(null); event.addParm(new Parm("ignoreUnmanaged", "true")); } getContext().sendEvent(event); }

Target:
public void sendDeleteEvent(final boolean ignoreUnmanaged) { final Event event = getContext().createEvent(EventConstants.DELETE_SERVICE_EVENT_UEI, getNodeId(), getAddress(), getSvcName(), new Date(), getStatus().getReason()); if (ignoreUnmanaged) { final Parm parm = new Parm(); parm.setParmName(EventConstants.PARM_IGNORE_UNMANAGED); parm.setValue(null); event.addParm(new Parm(EventConstants.PARM_IGNORE_UNMANAGED, "true")); } getContext().sendEvent(event); }
Source:
public void openErrorView(final String id){ final PlaceRequest request = new DefaultPlaceRequest(EXECUTION_ERRORS); if(TASK_TYPE.equals(type)) { request.addParameter(SEARCH_PARAMETER_TASK_ID, id); } else { request.addParameter(SEARCH_PARAMETER_PROCESS_INSTANCE_ID, id); } request.addParameter(SEARCH_PARAMETER_IS_ERROR_ACK, Boolean.toString(false)); viewPresenter.openView(request); }

Target:
public void openErrorView(final String id){ viewPresenter.openErrorView(id); }
Source:
public void afterRefreshTreatment(boolean succeeded) { if (!succeeded) { lockManager.releaseLock(monitoringLock); return; } try { synchronized (this) { unrespondedAttempts.set(0); setLastUpdate(); Guid storagePoolId = null; ArrayList<VDSDomainsData> domainsList = null; try { hostMonitoring.afterRefreshTreatment(); if (cachedVds != null && cachedVds.getStatus() != VDSStatus.Maintenance) { storagePoolId = cachedVds.getStoragePoolId(); domainsList = cachedVds.getDomains(); } hostMonitoring = null; } catch (IRSErrorException ex) { logAfterRefreshFailureMessage(ex); if (log.isDebugEnabled()) { logException(ex); } } catch (RuntimeException ex) { logAfterRefreshFailureMessage(ex); logException(ex); } if (domainsList != null) { updateVdsDomainsData(cachedVds, storagePoolId, domainsList); setDomains(cachedVds.getDomains()); } } } catch (Exception e) { log.error("Timer update runtime info failed. Exception:", ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception:", e); } finally { lockManager.releaseLock(monitoringLock); } }

Target:
public void afterRefreshTreatment(boolean succeeded) { if (!succeeded) { lockManager.releaseLock(monitoringLock); return; } try { synchronized (this) { unrespondedAttempts.set(0); setLastUpdate(); Guid storagePoolId = null; try { hostMonitoring.afterRefreshTreatment(); if (cachedVds != null && cachedVds.getStatus() != VDSStatus.Maintenance) { storagePoolId = cachedVds.getStoragePoolId(); setDomains(cachedVds.getDomains()); } hostMonitoring = null; } catch (IRSErrorException ex) { logAfterRefreshFailureMessage(ex); if (log.isDebugEnabled()) { logException(ex); } } catch (RuntimeException ex) { logAfterRefreshFailureMessage(ex); logException(ex); } if (getDomains() != null) { updateVdsDomainsData(cachedVds, storagePoolId, getDomains()); } } } catch (Exception e) { log.error("Timer update runtime info failed. Exception:", ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception:", e); } finally { lockManager.releaseLock(monitoringLock); } }
Source:
public void unregister(NotificationHandler handler, ID listenerID) throws NotificationServiceException { if (listenerID instanceof InstanceID) { try { InstanceID instanceID = (InstanceID) listenerID; SortedMap<Integer, ExecutionInstance> instances = executorAwaitedInstances.get(instanceID .getEntityClusterID()); synchronized (instances) { instances.remove(STATE_STORE.getExecutionInstance(instanceID) .getInstance().getInstanceSequence()); } } catch (Exception e) { throw new NotificationServiceException(e); } } }

Target:
public void unregister(NotificationHandler handler, ID listenerID) throws NotificationServiceException { if (listenerID instanceof InstanceID) { try { InstanceID instanceID = (InstanceID) listenerID; SortedMap<Integer, ExecutionInstance> instances = executorAwaitedInstances.get(instanceID .getEntityClusterID()); if (instances != null && !instances.isEmpty()) { synchronized (instances) { instances.remove(STATE_STORE.getExecutionInstance(instanceID) .getInstance().getInstanceSequence()); } } } catch (Exception e) { throw new NotificationServiceException(e); } } }
Source:
private String generateURL(String url, HashMap<String, String> properties) { if (properties.isEmpty()) return url; String encodedUrl = url + "?"; for (Map.Entry<String, String> map : properties.entrySet()) { try { encodedUrl += URLEncoder.encode(map.getKey(), ("utf-8")) + "=" + URLEncoder.encode(map.getValue(), "utf-8") + "&"; } catch (UnsupportedEncodingException e) { ZLog.logException(e); } } return encodedUrl.substring(0, encodedUrl.length() - 1); }

Target:
private String generateURL(String url, HashMap<String, String> properties) { if (properties.isEmpty()) return url; String encodedUrl = url + "?"; for (Map.Entry<String, String> map : properties.entrySet()) { try { encodedUrl += URLEncoder.encode(map.getKey(), ("utf-8")) + "=" + URLEncoder.encode(map.getValue(), "utf-8") + "&"; } catch (UnsupportedEncodingException e) { ZLog.logException(e); } } StringUtils.removeEnd(encodedUrl, "&"); return encodedUrl; }
Source:
public String toString() { return new ToStringBuilder(this) .append("enclosingClassNames", getEnclosingClassNames()) .append("nestedClassName", getNestedClassName()) .append("methodName", getMethodName()) .toString(); }

Target:
public String toString() { return new ToStringBuilder(this) .append("enclosingClassNames", getEnclosingClassNames()) .append("nestedClassName", getNestedClassName()) .append("methodName", getMethodName()) .append("methodParameterTypes", getMethodParameterTypes()) .toString(); }
Source:
public Object getSpmHost(String spUUID){ return this.spmMap.get(spUUID); }

Target:
public Host getSpmHost(String spUUID){ return this.spmMap.get(spUUID); }
Source:
protected void doExecute(Object[] targets, IProgressMonitor monitor, IRequest request) throws CoreException { Query<Boolean> connectQuery = new Query<Boolean>() { @Override public void execute(final DataRequestMonitor<Boolean> rm) { connect(new DataRequestMonitor<Boolean>(ImmediateExecutor.getInstance(), rm) { @Override @ConfinedToDsfExecutor("fExecutor") protected void handleCompleted() { super.handleCompleted(); updateEnablement(); } }); } }; try { fExecutor.execute(connectQuery); connectQuery.get(); } catch (InterruptedException e) { } catch (ExecutionException e) { } catch (CancellationException e) { } catch (RejectedExecutionException e) { } }

Target:
protected void doExecute(Object[] targets, IProgressMonitor monitor, IRequest request) throws CoreException { Query<Boolean> connectQuery = new Query<Boolean>() { @Override public void execute(DataRequestMonitor<Boolean> rm) { connect(rm); } }; try { fExecutor.execute(connectQuery); connectQuery.get(); } catch (InterruptedException e) { } catch (ExecutionException e) { } catch (CancellationException e) { } catch (RejectedExecutionException e) { } finally { updateEnablement(); } }
Source:
public ListImagesCmd withImageNameFilter(String imageNameFilter) { checkNotNull(imageNameFilter, "image name filter has not been specified"); this.imageNameFilter = imageNameFilter; return this; }

Target:
public ListImagesCmd withImageNameFilter(String imageNameFilter) { checkNotNull(imageNameFilter, "image name filter not specified"); this.imageNameFilter = imageNameFilter; return this; }
Source:
public static Integer compareGenesByKeyword(Gene g1, Gene g2, String keyword) { if (g1 == null) { return 1; } if (g2 == null) { return -1; } String s1 = ""; String s2 = ""; Integer i1 = -1; Integer i2 = -1; if (StringUtils.isNumeric(keyword)) { s1 = Integer.toString(g1.getEntrezGeneId()); s2 = Integer.toString(g2.getEntrezGeneId()); } else { s1 = g1.getHugoSymbol().toLowerCase(); s2 = g2.getHugoSymbol().toLowerCase(); } if (s1.equals(keyword)) { return -1; } if (s2.equals(keyword)) { return 1; } i1 = s1.indexOf(keyword); i2 = s2.indexOf(keyword); if (i1.equals(i2) && i1.equals(-1)) { Integer i1Alias = 100; Integer i2Alias = 100; Integer index = -1; for (String geneAlias : g1.getGeneAliases()) { index = geneAlias.toLowerCase().indexOf(keyword); if (index > -1 && index < i1Alias) { i1Alias = index; } } index = -1; for (String geneAlias : g2.getGeneAliases()) { index = geneAlias.toLowerCase().indexOf(keyword); if (index > -1 && index < i2Alias) { i2Alias = index; } } if (i1Alias.equals(-1)) return 1; if (i2Alias.equals(-1)) return -1; return -1; } else { if (i1.equals(-1)) return 1; if (i2.equals(-1)) return -1; if (i1.equals(i2)) { Integer result = s1.compareTo(s2); if (result == 0) { return -1; } else { return result; } } else { return i1 - i2; } } }

Target:
public static Integer compareGenesByKeyword(Gene g1, Gene g2, String keyword) { if (g1 == null) { return 1; } if (g2 == null) { return -1; } String s1 = ""; String s2 = ""; Integer i1 = -1; Integer i2 = -1; if (StringUtils.isNumeric(keyword)) { s1 = Integer.toString(g1.getEntrezGeneId()); s2 = Integer.toString(g2.getEntrezGeneId()); } else { s1 = g1.getHugoSymbol().toLowerCase(); s2 = g2.getHugoSymbol().toLowerCase(); } if (s1.equals(keyword)) { return -1; } if (s2.equals(keyword)) { return 1; } i1 = s1.indexOf(keyword); i2 = s2.indexOf(keyword); if (i1.equals(i2) && i1.equals(-1)) { Integer i1Alias = 100; Integer i2Alias = 100; Integer index = -1; for (String geneAlias : g1.getGeneAliases()) { index = geneAlias.toLowerCase().indexOf(keyword); if (index > -1 && index < i1Alias) { i1Alias = index; } } index = -1; for (String geneAlias : g2.getGeneAliases()) { index = geneAlias.toLowerCase().indexOf(keyword); if (index > -1 && index < i2Alias) { i2Alias = index; } } if (i1Alias.equals(-1)) return 1; if (i2Alias.equals(-1)) return -1; return i1Alias - i2Alias; } else { if (i1.equals(-1)) return 1; if (i2.equals(-1)) return -1; if (i1.equals(i2)) { Integer result = s1.compareTo(s2); if (result == 0) { return -1; } else { return result; } } else { return i1 - i2; } } }
Source:
XDRAcknowledgementType processDocSubmissionRequest(ProvideAndRegisterDocumentSetRequestType body, AssertionType assertion) { XDRAcknowledgementType response = null; String localHCID = getLocalHCID(); if (isPolicyValid(body, assertion, localHCID)) { try { LOG.debug("Policy Check Succeeded"); getDocSubmissionUtils().convertDataToFileLocationIfEnabled(body); response = sendToAdapter(body, assertion); } catch (LargePayloadException lpe) { LOG.error("Failed to retrieve payload document.", lpe); response = MessageGeneratorUtils.getInstance().createXDRAckWithRegistryErrorResponse(); } } else { LOG.error("Policy Check Failed"); response = sendErrorToAdapter(body, assertion, "Policy Check Failed"); } return response; }

Target:
XDRAcknowledgementType processDocSubmissionRequest(ProvideAndRegisterDocumentSetRequestType body, AssertionType assertion) { XDRAcknowledgementType response = null; String localHCID = getLocalHCID(); if (isPolicyValid(body, assertion, localHCID)) { try { LOG.debug("Policy Check Succeeded"); getDocSubmissionUtils().convertDataToFileLocationIfEnabled(body); response = sendToAdapter(body, assertion); } catch (LargePayloadException lpe) { LOG.error("Failed to retrieve payload document. " + lpe.getLocalizedMessage(), lpe); response = MessageGeneratorUtils.getInstance().createXDRAckWithRegistryErrorResponse(); } } else { LOG.error("Policy Check Failed"); response = sendErrorToAdapter(body, assertion, "Policy Check Failed"); } return response; }
Source:
public void initialise(FBOConfig inputFboConfig, FBOConfig outputFboConfig, BaseFBOsManager fboManager, float aRadius, String aLabel) { this.fboManager = fboManager; this.blurRadius = aRadius; this.performanceMonitorLabel = aLabel; this.inputFboUrn = inputFboConfig.getName(); this.outputFboUrn = outputFboConfig.getName(); inputFbo = requiresFBO(inputFboConfig, fboManager); outputFbo = requiresFBO(outputFboConfig, fboManager); addDesiredStateChange(new BindFBO(outputFboUrn, fboManager)); addDesiredStateChange(new SetViewportToSizeOf(outputFboUrn, fboManager)); setupConditions(); addDesiredStateChange(new EnableMaterial("engine:prog.blur")); this.blurMaterial = getMaterial(new ResourceUrn("engine:prog.blur")); fboManager.subscribe(this); }

Target:
public void initialise(FBOConfig inputFboConfig, FBOConfig outputFboConfig, BaseFBOsManager fboManager, float aRadius, String aLabel) { this.fboManager = fboManager; this.blurRadius = aRadius; this.performanceMonitorLabel = aLabel; this.inputFboUrn = inputFboConfig.getName(); this.outputFboUrn = outputFboConfig.getName(); setupConditions(); requiresFBO(inputFboConfig, fboManager); requiresFBO(outputFboConfig, fboManager); addDesiredStateChange(new BindFBO(outputFboUrn, fboManager)); addDesiredStateChange(new SetViewportToSizeOf(outputFboUrn, fboManager)); update(); fboManager.subscribe(this); addDesiredStateChange(new EnableMaterial("engine:prog.blur")); this.blurMaterial = getMaterial(new ResourceUrn("engine:prog.blur")); }
Source:
InstallIDProvider providesInstallIDProvider(Context context) { SharedPreferences preferences = context.getSharedPreferences("meta", Context.MODE_PRIVATE); return new SharedPreferencesInstallIDProvider(preferences, KEY_INSTALL_ID); }

Target:
InstallIDProvider providesInstallIDProvider(Context context) { SharedPreferences prefs = new MetaSharedPreferencesProvider(context).getMetaSharedPreferences(); return new SharedPreferencesInstallIDProvider(prefs, KEY_INSTALL_ID); }
Source:
public void verifyCreateAPageEditor(Editor expectedEditor, String articleName) { switch (expectedEditor) { case VE: VisualEditorPageObject ve = createArticleInVEUsingDropdown(articleName); ve.verifyVEToolBarPresent(); ve.verifyEditorSurfacePresent(); break; case CK: VisualEditModePageObject ck = createArticleInCKUsingDropdown(articleName); ck.isContentLoaded(); ck.clickPublishButton(); break; case SRC: SourceEditModePageObject src = createArticleInSrcUsingDropdown(articleName); src.verifySourceOnlyMode(); src.clickPublishButton(); break; } }

Target:
public void verifyCreateAPageEditor(Editor expectedEditor, String articleName) { switch (expectedEditor) { case VE: VisualEditorPageObject ve = createArticleInVEUsingDropdown(articleName); ve.verifyVEToolBarPresent(); ve.verifyEditorSurfacePresent(); break; case CK: VisualEditModePageObject ck = createArticleInCKUsingDropdown(articleName); Assertion.assertTrue(ck.isContentLoaded(), "Content is not loaded"); ck.clickPublishButton(); break; case SRC: SourceEditModePageObject src = createArticleInSrcUsingDropdown(articleName); src.verifySourceOnlyMode(); src.clickPublishButton(); break; } }
Source:
public void testConflictingSnapshotVersionUpdate() throws Exception { accountService = mockHelixAccountServiceFactory.getAccountService(); writeAccountsForConflictTest(); Account expectedAccount = accountService.getAccountById((short) 1); for (int snapshotVersion : new int[]{-1, 0, 2}) { Collection<Account> conflictAccounts = Collections.singleton( new AccountBuilder((short) 1, "a", AccountStatus.INACTIVE).snapshotVersion(snapshotVersion).build()); assertFalse("Wrong return value from update operation.", accountService.updateAccounts(conflictAccounts)); assertEquals("Wrong account number in HelixAccountService", 2, accountService.getAllAccounts().size()); assertEquals("Account should not have been updated", expectedAccount, accountService.getAccountById((short) 1)); } Collection<Account> validAccounts = Collections.singleton(new AccountBuilder((short) 1, "a", AccountStatus.INACTIVE).snapshotVersion(1).build()); updateAccountsAndAssertAccountExistence(validAccounts, 2, true); }

Target:
public void testConflictingSnapshotVersionUpdate() throws Exception { accountService = mockHelixAccountServiceFactory.getAccountService(); writeAccountsForConflictTest(); Account expectedAccount = accountService.getAccountById((short) 1); int currentSnapshotVersion = expectedAccount.getSnapshotVersion(); for (int snapshotVersionOffset : new int[]{-2, -1, 1}) { int snapshotVersionToUse = currentSnapshotVersion + snapshotVersionOffset; Collection<Account> conflictAccounts = Collections.singleton( new AccountBuilder((short) 1, "c", AccountStatus.INACTIVE).snapshotVersion(snapshotVersionToUse).build()); assertFalse("Wrong return value from update operation.", accountService.updateAccounts(conflictAccounts)); assertEquals("Wrong account number in HelixAccountService", 2, accountService.getAllAccounts().size()); Account account = accountService.getAccountById((short) 1); assertEquals("Account should not have been updated", expectedAccount, account); assertEquals("Snapshot version should not have been updated", currentSnapshotVersion, account.getSnapshotVersion()); } Collection<Account> validAccounts = Collections.singleton( new AccountBuilder((short) 1, "c", AccountStatus.INACTIVE).snapshotVersion(currentSnapshotVersion).build()); updateAccountsAndAssertAccountExistence(validAccounts, 2, true); }