auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testIgnoreTableNameLengthFlag() throws IOException { Schema schema = new Schema("Table", TEST_PACKAGE, Namespace.EMPTY_NAMESPACE); schema.ignoreTableNameLengthChecks(); String longTableName = String.join("", Collections.nCopies(100, "x")); schema.addTableDefinition(longTableName, getSimpleTableDefinition(TABLE_REF)); }

Target:
public void testIgnoreTableNameLengthFlag() throws IOException { Schema schema = new Schema("Table", TEST_PACKAGE, Namespace.EMPTY_NAMESPACE); schema.ignoreTableNameLengthChecks(); String longTableName = String.join("", Collections.nCopies(1000, "x")); TableReference tableRef = TableReference.createWithEmptyNamespace(longTableName); schema.addTableDefinition(longTableName, getSimpleTableDefinition(tableRef)); }
Source:
private static <H> List<H> getResults(StubSearchProjectionContext actualProjectionContext, ProjectionHitMapper<?, ?> actualProjectionHitMapper, StubSearchProjection<H> actualRootProjection, List<?> rawHits) { List<Object> extractedElements = new ArrayList<>( rawHits.size() ); for ( Object rawHit : rawHits ) { actualProjectionContext.reset(); Object extract = actualRootProjection.extract( actualProjectionHitMapper, rawHit, actualProjectionContext ); extractedElements.add( extract ); if ( extract instanceof Integer ) { if ( ( (int) extract ) >= rawHits.size() ) { fail( "index for loading is out of the rawHit bound, probably we're trying to reuse the same hit mapper on different invocations" ); } } } LoadingResult<?> loadingResult = actualProjectionHitMapper.loadBlocking(); List<H> hits = new ArrayList<>( rawHits.size() ); for ( Object extractedElement : extractedElements ) { actualProjectionContext.reset(); H hit = actualRootProjection.transform( loadingResult, extractedElement, actualProjectionContext ); if ( actualProjectionContext.hasFailedLoad() ) { continue; } hits.add( hit ); } return hits; }

Target:
private static <H> List<H> getResults(StubSearchProjectionContext actualProjectionContext, ProjectionHitMapper<?, ?> actualProjectionHitMapper, StubSearchProjection<H> actualRootProjection, List<?> rawHits) { List<Object> extractedElements = new ArrayList<>( rawHits.size() ); for ( Object rawHit : rawHits ) { actualProjectionContext.reset(); extractedElements.add( actualRootProjection.extract( actualProjectionHitMapper, rawHit, actualProjectionContext ) ); } LoadingResult<?> loadingResult = actualProjectionHitMapper.loadBlocking(); List<H> hits = new ArrayList<>( rawHits.size() ); for ( Object extractedElement : extractedElements ) { actualProjectionContext.reset(); H hit = actualRootProjection.transform( loadingResult, extractedElement, actualProjectionContext ); if ( actualProjectionContext.hasFailedLoad() ) { continue; } hits.add( hit ); } return hits; }
Source:
public void onSwipeRight() { Picasso.with(getApplicationContext()).load(allImgSrc[imgSrcPosition - 1]).into(detailedImageView); imgSrcPosition--; }

Target:
public void onSwipeRight() { PicassoScreens.load(allImgSrc[imgSrcPosition - 1]).into(detailedImageView); imgSrcPosition--; }
Source:
public void testAllOrNothing() { ITmfTrace trace = fTrace; assertNotNull(trace); TmfAnalysisRequirement req = new TmfCompositeAnalysisRequirement(ImmutableSet.of(TRUE_REQ1), ValuePriorityLevel.ALL_OR_NOTHING); assertTrue(req.test(trace)); req = new TmfCompositeAnalysisRequirement(ImmutableSet.of(TRUE_REQ1, TRUE_REQ2), ValuePriorityLevel.ALL_OR_NOTHING); assertTrue(req.test(trace)); req = new TmfCompositeAnalysisRequirement(ImmutableSet.of(FALSE_REQ1), ValuePriorityLevel.ALL_OR_NOTHING); assertTrue(req.test(trace)); req = new TmfCompositeAnalysisRequirement(ImmutableSet.of(FALSE_REQ1, TRUE_REQ1), ValuePriorityLevel.ALL_OR_NOTHING); assertFalse(req.test(trace)); req = new TmfCompositeAnalysisRequirement(ImmutableSet.of(FALSE_REQ1, FALSE_REQ2), ValuePriorityLevel.ALL_OR_NOTHING); assertTrue(req.test(trace)); }

Target:
public void testAllOrNothing() { ITmfTrace trace = fTrace; assertNotNull(trace); TmfAnalysisRequirement req = new TmfCompositeAnalysisRequirement(ImmutableSet.of(TRUE_REQ1), PriorityLevel.ALL_OR_NOTHING); assertTrue(req.test(trace)); req = new TmfCompositeAnalysisRequirement(ImmutableSet.of(TRUE_REQ1, TRUE_REQ2), PriorityLevel.ALL_OR_NOTHING); assertTrue(req.test(trace)); req = new TmfCompositeAnalysisRequirement(ImmutableSet.of(FALSE_REQ1), PriorityLevel.ALL_OR_NOTHING); assertTrue(req.test(trace)); req = new TmfCompositeAnalysisRequirement(ImmutableSet.of(FALSE_REQ1, TRUE_REQ1), PriorityLevel.ALL_OR_NOTHING); assertFalse(req.test(trace)); req = new TmfCompositeAnalysisRequirement(ImmutableSet.of(FALSE_REQ1, FALSE_REQ2), PriorityLevel.ALL_OR_NOTHING); assertTrue(req.test(trace)); }
Source:
private Set<Artifact> resolveTransitively(Artifact artifact, SkipFilter dependencyFilter, boolean verifyPom) throws MojoExecutionException { final ArtifactFilter requestFilter = a -> !dependencyFilter.shouldSkipArtifact(a); final ArtifactResolutionRequest request = new ArtifactResolutionRequest() .setArtifact(artifact).setLocalRepository(localRepository).setRemoteRepositories(remoteRepositories) .setResolutionFilter(requestFilter).setCollectionFilter(requestFilter).setResolveTransitively(true); final ArtifactResolutionResult resolution = repositorySystem.resolve(request); if (!resolution.isSuccess()) { if (resolution.hasMissingArtifacts()) { LOG.warn("Missing artifacts for {}: {}", artifact.getId(), resolution.getMissingArtifacts()); } resolution.getExceptions().forEach(e -> { LOG.warn("Failed to resolve transitive dependencies for {}: {}", artifact.getId(), e.getMessage()); LOG.debug("Exceptions in artifact resolution.", e); }); throw new MojoExecutionException("Failed to resolve transitive dependencies."); } if (verifyPom) { final LinkedHashSet<Artifact> resolved = new LinkedHashSet<>(resolution.getArtifacts()); for (Artifact a : resolution.getArtifacts()) { resolved.add(resolvePom(a)); } return resolved; } else { return resolution.getArtifacts(); } }

Target:
private Set<Artifact> resolveTransitively(Artifact artifact, SkipFilter dependencyFilter, boolean verifyPom) throws MojoExecutionException { final ArtifactFilter requestFilter = a -> !dependencyFilter.shouldSkipArtifact(a); final ArtifactResolutionRequest request = new ArtifactResolutionRequest() .setArtifact(artifact).setLocalRepository(localRepository).setRemoteRepositories(remoteRepositories) .setResolutionFilter(requestFilter).setCollectionFilter(requestFilter).setResolveTransitively(true); final ArtifactResolutionResult resolution = repositorySystem.resolve(request); if (!resolution.isSuccess()) { if (resolution.hasMissingArtifacts()) { LOG.warn("Missing artifacts for {}: {}", artifact.getId(), resolution.getMissingArtifacts()); } resolution.getExceptions().forEach(e -> LOG.warn("Failed to resolve transitive dependencies for {}: {}", artifact.getId(), e.getMessage())); throw new MojoExecutionException("Failed to resolve transitive dependencies."); } if (verifyPom) { final LinkedHashSet<Artifact> resolved = new LinkedHashSet<>(resolution.getArtifacts()); for (Artifact a : resolution.getArtifacts()) { resolved.add(resolvePom(a)); } return resolved; } else { return resolution.getArtifacts(); } }
Source:
private Object defaultCompletionStage(ProceedingJoinPoint proceedingJoinPoint, io.github.resilience4j.circuitbreaker.CircuitBreaker circuitBreaker, String methodName) throws Throwable { CircuitBreakerUtils.isCallPermitted(circuitBreaker); long start = System.nanoTime(); try { final CompletableFuture promise = new CompletableFuture<>(); if (circuitBreaker.isCallPermitted()) { CompletionStage<?> result = (CompletionStage<?>) proceedingJoinPoint.proceed(); if (result != null) { result.whenComplete((v, t) -> { long durationInNanos = System.nanoTime() - start; if (t != null) { circuitBreaker.onError(durationInNanos, t); promise.completeExceptionally(t); } else { circuitBreaker.onSuccess(durationInNanos); promise.complete(v); } }); } } return promise; } catch (Throwable throwable) { long durationInNanos = System.nanoTime() - start; circuitBreaker.onError(durationInNanos, throwable); if (logger.isDebugEnabled()) { logger.debug("Invocation of method '" + methodName + "' failed!", throwable); } throw throwable; } }

Target:
private Object defaultCompletionStage(ProceedingJoinPoint proceedingJoinPoint, io.github.resilience4j.circuitbreaker.CircuitBreaker circuitBreaker, String methodName) throws Throwable { final CompletableFuture promise = new CompletableFuture<>(); long start = System.nanoTime(); if (!circuitBreaker.isCallPermitted()) { promise.completeExceptionally( new CircuitBreakerOpenException( String.format("CircuitBreaker '%s' is open", circuitBreaker.getName()))); } else { try { CompletionStage<?> result = (CompletionStage<?>) proceedingJoinPoint.proceed(); if (result != null) { result.whenComplete((v, t) -> { long durationInNanos = System.nanoTime() - start; if (t != null) { circuitBreaker.onError(durationInNanos, t); promise.completeExceptionally(t); } else { circuitBreaker.onSuccess(durationInNanos); promise.complete(v); } }); } } catch (Exception e) { long durationInNanos = System.nanoTime() - start; circuitBreaker.onError(durationInNanos, e); throw e; } } return promise; }
Source:
public void testExecuteQueryWithOption() throws Exception { String query = "status:open"; String option = "LABELS"; List<GerritQueryResult> results = executeQuery(query, option); assertNotNull(results); }

Target:
public void testExecuteQueryWithOption() throws Exception { String query = "status:open"; String option = "LABELS"; List<GerritQueryResult> results = executeQuery(query, option); assertNotNull(results); for (int index = 0; index < results.size(); index++) { assertNotNull(results.get(index)); } }
Source:
void handleClosed() { Handler<Void> endHandler = this.endHandler; synchronized (conn) { cleanupHandlers(); Handler<Void> closeHandler = this.closeHandler; if (closeHandler != null) { conn.getContext().runOnContext(closeHandler); } } if (endHandler != null) { endHandler.handle(null); } }

Target:
void handleClosed() { Handler<Void> endHandler; synchronized (conn) { cleanupHandlers(); endHandler = this.endHandler; Handler<Void> closeHandler = this.closeHandler; if (closeHandler != null) { conn.getContext().runOnContext(closeHandler); } } if (endHandler != null) { endHandler.handle(null); } }
Source:
private void repairActualMutationList(List<Mutation> actualMutationList, List<Mutation> expectedMutationList) throws IOException { Mutation actual = null; for (Mutation mutation : actualMutationList) { if (mutation instanceof Put && !isVerified((Put) mutation)) { actual = mutation; break; } } if (actual == null) { return; } long ts = getTimestamp(actual); int expectedIndex; int expectedListSize = expectedMutationList.size(); for (expectedIndex = 0; expectedIndex < expectedListSize; expectedIndex++) { if (getTimestamp(expectedMutationList.get(expectedIndex)) <= ts) { if (expectedIndex > 0) { expectedIndex--; } break; } } if (expectedIndex == expectedListSize) { return; } for (; expectedIndex < expectedListSize; expectedIndex++) { Mutation mutation = expectedMutationList.get(expectedIndex); if (mutation instanceof Put) { mutation = new Put((Put) mutation); } else { mutation = new Delete((Delete) mutation); } actualMutationList.add(mutation); } Collections.sort(actualMutationList, MUTATION_TS_DESC_COMPARATOR); }

Target:
private void repairActualMutationList(List<Mutation> actualMutationList, List<Mutation> expectedMutationList) throws IOException { List<Mutation> repairedMutationList = new ArrayList<>(expectedMutationList.size()); for (Mutation actual : actualMutationList) { if (actual instanceof Put && !isVerified((Put) actual)) { long ts = getTimestamp(actual); int expectedIndex; int expectedListSize = expectedMutationList.size(); for (expectedIndex = 0; expectedIndex < expectedListSize; expectedIndex++) { if (getTimestamp(expectedMutationList.get(expectedIndex)) <= ts) { if (expectedIndex > 0) { expectedIndex--; } break; } } if (expectedIndex == expectedListSize) { continue; } for (; expectedIndex < expectedListSize; expectedIndex++) { Mutation mutation = expectedMutationList.get(expectedIndex); if (mutation instanceof Put) { mutation = new Put((Put) mutation); } else { mutation = new Delete((Delete) mutation); } repairedMutationList.add(mutation); } break; } } if (repairedMutationList.isEmpty()) { return; } actualMutationList.addAll(repairedMutationList); Collections.sort(actualMutationList, MUTATION_TS_DESC_COMPARATOR); }
Source:
public void tearDown() throws IOException { if (!file.delete()) { throw new IOException("Error deleting " + file.getAbsolutePath()); } }

Target:
public void tearDown() throws IOException { if (file.exists() && !file.delete()) { throw new IOException("Error deleting " + file.getAbsolutePath()); } }
Source:
private ITmfEvent parseLine(long rank, String line) { if (line == null) { return null; } String[] tokens = line.split(",", MAX_FIELDS); if (tokens.length < MAX_FIELDS) { return null; } int i = 0; Long timestamp = Longs.tryParse(tokens[i++]); if (timestamp == null) { return null; } String source = tokens[i++]; Long sourceInstance = Longs.tryParse(tokens[i++]); if (sourceInstance == null) { sourceInstance = -1L; } BtfEventType type = BtfEventTypeFactory.parse(tokens[i++]); if (type == null) { return null; } String target = tokens[i++]; Long targetInstance = Longs.tryParse(tokens[i++]); if (targetInstance == null) { targetInstance = -1L; } String event = tokens[i++]; ITmfEventField content = type.generateContent(event, sourceInstance, targetInstance); return new BtfEvent(this, rank, getTimestampTransform().transform(fTsFormat.createTimestamp(timestamp + fTsOffset)), source, type, type.getDescription(), content, target); }

Target:
private ITmfEvent parseLine(long rank, String line) { if (line == null) { return null; } String[] tokens = line.split(",", MAX_FIELDS); if (tokens.length < MAX_FIELDS) { return null; } Iterator<String> token = Iterators.forArray(tokens); Long timestamp = Longs.tryParse(token.next()); if (timestamp == null) { return null; } String source = token.next(); Long sourceInstance = Longs.tryParse(token.next()); if (sourceInstance == null) { sourceInstance = -1L; } BtfEventType type = BtfEventTypeFactory.parse(token.next()); if (type == null) { return null; } String target = token.next(); Long targetInstance = Longs.tryParse(token.next()); if (targetInstance == null) { targetInstance = -1L; } String event = token.next(); ITmfEventField content = type.generateContent(event, sourceInstance, targetInstance); return new BtfEvent(this, rank, getTimestampTransform().transform(fTsFormat.createTimestamp(timestamp + fTsOffset)), source, type, type.getDescription(), content, target); }
Source:
private SootMethod tryResolve(StringBuffer trace) { if(isSignaturePolymorphic()) { return new SootMethod(name(), parameterTypes(), returnType(), Modifier.PUBLIC); } if (declaringClass.getName().equals("java.dyn.InvokeDynamic")) { throw new IllegalStateException("Cannot resolve invokedynamic method references at compile time!"); } SootClass cl = declaringClass; while (true) { if (trace != null) trace.append("Looking in " + cl + " which has methods " + cl.getMethods() + "\n"); SootMethod sm = cl.getMethodUnsafe(getSubSignature()); if (sm != null) return checkStatic(sm); if (Scene.v().allowsPhantomRefs() && (cl.isPhantom() || Options.v().ignore_resolution_errors())) { SootMethod m = new SootMethod(name, parameterTypes, returnType, isStatic() ? Modifier.STATIC : 0); m.setPhantom(true); m = cl.getOrAddMethod(m); return checkStatic(m); } if (cl.hasSuperclass()) cl = cl.getSuperclass(); else break; } cl = declaringClass; while (true) { LinkedList<SootClass> queue = new LinkedList<SootClass>(); queue.addAll(cl.getInterfaces()); while (!queue.isEmpty()) { SootClass iface = queue.removeFirst(); if (trace != null) trace.append("Looking in " + iface + " which has methods " + iface.getMethods() + "\n"); SootMethod sm = iface.getMethodUnsafe(getSubSignature()); if (sm != null) return checkStatic(sm); queue.addAll(iface.getInterfaces()); } if (cl.hasSuperclass()) cl = cl.getSuperclass(); else break; } return null; }

Target:
private SootMethod tryResolve(StringBuffer trace) { if (declaringClass.getName().equals("java.dyn.InvokeDynamic")) { throw new IllegalStateException("Cannot resolve invokedynamic method references at compile time!"); } SootClass cl = declaringClass; while (true) { if (trace != null) trace.append("Looking in " + cl + " which has methods " + cl.getMethods() + "\n"); SootMethod sm = cl.getMethodUnsafe(getSubSignature()); if (sm != null) return checkStatic(sm); if (isSignaturePolymorphic()) { SootMethod dummyMethod = new SootMethod(name(), parameterTypes(), returnType(), Modifier.PUBLIC); cl.addMethod(dummyMethod); return dummyMethod; } if (Scene.v().allowsPhantomRefs() && (cl.isPhantom() || Options.v().ignore_resolution_errors())) { SootMethod m = new SootMethod(name, parameterTypes, returnType, isStatic() ? Modifier.STATIC : 0); m.setPhantom(true); m = cl.getOrAddMethod(m); return checkStatic(m); } if (cl.hasSuperclass()) cl = cl.getSuperclass(); else break; } cl = declaringClass; while (true) { LinkedList<SootClass> queue = new LinkedList<SootClass>(); queue.addAll(cl.getInterfaces()); while (!queue.isEmpty()) { SootClass iface = queue.removeFirst(); if (trace != null) trace.append("Looking in " + iface + " which has methods " + iface.getMethods() + "\n"); SootMethod sm = iface.getMethodUnsafe(getSubSignature()); if (sm != null) return checkStatic(sm); queue.addAll(iface.getInterfaces()); } if (cl.hasSuperclass()) cl = cl.getSuperclass(); else break; } return null; }
Source:
public void validate_shouldFailIfThereIsADuplicateUnretiredConceptNameInTheLocale() throws Exception { Context.setLocale(new Locale("en", "GB")); Concept concept = Context.getConceptService().getConcept(5497); String duplicateName = concept.getFullySpecifiedName(Context.getLocale()).getName(); ConceptName newName = new ConceptName(duplicateName, Context.getLocale()); newName.setDateCreated(Calendar.getInstance().getTime()); newName.setCreator(Context.getAuthenticatedUser()); concept.addName(newName); Errors errors = new BindException(concept, "concept"); try { new ConceptValidator().validate(concept, errors); } catch (DuplicateConceptNameException e) { Assert.assertEquals("'" + duplicateName + "' is a duplicate name in locale '" + Context.getLocale() + "' for the same concept", e.getMessage()); } }

Target:
public void validate_shouldFailIfThereIsADuplicateUnretiredConceptNameInTheLocale() throws Exception { Context.setLocale(new Locale("en", "GB")); Concept concept = Context.getConceptService().getConcept(5497); String duplicateName = concept.getFullySpecifiedName(Context.getLocale()).getName(); ConceptName newName = new ConceptName(duplicateName, Context.getLocale()); newName.setDateCreated(Calendar.getInstance().getTime()); newName.setCreator(Context.getAuthenticatedUser()); concept.addName(newName); Errors errors = new BindException(concept, "concept"); expectedException.expect(DuplicateConceptNameException.class); expectedException.expectMessage("'" + duplicateName + "' is a duplicate name in locale '" + Context.getLocale() + "' for the same concept"); new ConceptValidator().validate(concept, errors); }
Source:
public boolean isAllowed(Set<String> roles, List<String> allowedRoles) throws Exception { for (String role : allowedRoles) { if (roles.contains(role)) { return true; } } return false; }

Target:
public boolean isAllowed(Set<String> roles, List<String> allowedRoles) { for (String role : allowedRoles) { if (roles.contains(role)) { return true; } } return false; }
Source:
public void removeNotification(Notification notification) { Observable.fromCallable(() -> controller.markAsRead(notification)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(result -> { if (result){ notificationList.remove(notification); setAdapter(notificationList); adapter.notifyDataSetChanged(); Snackbar snackbar = Snackbar .make(relativeLayout,"Notification marked as read", Snackbar.LENGTH_LONG); snackbar.show(); if (notificationList.size()==0){ if (isarchivedvisible) { nonotificationtext.setText(R.string.no_archived_notification); }else { nonotificationtext.setText(R.string.no_notification); } relativeLayout.setVisibility(View.GONE); no_notification.setVisibility(View.VISIBLE); } } else { adapter.notifyDataSetChanged(); setAdapter(notificationList); Toast.makeText(NotificationActivity.this, "There was some error!", Toast.LENGTH_SHORT).show(); } }, throwable -> { Timber.e(throwable, "Error occurred while loading notifications"); throwable.printStackTrace(); ViewUtil.showShortSnackbar(relativeLayout, R.string.error_notifications); progressBar.setVisibility(View.GONE); }); }

Target:
public void removeNotification(Notification notification) { Observable.fromCallable(() -> controller.markAsRead(notification)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(result -> { if (result){ notificationList.remove(notification); setAdapter(notificationList); adapter.notifyDataSetChanged(); Snackbar snackbar = Snackbar .make(relativeLayout,"Notification marked as read", Snackbar.LENGTH_LONG); snackbar.show(); if (notificationList.size()==0){ setEmptyView(); relativeLayout.setVisibility(View.GONE); no_notification.setVisibility(View.VISIBLE); } } else { adapter.notifyDataSetChanged(); setAdapter(notificationList); Toast.makeText(NotificationActivity.this, "There was some error!", Toast.LENGTH_SHORT).show(); } }, throwable -> { Timber.e(throwable, "Error occurred while loading notifications"); throwable.printStackTrace(); ViewUtil.showShortSnackbar(relativeLayout, R.string.error_notifications); progressBar.setVisibility(View.GONE); }); }
Source:
public HadoopSparkJob(String jobid, Props sysProps, Props jobProps, Logger log) { super(jobid, sysProps, jobProps, log); getJobProps().put("azkaban.job.id", jobid); shouldProxy = getSysProps().getBoolean("azkaban.should.proxy", false); getJobProps().put("azkaban.should.proxy", Boolean.toString(shouldProxy)); obtainTokens = getSysProps().getBoolean("obtain.binary.token", false); if (shouldProxy) { getLog().info("Initiating hadoop security manager."); try { hadoopSecurityManager = loadHadoopSecurityManager(sysProps, log); } catch (RuntimeException e) { throw new RuntimeException("Failed to get hadoop security manager!" + e); } } }

Target:
public HadoopSparkJob(String jobid, Props sysProps, Props jobProps, Logger log) { super(jobid, sysProps, jobProps, log); getJobProps().put(CommonJobProperties.JOB_ID, jobid); shouldProxy = getSysProps().getBoolean(ENABLE_PROXYING, false); getJobProps().put(ENABLE_PROXYING, Boolean.toString(shouldProxy)); obtainTokens = getSysProps().getBoolean(OBTAIN_BINARY_TOKEN, false); if (shouldProxy) { getLog().info("Initiating hadoop security manager."); try { hadoopSecurityManager = HadoopJobUtils.loadHadoopSecurityManager(getSysProps(), log); } catch (RuntimeException e) { throw new RuntimeException("Failed to get hadoop security manager!" + e); } } }
Source:
public String toString() { StringBuilder b = new StringBuilder(); b.append("MetadataCollectionImpl{"); b.append("version="); b.append(", created="); b.append(", lastUsed="); b.append(", lifespan="); b.append(", maxIdle="); b.append(", collection=["); b.append(collection.stream() .map(r -> r.toString()) .collect(Collectors.joining(","))); b.append("]}"); return b.toString(); }

Target:
public String toString() { StringBuilder b = new StringBuilder(); b.append("MetadataCollectionImpl{"); b.append("version="); b.append(version); b.append(", created="); b.append(created); b.append(", lastUsed="); b.append(lastUsed); b.append(", lifespan="); b.append(lifespan); b.append(", maxIdle="); b.append(maxIdle); b.append(", collection="); b.append(collection); b.append("}"); return b.toString(); }
Source:
public Object[][] intervalsSameContig(){ List<Locatable> input = Arrays.asList( new Interval("1",10,100) ); List<Locatable> empty = new ArrayList<>(); List<Locatable> manyOverlapping = Arrays.asList( new Interval("1",10,100), new Interval("1",20,50), new Interval("1",20,51), new Interval("1",20,52) ); List<Locatable> mixInput = Arrays.asList( new Interval("1",10,20), new Interval("1",10,60), new Interval("1",30,50), new Interval("1",40,42), new Interval("1",45,60), new Interval("1",60,100) ); List<Locatable> mixExpected = Arrays.asList( new Interval("1",10,60), new Interval("1",30,50), new Interval("1",40,42), new Interval("1",45,60) ); return new Object[][]{ new Object[]{input, new Interval("1", 10, 10), input}, new Object[]{input, new Interval("1", 100, 100), input}, new Object[]{input, new Interval("1", 9, 9), empty}, new Object[]{input, new Interval("1", 11, 11), input}, new Object[]{input, new Interval("1", 99, 99), input}, new Object[]{input, new Interval("1", 101, 101), empty}, new Object[]{input, new Interval("2", 10, 100), empty}, new Object[]{empty, new Interval("1", 101, 101), empty}, new Object[]{input, new Interval("1", 10, 100), input}, new Object[]{manyOverlapping, new Interval("1", 20, 20), manyOverlapping}, new Object[]{mixInput, new Interval("1",30,50), mixExpected}, new Object[]{mixInput, new Interval("1",300,500), empty}, }; }

Target:
public Object[][] intervalsSameContig(){ final List<Locatable> input = Arrays.asList( new Interval("1",10,100) ); final List<Locatable> empty = new ArrayList<>(); final List<Locatable> manyOverlapping = Arrays.asList( new Interval("1",10,100), new Interval("1",20,50), new Interval("1",20,51), new Interval("1",20,52) ); final List<Locatable> mixInput = Arrays.asList( new Interval("1",10,20), new Interval("1",10,60), new Interval("1",30,50), new Interval("1",40,42), new Interval("1",45,60), new Interval("1",60,100) ); final List<Locatable> mixExpected = Arrays.asList( new Interval("1",10,60), new Interval("1",30,50), new Interval("1",40,42), new Interval("1",45,60) ); return new Object[][] { new Object[] {input, new Interval("1", 10, 10), input}, new Object[] {input, new Interval("1", 100, 100), input}, new Object[] {input, new Interval("1", 9, 9), empty}, new Object[] {input, new Interval("1", 11, 11), input}, new Object[] {input, new Interval("1", 99, 99), input}, new Object[] {input, new Interval("1", 101, 101), empty}, new Object[] {input, new Interval("2", 10, 100), empty}, new Object[] {empty, new Interval("1", 101, 101), empty}, new Object[] {input, new Interval("1", 10, 100), input}, new Object[] {manyOverlapping, new Interval("1", 20, 20), manyOverlapping}, new Object[] {mixInput, new Interval("1",30,50), mixExpected}, new Object[] {mixInput, new Interval("1",300,500), empty}, }; }
Source:
public int open() { super.setBlockOnOpen(false); super.open(); final Button okButton = super.getButton(IDialogConstants.OK_ID); okButton.setText("Finish"); Display display; Shell shell = super.getShell(); if (shell == null) { display = Display.getCurrent(); } else { display = shell.getDisplay(); } while (shell != null && !shell.isDisposed()) { try { if (!display.readAndDispatch()) { display.sleep(); } if(!pathIsValid.isDisposed() && !pathValidator(currentBuildPath)) { if(!((pathIsValid.getText()).equals(INVALID_PATH_MESSAGE))) { pathIsValid.setText(INVALID_PATH_MESSAGE); } } else { if(!pathIsValid.isDisposed() && !pathIsValid.getText().equals("")) { pathIsValid.setText(""); } } } catch (Throwable e) { e.printStackTrace(); } } if (!display.isDisposed()) { display.update(); } return super.getReturnCode(); }

Target:
public int open() { super.setBlockOnOpen(false); super.open(); final Button okButton = super.getButton(IDialogConstants.OK_ID); okButton.setText(Messages.StateSystemPathBuilder_okButtonText); Display display; Shell shell = super.getShell(); if (shell == null) { display = Display.getCurrent(); } else { display = shell.getDisplay(); } while (shell != null && !shell.isDisposed()) { try { if (!display.readAndDispatch()) { display.sleep(); } if (!pathIsValid.isDisposed() && !pathValidator(currentBuildPath)) { if (!((pathIsValid.getText()).equals(INVALID_PATH_MESSAGE))) { pathIsValid.setText(INVALID_PATH_MESSAGE); } } else { if (!pathIsValid.isDisposed() && !pathIsValid.getText().equals("")) { pathIsValid.setText(""); } } } catch (Throwable e) { Activator.logError(e.getMessage(), e); } } if (!display.isDisposed()) { display.update(); } return super.getReturnCode(); }
Source:
public void onEvent(ActivitiEvent event) { if (event instanceof ActivitiEntityEvent && TimerJobEntity.class.isAssignableFrom(((ActivitiEntityEvent) event).getEntity().getClass()) && ((TimerJobEntityImpl)((ActivitiEntityEvent) event).getEntity()).getJobType().equals("timer")) { converter.from((ActivitiEntityEvent) event) .ifPresent(convertedEvent -> { for (BPMNElementEventListener<BPMNTimerCancelledEvent> listener : processRuntimeEventListeners) { listener.onEvent(convertedEvent); } }); } }

Target:
public void onEvent(ActivitiEvent event) { converter.from(event) .ifPresent(convertedEvent -> { for (BPMNElementEventListener<BPMNTimerCancelledEvent> listener : processRuntimeEventListeners) { listener.onEvent(convertedEvent); } }); }
Source:
private void cleanup(final HostMessenger messenger) { shutdown = true; if (m_mbox != null && messenger != null) { for (Integer partition : m_dataSourcesByPartition.keySet()) { final String partitionDN = m_mailboxesZKPath + "/" + partition; String path = partitionDN + "/" + m_mbox.getHSId(); try { messenger.getZK().delete(path, 0); } catch (InterruptedException ex) { ; } catch (KeeperException ex) { ; } } messenger.removeMailbox(m_mbox); } }

Target:
private void cleanup(final HostMessenger messenger) { shutdown = true; if (m_mbox != null && messenger != null) { synchronized(m_dataSourcesByPartition) { for (Integer partition : m_dataSourcesByPartition.keySet()) { final String partitionDN = m_mailboxesZKPath + "/" + partition; String path = partitionDN + "/" + m_mbox.getHSId(); try { messenger.getZK().delete(path, 0); } catch (InterruptedException ex) { ; } catch (KeeperException ex) { ; } } } messenger.removeMailbox(m_mbox); } }
Source:
public void handleVillagerAI(EntityJoinWorldEvent event) { IForgeRegistry<VillagerRegistry.VillagerProfession> villagerProfessions = ForgeRegistries.VILLAGER_PROFESSIONS; Entity entity = event.getEntity(); if((entity instanceof EntityVillager)) { EntityVillager villager = (EntityVillager) event.getEntity(); if(villagerProfessions.getKey(villager.getProfessionForge()).toString().equals(Constants.ID_VILLAGER_APIARIST)) { villager.tasks.addTask(6, new ApiaristAI(villager, villager.getAIMoveSpeed())); } } }

Target:
public void handleVillagerAI(EntityJoinWorldEvent event) { IForgeRegistry<VillagerRegistry.VillagerProfession> villagerProfs = ForgeRegistries.VILLAGER_PROFESSIONS; Entity entity = event.getEntity(); if ((entity instanceof EntityVillager)) { EntityVillager villager = (EntityVillager) event.getEntity(); ResourceLocation villagerProf = villagerProfs.getKey(villager.getProfessionForge()); if (villagerProf.toString().equals(Constants.ID_VILLAGER_APIARIST)) { villager.tasks.addTask(6, new ApiaristAI(villager, 0.6)); } } }
Source:
public void testSetModulesEnabledFalse() throws Exception { Glide.tearDown(); Glide.setModulesEnabled(false); try { Glide glide = Glide.get(getContext()); List<ModelLoader<GlideUrl, ?>> modelLoaders = glide.getRegistry().getModelLoaders(mock(GlideUrl.class)); assertEquals(1, modelLoaders.size()); assertTrue(modelLoaders.get(0) instanceof HttpGlideUrlLoader); } finally { Glide.setModulesEnabled(true); } }

Target:
public void testSetModulesEnabledFalse() throws Exception { Glide.tearDown(); Glide.setModulesEnabled(false); Glide glide = Glide.get(getContext()); List<ModelLoader<GlideUrl, ?>> modelLoaders = glide.getRegistry().getModelLoaders(mock(GlideUrl.class)); assertEquals(1, modelLoaders.size()); assertTrue(modelLoaders.get(0) instanceof HttpGlideUrlLoader); }
Source:
protected QosBase createQosEntity(ResultSet rs) throws SQLException { switch (QosType.forValue(rs.getInt("qos_type"))) { case STORAGE: return StorageQosDaoDbFacadeImpl.StorageDaoDbFacadaeImplMapper.MAPPER.createQosEntity(rs); default: break; } return null; }

Target:
protected QosBase createQosEntity(ResultSet rs) throws SQLException { QosType qosType = QosType.forValue(rs.getInt("qos_type")); switch (qosType) { case STORAGE: return StorageQosDaoDbFacadeImpl.StorageDaoDbFacadaeImplMapper.MAPPER.createQosEntity(rs); default: log.debugFormat("not handled/missing qos_type", qosType); break; } return null; }
Source:
public void visitNode(Tree tree) { MethodTree node = (MethodTree) tree; Symbol symbol = node.symbol(); if (symbol.isPrivate() && symbol.usages().isEmpty()) { if (node.is(Tree.Kind.CONSTRUCTOR)) { addIssue(node, "Remove this unused private \"" + node.simpleName().name() + "\" constructor."); } else if (!SerializableContract.SERIALIZABLE_CONTRACT_METHODS.contains(node.symbol().name())) { addIssue(node, "Remove this unused private \"" + symbol.name() + "\" method."); } } }

Target:
public void visitNode(Tree tree) { MethodTree node = (MethodTree) tree; Symbol symbol = node.symbol(); if (node.modifiers().annotations().isEmpty() && symbol.isPrivate() && symbol.usages().isEmpty()) { if (node.is(Tree.Kind.CONSTRUCTOR)) { if (!node.parameters().isEmpty()) { addIssue(node, "Remove this unused private \"" + node.simpleName().name() + "\" constructor."); } } else if (!SerializableContract.SERIALIZABLE_CONTRACT_METHODS.contains(symbol.name())) { addIssue(node, "Remove this unused private \"" + symbol.name() + "\" method."); } } }
Source:
private void checkV14Bootsrapping(boolean loggWarning) { useDeprecatedV14Bootstrapping = getBooleanProperty( Constants.SERVLET_PARAMETER_USE_V14_BOOTSTRAP, false); if (loggWarning) { if (useDeprecatedV14Bootstrapping) { getLogger().info(WARNING_V14_BOOTSTRAP); } else if (!productionMode) { String frontendDir = getStringProperty(PARAM_FRONTEND_DIR, System .getProperty(PARAM_FRONTEND_DIR, DEFAULT_FRONTEND_DIR)); String indexHTMLMessage = getIndexHTMLMessage(frontendDir); String entryPointMessage = getEntryPointMessage(frontendDir); getLogger().info(String.format(WARNING_V15_BOOTSTRAP, indexHTMLMessage, entryPointMessage)); } } }

Target:
private void checkV14Bootsrapping(boolean loggWarning) { useDeprecatedV14Bootstrapping = getBooleanProperty( Constants.SERVLET_PARAMETER_USE_V14_BOOTSTRAP, false); if (loggWarning) { if (useDeprecatedV14Bootstrapping) { getLogger().info(WARNING_V14_BOOTSTRAP); } else if (!productionMode && getLogger().isInfoEnabled()) { String frontendDir = getStringProperty(PARAM_FRONTEND_DIR, System .getProperty(PARAM_FRONTEND_DIR, DEFAULT_FRONTEND_DIR)); String indexHTMLMessage = getIndexHTMLMessage(frontendDir); String entryPointMessage = getEntryPointMessage(frontendDir); getLogger().info(String.format(WARNING_V15_BOOTSTRAP, indexHTMLMessage, entryPointMessage)); } } }
Source:
public long getPositionsSizeInBytes(boolean[] positions) { int positionCount = getPositionCount(); checkValidPositions(positions, positionCount); boolean[] entryPositions = new boolean[getRawKeyBlock().getPositionCount()]; int usedEntryCount = 0; int usedPositionCount = 0; int end = Math.min(positionCount, positions.length); for (int i = 0; i < end; ++i) { if (positions[i]) { usedPositionCount++; int entriesStart = getOffsets()[getOffsetBase() + i]; int entriesEnd = getOffsets()[getOffsetBase() + i + 1]; for (int j = entriesStart; j < entriesEnd; j++) { entryPositions[j] = true; } usedEntryCount += (entriesEnd - entriesStart); } } long size = getRawKeyBlock().getPositionsSizeInBytes(entryPositions) + getRawValueBlock().getPositionsSizeInBytes(entryPositions) + (Integer.BYTES + Byte.BYTES) * (long) usedPositionCount + Integer.BYTES * HASH_MULTIPLIER * (long) usedEntryCount; return size; }

Target:
public long getPositionsSizeInBytes(boolean[] positions) { int positionCount = getPositionCount(); checkValidPositions(positions, positionCount); boolean[] entryPositions = booleanArrayPool.allocateAndInitialize(getRawKeyBlock().getPositionCount()); int usedEntryCount = 0; int usedPositionCount = 0; int end = Math.min(positionCount, positions.length); for (int i = 0; i < end; ++i) { if (positions[i]) { usedPositionCount++; int entriesStart = getOffsets()[getOffsetBase() + i]; int entriesEnd = getOffsets()[getOffsetBase() + i + 1]; for (int j = entriesStart; j < entriesEnd; j++) { entryPositions[j] = true; } usedEntryCount += (entriesEnd - entriesStart); } } booleanArrayPool.release(entryPositions); return getRawKeyBlock().getPositionsSizeInBytes(entryPositions) + getRawValueBlock().getPositionsSizeInBytes(entryPositions) + (Integer.BYTES + Byte.BYTES) * (long) usedPositionCount + Integer.BYTES * HASH_MULTIPLIER * (long) usedEntryCount; }
Source:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) { super.configurePipeline(pipelineConfigurer); FailureCollector failureCollector = pipelineConfigurer.getStageConfigurer().getFailureCollector(); createRecordTransformConfig.validate(failureCollector); Schema outputSchema = null; if (pipelineConfigurer.getStageConfigurer().getInputSchema() != null) { outputSchema = getOutputSchema(pipelineConfigurer.getStageConfigurer().getInputSchema(), failureCollector); } pipelineConfigurer.getStageConfigurer().setOutputSchema(outputSchema); }

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) { super.configurePipeline(pipelineConfigurer); FailureCollector failureCollector = pipelineConfigurer.getStageConfigurer().getFailureCollector(); createRecordTransformConfig.validate(failureCollector); if (pipelineConfigurer.getStageConfigurer().getInputSchema() != null && !createRecordTransformConfig.hasFieldsWithMacro()) { final Schema outputSchema = getOutputSchema(pipelineConfigurer.getStageConfigurer().getInputSchema(), failureCollector); pipelineConfigurer.getStageConfigurer().setOutputSchema(outputSchema); } }
Source:
private void applyEnabledProperty(boolean enabled, UIObject obj) { if(enabled) { obj.removeStyleName("disabled"); obj.getElement().removeAttribute(DISABLED); } else { obj.addStyleName("disabled"); obj.getElement().setAttribute(DISABLED, ""); } if(obj instanceof HasWidgets) { for(Widget widget: (HasWidgets) obj) { if(widget instanceof HasEnabled) { setEnabled(widget, enabled); } } } }

Target:
private void applyEnabledProperty(boolean enabled, UIObject obj) { if(enabled) { obj.removeStyleName("disabled"); obj.getElement().removeAttribute(DISABLED); } else { obj.addStyleName("disabled"); obj.getElement().setAttribute(DISABLED, ""); } }
Source:
public MetaCommand(Meta meta) { this.meta = meta; this.setCreated(meta.getCreated()); this.setLastModified(meta.getLastModified()); this.setLocation(meta.getLocation()); this.setResourceType(meta.getResourceType()); this.setVersion(meta.getVersion()); }

Target:
public MetaCommand(Meta meta) { this.setCreated(meta.getCreated()); this.setLastModified(meta.getLastModified()); this.setLocation(meta.getLocation()); this.setResourceType(meta.getResourceType()); this.setVersion(meta.getVersion()); }
Source:
public String getExportAsString(Dataset dataset, String formatName) { InputStream inputStream = null; InputStreamReader inp = null; try { inputStream = getExport(dataset, formatName); if (inputStream != null) { inp = new InputStreamReader(inputStream,"UTF8"); BufferedReader br = new BufferedReader(inp); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); sb.append('\n'); } br.close(); inp.close(); inputStream.close(); return sb.toString(); } } catch (ExportException | IOException ex) { return null; } finally { try{inp.close();} catch(IOException ic){} try{inputStream.close();} catch(IOException ic){} } return null; }

Target:
public String getExportAsString(Dataset dataset, String formatName) { InputStream inputStream = null; InputStreamReader inp = null; try { inputStream = getExport(dataset, formatName); if (inputStream != null) { inp = new InputStreamReader(inputStream, "UTF8"); BufferedReader br = new BufferedReader(inp); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); sb.append('\n'); } br.close(); inp.close(); inputStream.close(); return sb.toString(); } } catch (ExportException | IOException ex) { return null; } finally { IOUtils.closeQuietly(inp); IOUtils.closeQuietly(inputStream); } return null; }
Source:
public static String validate(String path) { Path p = new Path(path); if (p.toUri().getScheme() == null) { throw new IllegalArgumentException("Invalid path provided, no scheme in " + path); } return path; }

Target:
public static String validate(String path) { Path p = new Path(path); if (p.toUri().getScheme() == null) { throw new IllegalArgumentException("Invalid path provided, no scheme in " + path); } return p.toString(); }
Source:
public MacPool getMacPoolByName(String macPoolName) { return getAll().stream().filter(e -> e.getName().equals(macPoolName)).findFirst().orElse(null); }

Target:
public MacPool getMacPoolByName(String macPoolName) { return getCallsHandler().executeRead("GetMacPoolByMacPoolName", macPoolRowMapper, getCustomMapSqlParameterSource().addValue("name", macPoolName)); }
Source:
public static Context wbFromDMN(final JSITContext dmn, final JSITExpression parent, final BiConsumer<String, HasComponentWidths> hasComponentWidthsConsumer) { final Id id = IdPropertyConverter.wbFromDMN(dmn.getId()); final Description description = DescriptionPropertyConverter.wbFromDMN(dmn.getDescription()); final QName typeRef = QNamePropertyConverter.wbFromDMN(dmn.getTypeRef()); final Context result = new Context(id, description, typeRef); final List<JSITContextEntry> jsiContextEntries = dmn.getContextEntry(); for (int i = 0; i < jsiContextEntries.size(); i++) { final JSITContextEntry jsiContextentry = Js.uncheckedCast(jsiContextEntries.get(i)); final ContextEntry ceConverted = ContextEntryPropertyConverter.wbFromDMN(jsiContextentry, hasComponentWidthsConsumer); if (Objects.nonNull(ceConverted)) { ceConverted.setParent(result); result.getContextEntry().add(ceConverted); } } if (JSITFunctionDefinition.instanceOf(parent)) { final JSITFunctionDefinition functionDefinition = Js.uncheckedCast(parent); final String sKind = Js.uncheckedCast(functionDefinition.getKind()); final Kind kind = Kind.fromValue(sKind); if (!Kind.FEEL.equals(kind)) { return result; } } final int contextEntriesCount = result.getContextEntry().size(); if (contextEntriesCount == 0) { result.getContextEntry().add(new ContextEntry()); } else if (!Objects.isNull(result.getContextEntry().get(contextEntriesCount - 1).getVariable())) { result.getContextEntry().add(new ContextEntry()); } return result; }

Target:
public static Context wbFromDMN(final JSITContext dmn, final JSITExpression parent, final BiConsumer<String, HasComponentWidths> hasComponentWidthsConsumer) { final Id id = IdPropertyConverter.wbFromDMN(dmn.getId()); final Description description = DescriptionPropertyConverter.wbFromDMN(dmn.getDescription()); final QName typeRef = QNamePropertyConverter.wbFromDMN(dmn.getTypeRef()); final Context result = new Context(id, description, typeRef); final List<JSITContextEntry> jsiContextEntries = dmn.getContextEntry(); for (int i = 0; i < jsiContextEntries.size(); i++) { final JSITContextEntry jsiContextentry = Js.uncheckedCast(jsiContextEntries.get(i)); final ContextEntry ceConverted = ContextEntryPropertyConverter.wbFromDMN(jsiContextentry, hasComponentWidthsConsumer); if (Objects.nonNull(ceConverted)) { ceConverted.setParent(result); result.getContextEntry().add(ceConverted); } } if (JSITFunctionDefinition.instanceOf(parent)) { final JSITFunctionDefinition functionDefinition = Js.uncheckedCast(parent); final String sKind = Js.uncheckedCast(functionDefinition.getKind()); final Kind kind = Kind.fromValue(sKind); if (!Objects.equals(Kind.FEEL, kind)) { return result; } } final int contextEntriesCount = result.getContextEntry().size(); if (contextEntriesCount == 0) { result.getContextEntry().add(new ContextEntry()); } else if (!Objects.isNull(result.getContextEntry().get(contextEntriesCount - 1).getVariable())) { result.getContextEntry().add(new ContextEntry()); } return result; }
Source:
public static synchronized void logDebug(String message) { if (IntroPlugin.getDefault().isDebugging() && LOG_INFO) { getDefault().getLog().info(message); } }

Target:
public static synchronized void logDebug(String message) { if (LOG_INFO && IntroPlugin.getDefault().isDebugging()) { getDefault().getLog().info(message); } }
Source:
public int rank(final Set<ResourceType> resourceTypes, final Collection<ServiceConfiguration<?>> serviceConfigs) { if (SUPPORTED_RESOURCE_TYPES.containsAll(resourceTypes)) { return resourceTypes.size(); } else { return 0; } }

Target:
public int rank(final Set<ResourceType> resourceTypes, final Collection<ServiceConfiguration<?>> serviceConfigs) { if (SUPPORTED_RESOURCE_COMBINATIONS.contains(resourceTypes)) { return resourceTypes.size(); } else { return 0; } }
Source:
private double meanOfPointCollectionRoll( Collection<Points.Point<BasicRollup>> fullPoints ) { long sum = 0; int count = 0; for( Points.Point<BasicRollup> p : fullPoints ) { sum += p.getData().getAverage().toLong(); count++; } return sum / count; }

Target:
private double meanOfPointCollectionRoll( Collection<Points.Point<BasicRollup>> fullPoints ) { long sum = 0; for( Points.Point<BasicRollup> p : fullPoints ) { sum += p.getData().getAverage().toLong(); } return sum / fullPoints.size(); }
Source:
public TextPainter(final Composite parent) { this.parent = parent; Listener listener = new Listener() { public void handleEvent(Event event) { switch (event.type) { case SWT.Dispose: dispose(); break; } } }; parent.addListener(SWT.Dispose, listener); handCursor = new Cursor(parent.getDisplay(), SWT.CURSOR_HAND); text = ""; clipping = true; wrapping = true; textTokenizer = TextTokenizerFactory.createDefault(); foregroundColor = parent.getForeground(); hyperlinkColor = buildColor(100, 50, 200); boundaryColor = buildColor(255, 30, 30); FontData fontData = parent.getFont().getFontData()[0]; setFont(fontData.getName(), fontData.getHeight()); Point size = parent.getSize(); bounds = new Rectangle(0, 0, size.x, size.y); navigationListeners = new ArrayList<NavigationListener>(); hyperlinks = new ArrayList<Hyperlink>(); parent.addMouseMoveListener(new MouseMoveListener() { private Cursor defaultCursor = parent.getCursor(); @Override public void mouseMove(MouseEvent e) { for (Hyperlink hyperlink : hyperlinks) { if (hyperlink.contains(e.x, e.y)) { activeHyperlink = hyperlink; break; } else { activeHyperlink = null; } } if (activeHyperlink != null) { parent.setCursor(handCursor); } else { parent.setCursor(defaultCursor); } } }); parent.addMouseListener(new MouseListener() { @Override public void mouseUp(MouseEvent e) { if (activeHyperlink != null) { notifyNavigationListeners(activeHyperlink); } } @Override public void mouseDown(MouseEvent e) @Override public void mouseDoubleClick(MouseEvent e) }); }

Target:
public TextPainter(final Composite parent) { this.parent = parent; Listener listener = new Listener() { public void handleEvent(Event event) { switch (event.type) { case SWT.Dispose: dispose(); break; } } }; parent.addListener(SWT.Dispose, listener); handCursor = new Cursor(parent.getDisplay(), SWT.CURSOR_HAND); text = ""; clipping = true; wrapping = true; textTokenizer = TextTokenizerFactory.createDefault(); foregroundColor = parent.getForeground(); hyperlinkColor = buildColor(100, 50, 200); boundaryColor = buildColor(255, 30, 30); FontData fontData = parent.getFont().getFontData()[0]; setFont(fontData.getName(), fontData.getHeight()); Point size = parent.getSize(); bounds = new Rectangle(0, 0, size.x, size.y); navigationListeners = new ArrayList<NavigationListener>(); hyperlinks = new ArrayList<Hyperlink>(); parent.addMouseMoveListener(new MouseMoveListener() { private Cursor defaultCursor = parent.getCursor(); @Override public void mouseMove(MouseEvent e) { for (Hyperlink hyperlink : hyperlinks) { if (hyperlink.contains(e.x, e.y)) { activeHyperlink = hyperlink; break; } else { activeHyperlink = null; } } if (activeHyperlink != null) { parent.setCursor(handCursor); } else { parent.setCursor(defaultCursor); } } }); parent.addMouseListener(new MouseAdapter() { @Override public void mouseUp(MouseEvent e) { if (activeHyperlink != null) { notifyNavigationListeners(activeHyperlink); } } }); }