auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void configureRepositories(Project project) { project.getRepositories().all(repository -> { if (repository instanceof MavenArtifactRepository) { final MavenArtifactRepository maven = (MavenArtifactRepository) repository; assertRepositoryURIIsSecure(maven.getName(), project.getPath(), maven.getUrl()); for (URI uri : maven.getArtifactUrls()) { assertRepositoryURIIsSecure(maven.getName(), project.getPath(), uri); } } else if (repository instanceof IvyArtifactRepository) { final IvyArtifactRepository ivy = (IvyArtifactRepository) repository; assertRepositoryURIIsSecure(ivy.getName(), project.getPath(), ivy.getUrl()); } }); RepositoryHandler repos = project.getRepositories(); if (System.getProperty("repos.mavenLocal") != null) { repos.mavenLocal(); } repos.jcenter(); String luceneVersion = VersionProperties.getLucene(); if (luceneVersion.contains("-snapshot")) { Matcher matcher = LUCENE_SNAPSHOT_REGEX.matcher(luceneVersion); if (matcher.find() == false) { throw new GradleException("Malformed lucene snapshot version: " + luceneVersion); } String revision = matcher.group(1); MavenArtifactRepository luceneRepo = repos.maven(repo -> { repo.setName("lucene-snapshots"); repo.setUrl("<LINK_0>" + revision); }); repos.exclusiveContent(exclusiveRepo -> { exclusiveRepo.filter(descriptor -> { descriptor.includeVersionByRegex("org\\.apache\\.lucene", ".*", ".*-snapshot-" + revision); }); exclusiveRepo.forRepositories(luceneRepo); }); } }

Target:
public static void configureRepositories(Project project) { project.getRepositories().all(repository -> { if (repository instanceof MavenArtifactRepository) { final MavenArtifactRepository maven = (MavenArtifactRepository) repository; assertRepositoryURIIsSecure(maven.getName(), project.getPath(), maven.getUrl()); for (URI uri : maven.getArtifactUrls()) { assertRepositoryURIIsSecure(maven.getName(), project.getPath(), uri); } } else if (repository instanceof IvyArtifactRepository) { final IvyArtifactRepository ivy = (IvyArtifactRepository) repository; assertRepositoryURIIsSecure(ivy.getName(), project.getPath(), ivy.getUrl()); } }); RepositoryHandler repos = project.getRepositories(); if (System.getProperty("repos.mavenLocal") != null) { repos.mavenLocal(); } repos.jcenter(); String luceneVersion = VersionProperties.getLucene(); if (luceneVersion.contains("-snapshot")) { Matcher matcher = LUCENE_SNAPSHOT_REGEX.matcher(luceneVersion); if (matcher.find() == false) { throw new GradleException("Malformed lucene snapshot version: " + luceneVersion); } String revision = matcher.group(1); MavenArtifactRepository luceneRepo = repos.maven(repo -> { repo.setName("lucene-snapshots"); repo.setUrl("<LINK_0>" + revision); }); repos.exclusiveContent(exclusiveRepo -> { exclusiveRepo.filter( descriptor -> descriptor.includeVersionByRegex("org\\.apache\\.lucene", ".*", ".*-snapshot-" + revision) ); exclusiveRepo.forRepositories(luceneRepo); }); } }
Source:
public static Repository getRepository(ExecutionEvent event) { ISelection selection = HandlerUtil.getCurrentSelection(event); IEditorInput editorInput = HandlerUtil.getActiveEditorInput(event); return getRepository(selection, editorInput); }

Target:
public static Repository getRepository(ExecutionEvent event) { ISelection selection = HandlerUtil.getCurrentSelection(event); IEditorInput editorInput = getActiveEditorInput(event); return getRepository(selection, editorInput); }
Source:
public String toString() { if (this.equals(ANY_VALUE)) { return "ANY_VALUE"; } else if (this.equals(NO_POSSIBLE_VALUE)) { return "NO_POSSIBLE_VALUE"; } else if (this.equals(TRUTHY)) { return "TRUTHY"; } else if (this.equals(FALSY)) { return "FALSY"; } else { StringBuilder result = new StringBuilder(); for (SubConstraint subConstraint : SubConstraint.values()) { if ((this.bitSet & subConstraint.bitSet) == subConstraint.bitSet) { result.append("|").append(subConstraint.toString()); } } return result.substring(1); } }

Target:
public String toString() { String name = COMMON_CONSTRAINT_NAMES.get(this); if (name != null) { return name; } StringBuilder result = new StringBuilder(); for (ValueSubSet subSet : ValueSubSet.values()) { if ((this.bitSet & subSet.bitSet()) == subSet.bitSet()) { result.append("|").append(subSet); } } return result.substring(1); }
Source:
protected void deallocate(Event event) { log.info("Deallocating [{}:{}]", event.getResourceType(), event.getResourceId()); AllocationRequest request = new AllocationRequest(event); try { allocator.deallocate(request); log.info("Deallocator handled request [{}]", allocator, request); eventService.publish(EventVO.reply(event)); } catch (AllocationException e) { String errorMessage = "Failed to deallocate: " + e.getMessage(); eventService.publish(EventVO.reply(event).withTransitioningMessage(errorMessage).withTransitioning(Event.TRANSITIONING_ERROR)); } eventService.publish(EventVO.reply(event)); }

Target:
protected void deallocate(Event event) { log.info("Deallocating [{}:{}]", event.getResourceType(), event.getResourceId()); AllocationRequest request = new AllocationRequest(event); try { allocator.deallocate(request); log.info("Deallocator handled request [{}]", allocator, request); eventService.publish(EventVO.reply(event)); } catch (FailedToAllocate e) { String errorMessage = "Failed to deallocate: " + e.getMessage(); eventService.publish(EventVO.reply(event).withTransitioningMessage(errorMessage).withTransitioning(Event.TRANSITIONING_ERROR)); } }
Source:
public void edit(final VnicProfileModel model) { driver.edit(model); publicInfo.setVisible(model.getPublicUse().getIsAvailable()); nameEditor.addKeyPressHandler(new KeyPressHandler() { @Override public void onKeyPress(KeyPressEvent event) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { ValueChangeEvent.fire(nameEditor.asValueBox(), nameEditor.asValueBox().getValue()); } }); } }); nameEditor.asValueBox().addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { ValueChangeEvent.fire(VnicProfileWidget.this, model); } }); model.getName().getEntityChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { ValueChangeEvent.fire(VnicProfileWidget.this, model); } }); }

Target:
public void edit(final VnicProfileModel model) { driver.edit(model); publicInfo.setVisible(model.getPublicUse().getIsAvailable()); nameEditor.addKeyPressHandler(new KeyPressHandler() { @Override public void onKeyPress(KeyPressEvent event) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { ValueChangeEvent.fire(nameEditor.asValueBox(), nameEditor.asValueBox().getValue()); } }); } }); nameEditor.asValueBox().addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { ValueChangeEvent.fire(VnicProfileWidget.this, model); } }); }
Source:
public ListenableFuture<AckingContainer> poll(boolean forcePollSchema) { final SettableFuture<AckingContainer> fut = SettableFuture.create(false); PollTask pollTask = new PollTask(fut, forcePollSchema); try { m_es.execute(new Runnable() { @Override public void run() { if (!m_mastershipAccepted.get()) { try { pollTask.clear(); } catch (RejectedExecutionException rej) { } m_pollTask = null; return; } try { if (m_pollTask != null) { fut.setException(new ReentrantPollException("Reentrant poll detected: InCat = " + m_isInCatalog + " In " + ExportDataSource.this.toString())); return; } if (!m_es.isShutdown()) { pollImpl(pollTask); } } catch (Exception e) { exportLog.error("Exception polling export buffer", e); } catch (Error e) { VoltDB.crashLocalVoltDB("Error polling export buffer", true, e); } } }); } catch (RejectedExecutionException rej) { exportLog.info("Polling from export data source rejected."); } return fut; }

Target:
public ListenableFuture<AckingContainer> poll(boolean forcePollSchema) { final SettableFuture<AckingContainer> fut = SettableFuture.create(false); PollTask pollTask = new PollTask(fut, forcePollSchema); try { m_es.execute(new Runnable() { @Override public void run() { if (m_pollTask != null) { try { pollTask.setException( new ReentrantPollException("Reentrant poll detected: InCat = " + m_isInCatalog + " In " + ExportDataSource.this.toString())); } catch (RejectedExecutionException reex) { } return; } if (!m_mastershipAccepted.get()) { try { pollTask.clear(); } catch (RejectedExecutionException rej) { } return; } try { if (!m_es.isShutdown()) { pollImpl(pollTask); } } catch (Exception e) { exportLog.error("Exception polling export buffer", e); } catch (Error e) { VoltDB.crashLocalVoltDB("Error polling export buffer", true, e); } } }); } catch (RejectedExecutionException rej) { exportLog.info("Polling from export data source rejected."); } return fut; }
Source:
private void traceRequest(final RequestLogInfo requestLogInfo, final int statusCode, final Long timeSpentMs) { if ("POST".equals(requestLogInfo.method) && requestLogInfo.path.startsWith("/event-types/") && requestLogInfo.path.contains("/events")) { final String eventType = requestLogInfo.path.substring("/event-types/".length(), requestLogInfo.path.lastIndexOf("/events")); String sloBucket = "5K-50K"; if (requestLogInfo.contentLength < 5000) { sloBucket = "<5K"; } else if (requestLogInfo.contentLength > 50000) { sloBucket = ">50K"; } GlobalTracer.get() .buildSpan("publish_events") .withStartTimestamp(TimeUnit.MILLISECONDS.toMicros(requestLogInfo.requestTime)) .start() .setTag("client_id", requestLogInfo.user) .setTag("event_type", eventType) .setTag("error", statusCode == 207 || statusCode >= 500) .setTag("http.status_code", statusCode) .setTag("http.url", requestLogInfo.path + requestLogInfo.query) .setTag("http.header.content_encoding", requestLogInfo.contentEncoding) .setTag("http.header.accept_encoding", requestLogInfo.acceptEncoding) .setTag("http.header.user_agent", requestLogInfo.userAgent) .setTag("slo_bucket", sloBucket) .setTag("content_length", requestLogInfo.contentLength) .finish(TimeUnit.MILLISECONDS.toMicros(requestLogInfo.requestTime + timeSpentMs)); } }

Target:
private void traceRequest(final RequestLogInfo requestLogInfo, final int statusCode, final Long timeSpentMs) { if (requestLogInfo.path != null && "POST".equals(requestLogInfo.method) && requestLogInfo.path.startsWith("/event-types/") && requestLogInfo.path.contains("/events")) { final String eventType = requestLogInfo.path.substring("/event-types/".length(), requestLogInfo.path.lastIndexOf("/events")); String sloBucket = "5K-50K"; if (requestLogInfo.contentLength < 5000) { sloBucket = "<5K"; } else if (requestLogInfo.contentLength > 50000) { sloBucket = ">50K"; } GlobalTracer.get() .buildSpan("publish_events") .withStartTimestamp(TimeUnit.MILLISECONDS.toMicros(requestLogInfo.requestTime)) .start() .setTag("client_id", requestLogInfo.user) .setTag("event_type", eventType) .setTag("error", statusCode == 207 || statusCode >= 500) .setTag("http.status_code", statusCode) .setTag("http.url", requestLogInfo.path + requestLogInfo.query) .setTag("http.header.content_encoding", requestLogInfo.contentEncoding) .setTag("http.header.accept_encoding", requestLogInfo.acceptEncoding) .setTag("http.header.user_agent", requestLogInfo.userAgent) .setTag("slo_bucket", sloBucket) .setTag("content_length", requestLogInfo.contentLength) .finish(TimeUnit.MILLISECONDS.toMicros(requestLogInfo.requestTime + timeSpentMs)); } }
Source:
protected List<VmStatic> filterVmsInClusterNeedUpdate() { List<VmStatic> allVms = vmStaticDao.getAllByCluster(getCluster().getId()); Set<VmStatic> vmSet = allVms.stream() .filter(vm -> vm.getOrigin() != OriginType.EXTERNAL && !vm.isHostedEngine()) .filter(vm -> vm.getCustomCompatibilityVersion() == null) .collect(Collectors.toSet()); try { if (FeatureSupported.isBiosTypeSupported(getCluster().getCompatibilityVersion()) && oldCluster.getBiosType() != getCluster().getBiosType()) { allVms.stream() .filter(vm -> vm.getOrigin() != OriginType.EXTERNAL) .filter(vm -> vm.getBiosType() == BiosType.CLUSTER_DEFAULT) .forEach(vmSet::add); } } catch (IllegalArgumentException e) { } return vmSet.stream() .sorted() .collect(Collectors.toList()); }

Target:
protected List<VmStatic> filterVmsInClusterNeedUpdate() { final boolean biosTypeChanged = isBiosTypeChanged(); return vmStaticDao.getAllByCluster(getCluster().getId()).stream() .filter(vm -> vm.getOrigin() != OriginType.EXTERNAL && !vm.isHostedEngine()) .filter(vm -> vm.getCustomCompatibilityVersion() == null || biosTypeChanged && vm.getBiosType() == BiosType.CLUSTER_DEFAULT) .sorted() .collect(Collectors.toList()); }
Source:
public void onFailure(final Throwable caught) { if (isNotSignedIn(caught) || isInvalidXSRF(caught)) { new NotSignedInDialog().center(); } else if (isNoSuchEntity(caught)) { new ErrorDialog(Gerrit.C.notFoundBody()).center(); } else if (isInactiveAccount(caught)) { new ErrorDialog(Gerrit.C.inactiveAccountBody()).center(); } else if (isNoSuchAccount(caught)) { final String msg = caught.getMessage(); final String who = msg.substring(NoSuchAccountException.MESSAGE.length()); final ErrorDialog d = new ErrorDialog(Gerrit.M.noSuchAccountMessage(who)); d.setText(Gerrit.C.noSuchAccountTitle()); d.center(); } else if (isNameAlreadyUsed(caught)) { new ErrorDialog(Gerrit.C.nameAlreadyUsedBody()).center(); } else if (caught instanceof ServerUnavailableException) { new ErrorDialog(RpcConstants.C.errorServerUnavailable()).center(); } else if (isForbiddenRefRight(caught)) { final String msg = caught.getMessage(); final String allows = msg.substring(ForbiddenRefRightException.MESSAGE.length()); String err; if (allows.length() > 0) { err = Gerrit.M.forbiddenRefRight1(allows); } else { err = Gerrit.M.forbiddenRefRight2(); } final ErrorDialog d = new ErrorDialog(err); d.setText(Gerrit.C.forbidden()); d.center(); } else if (isInvalidRegExp(caught)) { final String msg = caught.getMessage(); final String regExp = msg.substring(InvalidRegExpException.MESSAGE.length()); final ErrorDialog d = new ErrorDialog(regExp); d.setText(Gerrit.C.invalidRegExp()); d.center(); } else { GWT.log(getClass().getName() + " caught " + caught, caught); new ErrorDialog(caught).center(); } }

Target:
public void onFailure(final Throwable caught) { if (isNotSignedIn(caught) || isInvalidXSRF(caught)) { new NotSignedInDialog().center(); } else if (isNoSuchEntity(caught)) { new ErrorDialog(Gerrit.C.notFoundBody()).center(); } else if (isInactiveAccount(caught)) { new ErrorDialog(Gerrit.C.inactiveAccountBody()).center(); } else if (isNoSuchAccount(caught)) { final String msg = caught.getMessage(); final String who = msg.substring(NoSuchAccountException.MESSAGE.length()); final ErrorDialog d = new ErrorDialog(Gerrit.M.noSuchAccountMessage(who)); d.setText(Gerrit.C.noSuchAccountTitle()); d.center(); } else if (isNameAlreadyUsed(caught)) { new ErrorDialog(Gerrit.C.nameAlreadyUsedBody()).center(); } else if (isNoSuchGroup(caught)) { final String msg = caught.getMessage(); final String group = msg.substring(NoSuchGroupException.MESSAGE.length()); final ErrorDialog d = new ErrorDialog(Gerrit.M.noSuchGroupMessage(group)); d.setText(Gerrit.C.noSuchGroupTitle()); d.center(); } else if (caught instanceof ServerUnavailableException) { new ErrorDialog(RpcConstants.C.errorServerUnavailable()).center(); } else if (isRuleNotAllowed(caught)) { final String msg = caught.getMessage(); final String rule = msg.substring(RuleNotAllowedException.MESSAGE.length()); final ErrorDialog d = new ErrorDialog(Gerrit.M.ruleNotAllowedMessage(rule)); d.setText(Gerrit.C.ruleNotAllowedTitle()); } else { GWT.log(getClass().getName() + " caught " + caught, caught); new ErrorDialog(caught).center(); } }
Source:
private void handleLogReplicationEntry(CorfuPayloadMsg<LogReplicationEntry> msg, ChannelHandlerContext ctx, IServerRouter r) { log.info("Log Replication Entry received by Server."); if (isLeader(msg, r)) { LogReplicationEntry ack = sinkManager.receive(msg.getPayload()); if (ack != null) { long ts = ack.getMetadata().getMessageMetadataType().equals(MessageType.LOG_ENTRY_REPLICATED) ? ack.getMetadata().getTimestamp() : ack.getMetadata().getSnapshotTimestamp(); log.info("Sending ACK on to Client ", ack.getMetadata(), ts); r.sendResponse(msg, CorfuMsgType.LOG_REPLICATION_ENTRY.payloadMsg(ack)); } } }

Target:
private void handleLogReplicationEntry(CorfuPayloadMsg<LogReplicationEntry> msg, ChannelHandlerContext ctx, IServerRouter r) { log.trace("Log Replication Entry received by Server."); if (isLeader(msg, r)) { LogReplicationEntry ack = sinkManager.receive(msg.getPayload()); if (ack != null) { long ts = ack.getMetadata().getMessageMetadataType().equals(MessageType.LOG_ENTRY_REPLICATED) ? ack.getMetadata().getTimestamp() : ack.getMetadata().getSnapshotTimestamp(); log.info("Sending ACK on to Client ", ack.getMetadata(), ts); r.sendResponse(msg, CorfuMsgType.LOG_REPLICATION_ENTRY.payloadMsg(ack)); } } }
Source:
private void render(DiffInfo diff) { JsArray<Region> regions = diff.content(); int lineA = 0, lineB = 0; for (int i = 0; i < regions.length(); i++) { Region current = regions.get(i); if (current.ab() != null) { lineA += current.ab().length(); lineB += current.ab().length(); } else if (current.a() == null && current.b() != null) { int delta = current.b().length(); padLines(cmA, delta, lineA - 1); lineB = colorLine(delta, lineA, lineB, true); } else if (current.a() != null && current.b() == null) { int delta = current.a().length(); padLines(cmB, delta, lineB - 1); lineA = colorLine(delta, lineA, lineB, false); } else { lineA = colorLine(current.a().length(), lineA, lineB, false); lineB = colorLine(current.b().length(), lineA, lineB, true); } } }

Target:
private void render(DiffInfo diff) { JsArray<Region> regions = diff.content(); int lineA = 0, lineB = 0; for (int i = 0; i < regions.length(); i++) { Region current = regions.get(i); if (current.ab() != null) { lineA += current.ab().length(); lineB += current.ab().length(); } else if (current.a() == null && current.b() != null) { int delta = current.b().length(); padLines(cmA, delta, lineA - 1); lineB = colorLine(delta, lineB, true); } else if (current.a() != null && current.b() == null) { int delta = current.a().length(); padLines(cmB, delta, lineB - 1); lineA = colorLine(delta, lineA, false); } else { lineA = colorLine(current.a().length(), lineA, false); lineB = colorLine(current.b().length(), lineB, true); } } }
Source:
private static void printPowerSources(PowerSource[] powerSources) { StringBuilder sb = new StringBuilder("Power: "); if (powerSources.length == 0) { sb.append("Unknown"); } else { double timeRemaining = powerSources[0].getTimeRemaining(); if (timeRemaining < -1d) { sb.append("Charging"); } else if (timeRemaining < 0d) { sb.append("Calculating time remaining"); } else { sb.append(String.format("%d:%02d remaining", (int) (timeRemaining / 3600), (int) (timeRemaining / 60) % 60)); } } for (PowerSource powerSource : powerSources) { sb.append(powerSource.toString()); } oshi.add(sb.toString()); }

Target:
private static void printPowerSources(PowerSource[] powerSources) { StringBuilder sb = new StringBuilder("Power: "); if (powerSources.length == 0) { sb.append("Unknown"); } for (PowerSource powerSource : powerSources) { sb.append("\n ").append(powerSource.toString()); } oshi.add(sb.toString()); }
Source:
public void testInterfaceDefaultMethodBreakpoint() throws Exception { Listener listener = new Listener(); IBreakpointManager manager = getBreakpointManager(); manager.addBreakpointListener(listener); try { Path path = new Path("java8/EvalTestIntf18.java"); toggleBreakpoint(path, 20); IBreakpoint added = listener.getAdded(); assertTrue("Should be a method breakpoint", added instanceof IJavaMethodBreakpoint); IJavaMethodBreakpoint breakpoint = (IJavaMethodBreakpoint) added; assertEquals("Wrong type name", "Intf18", breakpoint.getTypeName()); assertEquals("Wrong method name", "test2", breakpoint.getMethodName()); assertEquals("Wrong signature", "()I", breakpoint.getMethodSignature()); TestUtil.waitForJobs(getName(), 100, DEFAULT_TIMEOUT); } finally { manager.removeBreakpointListener(listener); removeAllBreakpoints(); } }

Target:
public void testInterfaceDefaultMethodBreakpoint() throws Exception { Listener listener = new Listener(); IBreakpointManager manager = getBreakpointManager(); manager.addBreakpointListener(listener); try { Path path = new Path("java8/EvalTestIntf18.java"); toggleBreakpoint(path, 20); TestUtil.waitForJobs(getName(), 100, DEFAULT_TIMEOUT); IBreakpoint added = listener.getAdded(); assertTrue("Should be a method breakpoint", added instanceof IJavaMethodBreakpoint); IJavaMethodBreakpoint breakpoint = (IJavaMethodBreakpoint) added; assertEquals("Wrong type name", "Intf18", breakpoint.getTypeName()); assertEquals("Wrong method name", "test2", breakpoint.getMethodName()); assertEquals("Wrong signature", "()I", breakpoint.getMethodSignature()); } finally { manager.removeBreakpointListener(listener); removeAllBreakpoints(); } }
Source:
public double[] getTargetFactors() { final double[] values = file.readDoubleArray(TARGET_FACTORS_PATH); if (values.length != targetNames.get().size()) { throw new GATKException(String.format("Wrong number of elements in the target factors recovered " + "from file '%s': %d != %d", file.getFile(), values.length, targetNames.get().size())); } return values; }

Target:
public double[] getTargetFactors() { final double[] values = file.readDoubleArray(TARGET_FACTORS_PATH); if (values.length != targetNames.get().size()) { throw new GATKException(String.format("Wrong number of elements in the target factors recovered " + "from file '%s': number of target factors found in file (%d) != number of target names (%d)", file.getFile(), values.length, targetNames.get().size())); } return values; }
Source:
public void addContent(String content) { driver.switchTo().frame(iframe); contentInput.clear(); contentInput.sendKeys(content); driver.switchTo().defaultContent(); }

Target:
public void addContent(String content) { driver.switchTo().frame(iframe); contentInput.clear(); contentInput.sendKeys(content); driver.switchTo().defaultContent(); PageObjectLogging.log("addContent", "content " + content + " added to the article", true); }
Source:
public static String parseSessionId(String legend) { if (legend.startsWith("#")) { return legend.substring(legend.indexOf('#'), legend.indexOf(':')); } return ""; }

Target:
public static String parseSessionId(String legend) { if (legend.startsWith(SESSION_PREFIX)) { return legend.substring(legend.indexOf(SESSION_PREFIX), legend.indexOf(LEGEND_DESCRIPTION_SEPARATOR)); } return ""; }
Source:
public Response getAllRefunds(UriInfo uriInfo, SearchParams searchParams) { RefundSearchStrategy refundSearchStrategy = new RefundSearchStrategy(refundDao); return refundSearchStrategy.search(searchParams, uriInfo); }

Target:
public Response getAllRefunds(UriInfo uriInfo, SearchParams searchParams) { refundSearchStrategy = new RefundSearchStrategy(refundDao); return refundSearchStrategy.search(searchParams, uriInfo); }
Source:
private Map<String, DashboardInfo> allDashboardsFor(ProjectState projectState) { final Project.NameKey projectName = projectState.getProject().getNameKey(); Project.NameKey parent; Map<String, DashboardInfo> dashboards = Maps.newTreeMap(); Set<Project.NameKey> seen = new HashSet<Project.NameKey>(); seen.add(projectName); do { dashboards = addProjectDashboards(projectState, dashboards); parent = projectState.getProject().getParent(); if (parent == null || !seen.add(parent)) { break; } projectState = projectCache.get(parent); } while (projectState != null); projectState = projectCache.getAllProjects(); parent = projectState.getProject().getNameKey(); if (seen.add(parent)) { dashboards = addProjectDashboards(projectState, dashboards); } return dashboards; }

Target:
private Map<String, DashboardInfo> allDashboardsFor(ProjectState projectState) { final Project.NameKey projectName = projectState.getProject().getNameKey(); Project.NameKey parent; Map<String, DashboardInfo> dashboards = Maps.newTreeMap(); Set<Project.NameKey> seen = new HashSet<Project.NameKey>(); seen.add(projectName); do { dashboards = addProjectDashboards(projectState, dashboards); parent = projectState.getProject().getParent(allProjects); projectState = projectCache.get(parent); } while (projectState != null && seen.add(parent)); return dashboards; }
Source:
public boolean apply(BlockRayHit lastHit) { return !lastHit.getBlockPosition().equals(this.target); }

Target:
public boolean apply(BlockRayHit lastHit) { return lastHit.getBlockX() != this.target.getX() || lastHit.getBlockY() != this.target.getY() || lastHit.getBlockZ() != this.target.getZ(); }
Source:
public List<Statement> createAttributeStatements(final CallbackProperties properties, final Subject subject) { final List<Statement> statements = new ArrayList<>(); statements.add(createAuthenicationStatements(properties)); statements.add(createSubjectIdAttributeStatement(properties)); statements.add(createOrganizationAttributeStatements(properties)); statements.add(createSubjectRoleStatement(properties)); statements.add(createPurposeOfUseStatements(properties)); statements.add(createHomeCommunityIdAttributeStatement(properties)); statements.add(createOrganizationIdAttributeStatement(properties)); statements.add(createResourceIdAttributeStatement(properties)); statements.add(createNPIAttributeStatement(properties)); statements.addAll(createAcpAttributeStatements(properties)); if (isAcpOrIacpExists(properties)) { statements.add(createAuthorizationDecisionStatements(properties, subject)); } return statements; }

Target:
public List<Statement> createAttributeStatements(final CallbackProperties properties, final Subject subject) { final List<Statement> statements = new ArrayList<>(); addOptionalStatement(statements, createAuthenicationStatements(properties)); addOptionalStatement(statements, createSubjectIdAttributeStatement(properties)); addOptionalStatement(statements, createOrganizationAttributeStatement(properties)); addOptionalStatement(statements, createSubjectRoleStatement(properties)); addOptionalStatement(statements, createPurposeOfUseStatement(properties)); addOptionalStatement(statements, createHomeCommunityIdAttributeStatement(properties)); addOptionalStatement(statements, createOrganizationIdAttributeStatement(properties)); addOptionalStatement(statements, createResourceIdAttributeStatement(properties)); addOptionalStatement(statements, createNPIAttributeStatement(properties)); addOptionalAttributeStatements(statements, createAcpAttributeStatements(properties)); if (isAcpOrIacpExists(properties)) { addOptionalStatement(statements, createAuthorizationDecisionStatement(properties, subject)); } return statements; }
Source:
public void handleForeignKeyAdd(DDLChange ddlChange, long onConglomerateNumber) { TentativeFK tentativeFKAdd = ddlChange.getTentativeFK(); if (onConglomerateNumber == tentativeFKAdd.getReferencedConglomerateNumber()) { addParentInterceptWriteFactory(tentativeFKAdd.getReferencedTableName(), ImmutableList.of(tentativeFKAdd.getReferencingConglomerateNumber()), ImmutableList.of(tentativeFKAdd.getFkConstraintInfo().getTable().getConglomerate()),ImmutableList.of(tentativeFKAdd.getFkConstraintInfo())); } if (onConglomerateNumber == tentativeFKAdd.getReferencingConglomerateNumber()) { addChildIntercept(tentativeFKAdd.getReferencedConglomerateNumber(), tentativeFKAdd.getFkConstraintInfo()); } }

Target:
public void handleForeignKeyAdd(DDLChange ddlChange, long onConglomerateNumber) { TentativeFK tentativeFKAdd = ddlChange.getTentativeFK(); if (onConglomerateNumber == tentativeFKAdd.getReferencedConglomerateNumber()) { addParentInterceptWriteFactory(tentativeFKAdd.getReferencedTableName(), ImmutableList.of(tentativeFKAdd.getReferencingConglomerateNumber()), ImmutableList.of(tentativeFKAdd.getFkConstraintInfo())); } if (onConglomerateNumber == tentativeFKAdd.getReferencingConglomerateNumber()) { addChildIntercept(tentativeFKAdd.getReferencedConglomerateNumber(), tentativeFKAdd.getFkConstraintInfo()); } }
Source:
protected List<MethodHandle> getMethodHandles(RowType type, FunctionManager functionManager, OperatorType operatorType) { ImmutableList.Builder<MethodHandle> argumentMethods = ImmutableList.builder(); for (Type parameterType : type.getTypeParameters()) { FunctionHandle operator = functionManager.resolveOperator(operatorType, ImmutableList.of(parameterType, parameterType)); argumentMethods.add(functionManager.getScalarFunctionImplementation(operator).getMethodHandle()); } return argumentMethods.build(); }

Target:
protected List<MethodHandle> getMethodHandles(RowType type, FunctionManager functionManager, OperatorType operatorType) { ImmutableList.Builder<MethodHandle> argumentMethods = ImmutableList.builder(); for (Type parameterType : type.getTypeParameters()) { FunctionHandle operatorHandle = functionManager.resolveOperator(operatorType, ImmutableList.of(parameterType, parameterType)); argumentMethods.add(functionManager.getScalarFunctionImplementation(operatorHandle).getMethodHandle()); } return argumentMethods.build(); }
Source:
public EditionLimiter(TextViewer viewer) { this.textViewer = viewer; textViewer.getTextWidget().addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { if (((e.stateMask & SWT.CTRL) == SWT.CTRL) && (e.keyCode == 'd')) { triggeredFromWidget = true; Point currentlocation = e.widget.getDisplay().getCursorLocation(); Control currentcontrol = e.widget.getDisplay().getCursorControl(); StyledText txt = (StyledText) e.getSource(); int lineLength = 0; int caretOffset = txt.getCaretOffset(); if (document == null) { initialize(); } try { int lineNo = document.getLineOfOffset(caretOffset); lineLength = document.getLineLength(lineNo); } catch (BadLocationException e1) { e1.printStackTrace(); } isDeleteLine = true; doit(txt.getCaretOffset(), lineLength, "", true, true); try { document.replace(txt.getCaretOffset(), lineLength, ""); } catch (BadLocationException e1) { e1.printStackTrace(); } isDeleteLine = false; lastTextForShortCircuiting = null; triggeredFromWidget = false; } } @Override public void keyReleased(KeyEvent e) { } }); }

Target:
public EditionLimiter(TextViewer viewer) { this.textViewer = viewer; textViewer.getTextWidget().addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { if (((e.stateMask & SWT.CTRL) == SWT.CTRL) && (e.keyCode == 'd')) { triggeredFromWidget = true; StyledText txt = (StyledText) e.getSource(); int lineLength = 0; int lineNo = 0; int caretOffset = txt.getCaretOffset(); if (document == null) { initialize(); } try { lineNo = document.getLineOfOffset(caretOffset); lineLength = document.getLineLength(lineNo); } catch (BadLocationException e1) { logger.debug("Exception inserting " + "Could not obtain line info", e1); } try { if (!isEditableLine(document.getLineOffset(lineNo), 1)) { return; } } catch (BadLocationException e2) { logger.debug("Exception inserting " + "Could not check if editable", e2); } isDeleteLine = true; doit(caretOffset, lineLength, "", false, true); try { document.replace(document.getLineOffset(lineNo), lineLength, ""); } catch (BadLocationException e1) { logger.debug("Exception inserting " + "Could not replace text", e1); } isDeleteLine = false; lastTextForShortCircuiting = null; triggeredFromWidget = false; } } @Override public void keyReleased(KeyEvent e) { } }); }
Source:
protected Set<RunningInstance> createNodesInRegionAndZone(String region, String zone, String group, int count, Template template, RunInstancesOptions instanceOptions) { int countStarted = 0; int tries = 0; Set<RunningInstance> started = ImmutableSet.<RunningInstance> of(); int maxCount = EC2TemplateOptions.class.cast(template.getOptions()).getMaxCount(); int provCount; if (maxCount == 0) { maxCount = count; provCount = 1; } else { provCount = count; } while (countStarted < count && tries++ < count) { if (logger.isDebugEnabled()) logger.debug(">> running %d instance region(%s) zone(%s) ami(%s) params(%s)", count - countStarted, region, zone, template.getImage().getProviderId(), instanceOptions.buildFormParameters()); started = ImmutableSet.copyOf(concat( started, client.getInstanceApi().get().runInstancesInRegion(region, zone, template.getImage().getProviderId(), provCount, maxCount - countStarted, instanceOptions))); countStarted = size(started); if (countStarted < count) logger.debug(">> not enough instances (%d/%d) started, attempting again", countStarted, count); } return started; }

Target:
protected Set<RunningInstance> createNodesInRegionAndZone(String region, String zone, String group, int count, Template template, RunInstancesOptions instanceOptions) { int countStarted = 0; int tries = 0; Set<RunningInstance> started = ImmutableSet.<RunningInstance> of(); int maxCount = EC2TemplateOptions.class.cast(template.getOptions()).getMaxCount(); int countToProvision; if (maxCount == 0) { maxCount = count; countToProvision = 1; } else { countToProvision = count; } while (countStarted < count && tries++ < count) { if (logger.isDebugEnabled()) logger.debug(">> running %d instance region(%s) zone(%s) ami(%s) params(%s)", count - countStarted, region, zone, template.getImage().getProviderId(), instanceOptions.buildFormParameters()); started = ImmutableSet.copyOf(concat( started, client.getInstanceApi().get().runInstancesInRegion(region, zone, template.getImage().getProviderId(), countToProvision, maxCount - countStarted, instanceOptions))); countStarted = size(started); if (countStarted < count) logger.debug(">> not enough instances (%d/%d) started, attempting again", countStarted, count); } return started; }
Source:
public static boolean hasPermission( final String owner, final String activity, final String target) { logger.warn("BEACH Test: in hasPermission and the upAuth helper is: " + authorizationHelper.getClass()); return authorizationHelper.hasPermission(owner, activity, target); }

Target:
public static boolean hasPermission( final String owner, final String activity, final String target) { return authorizationHelper.hasPermission(owner, activity, target); }
Source:
public void initializeOfferings() { File metaDirectory = ufg.getMetaDirectory(); File[] files = metaDirectory.listFiles(); for (File file : files) { if (file.getName().startsWith("offer_") == false) continue; String offeringId = this.ufg.extractUniqueCode(file.getName()); try { String json = new String(Files.readAllBytes(Paths.get(file.getAbsolutePath()))); Offering offering = Offering.fromJSON(json); offeringNameToOfferingId.put(offering.getName(), offering.getId()); } catch (Exception e) { this.removeOffering(offeringId); } } }

Target:
public void initializeOfferings() { File metaDirectory = ufg.getMetaDirectory(); File[] files = metaDirectory.listFiles(); for (File file : files) { if (file.getName().startsWith("offer_") == false) continue; String offeringId = this.ufg.extractUniqueCode(file.getName()); try { String json = new String(Files.readAllBytes(Paths.get(file.getAbsolutePath()))); Offering offering = Offering.fromJSON(json); offeringNameToOfferingId.put(offering.getName(), offering.getId()); } catch (IOException e) { this.removeOffering(offeringId); } } }
Source:
private QName getPortTypeName(Class<?> serviceEndpointInterface) { Class<?> seiClass = serviceEndpointInterface; if (!serviceEndpointInterface.isAnnotationPresent(WebService.class)) { Message msg = new Message("SEI_NO_WEBSERVICE_ANNOTATION", BUNDLE, serviceEndpointInterface .getCanonicalName()); throw new WebServiceException(msg.toString()); } if (!serviceEndpointInterface.isInterface()) { WebService webService = serviceEndpointInterface.getAnnotation(WebService.class); String epi = webService.endpointInterface(); if (epi.length() > 0) { try { seiClass = Thread.currentThread().getContextClassLoader().loadClass(epi); } catch (ClassNotFoundException e) { Message msg = new Message("COULD_NOT_LOAD_CLASS", BUNDLE, api); throw new WebServiceException(msg.toString()); } if (!seiClass.isAnnotationPresent(javax.jws.WebService.class)) { Message msg = new Message("SEI_NO_WEBSERVICE_ANNOTATION", BUNDLE, seiClass.getCanonicalName()); throw new WebServiceException(msg.toString()); } } } WebService webService = seiClass.getAnnotation(WebService.class); String name = webService.name(); if (name.length() == 0) { name = seiClass.getSimpleName(); } String tns = webService.targetNamespace(); if (tns.length() == 0) { tns = URIParserUtil.getNamespace(PackageUtils.getPackageName(seiClass)); } return new QName(tns, name); }

Target:
private QName getPortTypeName(Class<?> serviceEndpointInterface) { Class<?> seiClass = serviceEndpointInterface; if (!serviceEndpointInterface.isAnnotationPresent(WebService.class)) { Message msg = new Message("SEI_NO_WEBSERVICE_ANNOTATION", BUNDLE, serviceEndpointInterface .getCanonicalName()); throw new WebServiceException(msg.toString()); } if (!serviceEndpointInterface.isInterface()) { WebService webService = serviceEndpointInterface.getAnnotation(WebService.class); String epi = webService.endpointInterface(); if (epi.length() > 0) { try { seiClass = Thread.currentThread().getContextClassLoader().loadClass(epi); } catch (ClassNotFoundException e) { Message msg = new Message("COULD_NOT_LOAD_CLASS", BUNDLE, epi); throw new WebServiceException(msg.toString()); } if (!seiClass.isAnnotationPresent(javax.jws.WebService.class)) { Message msg = new Message("SEI_NO_WEBSERVICE_ANNOTATION", BUNDLE, seiClass.getCanonicalName()); throw new WebServiceException(msg.toString()); } } } WebService webService = seiClass.getAnnotation(WebService.class); String name = webService.name(); if (name.length() == 0) { name = seiClass.getSimpleName(); } String tns = webService.targetNamespace(); if (tns.length() == 0) { tns = URIParserUtil.getNamespace(PackageUtils.getPackageName(seiClass)); } return new QName(tns, name); }
Source:
private static Set<Language> getApplicableLanguages(PMDConfiguration configuration, RuleSets ruleSets) { Set<Language> languages = new HashSet<>(); LanguageVersionDiscoverer discoverer = configuration.getLanguageVersionDiscoverer(); for (Rule rule : ruleSets.getAllRules()) { Language language = rule.getLanguage(); if (languages.contains(language)) continue; LanguageVersion version = discoverer.getDefaultLanguageVersion(language); if (RuleSet.applies(rule, version)) { languages.add(language); log.debug("Using " + language.getShortName() + " version: " + version.getShortName()); } } return languages; }

Target:
private static Set<Language> getApplicableLanguages(PMDConfiguration configuration, RuleSets ruleSets) { Set<Language> languages = new HashSet<>(); LanguageVersionDiscoverer discoverer = configuration.getLanguageVersionDiscoverer(); for (Rule rule : ruleSets.getAllRules()) { Language language = rule.getLanguage(); if (languages.contains(language)) continue; LanguageVersion version = discoverer.getDefaultLanguageVersion(language); if (RuleSet.applies(rule, version)) { languages.add(language); log.debug("Using version: {}", language.getShortName(), version.getShortName()); } } return languages; }
Source:
private static void closeResponse(final Response response) { try { if (response != null) { response.close(); } } catch (ProcessingException e) { log.warn("Couldn't close response", e); } finally { if (response != null) { response.close(); } } }

Target:
private static void closeResponse(final Response response) { try { if (response != null) { response.close(); } } catch (ProcessingException e) { log.warn("Couldn't close response", e); } }
Source:
private String getAllCfdefsString(Collection<CfDef> updatedCfs) { StringBuilder sb = new StringBuilder("CfDefs("); updatedCfs.stream() .forEach(def -> sb.append(def.toString()).append(", ")); sb.append(")"); return sb.toString(); }

Target:
private String getAllCfdefsString(Collection<CfDef> updatedCfs) { return updatedCfs.stream().map(CfDef::toString).collect(Collectors.joining(",")); }
Source:
public LibraryDilution save(LibraryDilution dilution) throws IOException { dilution.setLastModifier(authorizationManager.getCurrentUser()); try { Long newId = dilutionDao.save(dilution); LibraryDilution managed = dilutionDao.get(newId); boolean needsUpdate = false; if (hasTemporaryName(dilution)) { managed.setName(namingScheme.generateNameFor(managed)); validateNameOrThrow(managed, namingScheme); if (autoGenerateIdBarcodes && isStringEmptyOrNull(managed.getIdentificationBarcode())) generateAndSetIdBarcode(managed); needsUpdate = true; } if (needsUpdate) dilutionDao.save(managed); return managed; } catch (MisoNamingException e) { throw new IllegalArgumentException("Name generator failed to generate valid name for library"); } catch (ConstraintViolationException e) { throw new ConstraintViolationException(e.getMessage() + " " + ExceptionUtils.getRootCauseMessage(e), e.getSQLException(), e.getConstraintName()); } }

Target:
private LibraryDilution save(LibraryDilution dilution) throws IOException { dilution.setLastModifier(authorizationManager.getCurrentUser()); try { Long newId = dilutionDao.save(dilution); LibraryDilution managed = dilutionDao.get(newId); boolean needsUpdate = false; if (hasTemporaryName(dilution)) { managed.setName(namingScheme.generateNameFor(managed)); validateNameOrThrow(managed, namingScheme); needsUpdate = true; } if (autoGenerateIdBarcodes && isStringEmptyOrNull(managed.getIdentificationBarcode())) { generateAndSetIdBarcode(managed); needsUpdate = true; } if (needsUpdate) dilutionDao.save(managed); return managed; } catch (MisoNamingException e) { throw new IllegalArgumentException("Name generator failed to generate valid name for library"); } catch (ConstraintViolationException e) { throw new ConstraintViolationException(e.getMessage() + " " + ExceptionUtils.getRootCauseMessage(e), e.getSQLException(), e.getConstraintName()); } }
Source:
protected void writeDeliveryAnnotationsForSendBuffer(ByteBuf result, DeliveryAnnotations deliveryAnnotations) { DeliveryAnnotations daToUse = deliveryAnnotations != null ? deliveryAnnotations : deliveryAnnotationsForSendBuffer; if (daToUse != null && !daToUse.getValue().isEmpty()) { TLSEncode.getEncoder().setByteBuffer(new NettyWritable(result)); TLSEncode.getEncoder().writeObject(daToUse); TLSEncode.getEncoder().setByteBuffer((WritableBuffer) null); } }

Target:
protected void writeDeliveryAnnotationsForSendBuffer(ByteBuf result, DeliveryAnnotations deliveryAnnotations) { if (deliveryAnnotations != null && !deliveryAnnotations.getValue().isEmpty()) { TLSEncode.getEncoder().setByteBuffer(new NettyWritable(result)); TLSEncode.getEncoder().writeObject(deliveryAnnotations); TLSEncode.getEncoder().setByteBuffer((WritableBuffer) null); } }
Source:
public String getValue(String value) throws GeneralSecurityException { String returnedValue = "Empty"; if (value != null && !value.equals("")){ try { decrypt(value); returnedValue = "Set"; } catch (Exception exception) { String msg = "Failed to decrypt the current value."; console.writeLine(msg); log.error("", exception); throw new GeneralSecurityException(msg); } } return returnedValue; }

Target:
public String getValue(String value) throws GeneralSecurityException { String returnedValue = "Empty"; if (value != null && !value.equals("")){ try { decrypt(value); returnedValue = "Set"; } catch (Exception exception) { String msg = "Failed to decrypt the current value."; console.writeLine(msg); log.error("Exception", exception); throw new GeneralSecurityException(msg); } } return returnedValue; }
Source:
private void createHandlerLocationControls(Composite parent) { handlerComposite = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(handlerComposite); GridDataFactory.fillDefaults().grab(true, false).applyTo(handlerComposite); new Label(handlerComposite, SWT.NONE).setText(IDEWorkbenchMessages.UrlHandlerPreferencePage_Handler_Label); handlerLocation = new Text(handlerComposite, SWT.READ_ONLY); handlerLocation.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); handlerComposite.setVisible(false); }

Target:
private void createHandlerLocationControls(Composite parent) { handlerComposite = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(handlerComposite); GridDataFactory.fillDefaults().grab(true, false).applyTo(handlerComposite); new Label(handlerComposite, SWT.NONE).setText(IDEWorkbenchMessages.UrlHandlerPreferencePage_Handler_Label); handlerLocation = new Text(handlerComposite, SWT.READ_ONLY | SWT.BORDER); handlerLocation.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); handlerComposite.setVisible(false); }
Source:
public void testAddWork() throws Exception { AdminUnit adminUnit = repositoryObjectFactory.createAdminUnit(null); contentRoot.addMember(adminUnit); CollectionObject collObj = repositoryObjectFactory.createCollectionObject(null); adminUnit.addMember(collObj); treeIndexer.indexAll(baseAddress); String label = "work_label"; MvcResult result = mvc.perform(post("/edit/create/work/" + collObj.getPid().getId()) .param("label", label) .param("patronOnly", (String) null)) .andExpect(status().is2xxSuccessful()) .andReturn(); treeIndexer.indexAll(baseAddress); assertChildContainerAdded(collObj, label, WorkObject.class); Map<String, Object> respMap = getMapFromResponse(result); assertEquals(collObj.getPid().getId(), respMap.get("pid")); assertEquals("create", respMap.get("action")); }

Target:
public void testAddWork() throws Exception { AdminUnit adminUnit = repositoryObjectFactory.createAdminUnit(null); contentRoot.addMember(adminUnit); CollectionObject collObj = repositoryObjectFactory.createCollectionObject(null); adminUnit.addMember(collObj); treeIndexer.indexAll(baseAddress); String label = "work_label"; MvcResult result = mvc.perform(post("/edit/create/work/" + collObj.getPid().getId()) .param("label", label)) .andExpect(status().is2xxSuccessful()) .andReturn(); treeIndexer.indexAll(baseAddress); assertChildContainerAdded(collObj, label, WorkObject.class); Map<String, Object> respMap = getMapFromResponse(result); assertEquals(collObj.getPid().getId(), respMap.get("pid")); assertEquals("create", respMap.get("action")); assertPatronDoesNotHaveNonePermission(collObj, label); }
Source:
@Test public void indexedElseIf() throws Exception { TypeSpec taco = TypeSpec.classBuilder("Taco") .addMethod(MethodSpec.methodBuilder("choices") .beginControlFlow("if ($1L != null || $1L == $2L)", "mTaco", "mOtherTaco") .addStatement("$T.out.println($S)", System.class, "only one taco? NOO!") .nextControlFlow("else if ($1L.$3L && $2L.$3L)", "mTaco", "mOtherTaco", "isSupreme()") .addStatement("$T.out.println($S)", System.class, "taco heaven") .endControlFlow() .build()) .build(); assertThat(toString(taco)).isEqualTo("" + "package com.squareup.tacos;\n" + "\n" + "import java.lang.System;\n" + "\n" + "class Taco {\n" + " void choices() {\n" + " if (mTaco != null || mTaco == mOtherTaco) {\n" + " System.out.println(\"only one taco? NOO!\");\n" + " } else if (mTaco.isSupreme() && mOtherTaco.isSupreme()) {\n" + " System.out.println(\"taco heaven\");\n" + " }\n" + " }\n" + "}\n"); }

Target:
@Test public void indexedElseIf() throws Exception { TypeSpec taco = TypeSpec.classBuilder("Taco") .addMethod(MethodSpec.methodBuilder("choices") .beginControlFlow("if ($1L != null || $1L == $2L)", "taco", "otherTaco") .addStatement("$T.out.println($S)", System.class, "only one taco? NOO!") .nextControlFlow("else if ($1L.$3L && $2L.$3L)", "taco", "otherTaco", "isSupreme()") .addStatement("$T.out.println($S)", System.class, "taco heaven") .endControlFlow() .build()) .build(); assertThat(toString(taco)).isEqualTo("" + "package com.squareup.tacos;\n" + "\n" + "import java.lang.System;\n" + "\n" + "class Taco {\n" + " void choices() {\n" + " if (taco != null || taco == otherTaco) {\n" + " System.out.println(\"only one taco? NOO!\");\n" + " } else if (taco.isSupreme() && otherTaco.isSupreme()) {\n" + " System.out.println(\"taco heaven\");\n" + " }\n" + " }\n" + "}\n"); }
Source:
public void setUp() throws Exception { File sandbox; do { currSandbox = SANDBOX_DIR + "sandbox" + Integer.toString(r.nextInt(Integer.MAX_VALUE)); sandbox = new File(currSandbox); } while (sandbox.exists()); mavenSandbox = new FileSystemMavenSandbox(currSandbox); mojo = new GitCommitIdMojo(); initializeMojoWithDefaults(mojo); }

Target:
public void setUp() throws Exception { File sandbox; do { currSandbox = SANDBOX_DIR + "sandbox" + Integer.toString(ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE)); sandbox = new File(currSandbox); } while (sandbox.exists()); mavenSandbox = new FileSystemMavenSandbox(currSandbox); mojo = new GitCommitIdMojo(); initializeMojoWithDefaults(mojo); }