auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean proceedCommandExecutionFailed() { if (getParameters().getCommandStep() == RemoveSnapshotSingleDiskLiveStep.MERGE) { log.debug("Merge failed, retrying to recover from MERGE_STATUS step"); getParameters().setCommandStep(RemoveSnapshotSingleDiskLiveStep.MERGE_STATUS); return true; } if (getParameters().getCommandStep() == RemoveSnapshotSingleDiskLiveStep.MERGE_STATUS) { log.debug("Merge failed at MERGE_STATUS step"); if (getParameters().getMergeStatusReturnValue() != null && getParameters().getMergeStatusReturnValue().isMergeRunning()) { log.debug("Merge block job is still running, recovering from MERGE step"); getParameters().setCommandStep(RemoveSnapshotSingleDiskLiveStep.MERGE); return true; } setCommandStatus(CommandStatus.FAILED); return false; } if (getParameters().getCommandStep() == RemoveSnapshotSingleDiskLiveStep.DESTROY_IMAGE) { log.warn("Child command '{}' failed, proceeding to verify", getParameters().getCommandStep()); getParameters().setCommandStep(getParameters().getNextCommandStep()); return true; } log.error("Failed child command status for step '{}'", getParameters().getCommandStep()); setCommandStatus(CommandStatus.FAILED); return false; }

Target:
private boolean proceedCommandExecutionFailed() { if (getParameters().getCommandStep() == RemoveSnapshotSingleDiskLiveStep.MERGE) { log.warn("Merge failed, retrying to recover from MERGE_STATUS step"); getParameters().setCommandStep(RemoveSnapshotSingleDiskLiveStep.MERGE_STATUS); return true; } if (getParameters().getCommandStep() == RemoveSnapshotSingleDiskLiveStep.MERGE_STATUS) { log.warn("Merge failed at MERGE_STATUS step"); if (getParameters().getMergeStatusReturnValue() != null && getParameters().getMergeStatusReturnValue().isMergeRunning()) { log.info("Merge block job is still running, recovering from MERGE step"); getParameters().setCommandStep(RemoveSnapshotSingleDiskLiveStep.MERGE); return true; } setCommandStatus(CommandStatus.FAILED); return false; } if (getParameters().getCommandStep() == RemoveSnapshotSingleDiskLiveStep.DESTROY_IMAGE) { log.warn("Child command '{}' failed, proceeding to verify", getParameters().getCommandStep()); getParameters().setCommandStep(getParameters().getNextCommandStep()); return true; } log.error("Failed child command status for step '{}'", getParameters().getCommandStep()); setCommandStatus(CommandStatus.FAILED); return false; }
Source:
public synchronized void chooseSinks() { List<ServerName> slaveAddresses = endpoint.getRegionServers(); if(slaveAddresses==null){ LOG.warn("No sinks available at peer. Will not be able to replicate"); sinks = new ArrayList<ServerName>(); } else { Collections.shuffle(slaveAddresses, ThreadLocalRandom.current()); int numSinks = (int) Math.ceil(slaveAddresses.size() * ratio); sinks = slaveAddresses.subList(0, numSinks); } lastUpdateToPeers = System.currentTimeMillis(); badReportCounts.clear(); }

Target:
public synchronized void chooseSinks() { List<ServerName> slaveAddresses = endpoint.getRegionServers(); if(slaveAddresses.isEmpty()){ LOG.warn("No sinks available at peer. Will not be able to replicate"); } Collections.shuffle(slaveAddresses, ThreadLocalRandom.current()); int numSinks = (int) Math.ceil(slaveAddresses.size() * ratio); sinks = slaveAddresses.subList(0, numSinks); lastUpdateToPeers = System.currentTimeMillis(); badReportCounts.clear(); }
Source:
private void optOut() { String token = mUser.getAccountToken(); String metricType = mSettings.getSurveyType(); String endUserId = Long.toString(mEndUser.getId()); String endUserEmail = mEndUser.getEmail(); String uniqueLink = mUniqueLink; String optOutToken = mAccessToken; String optOutUrl = "<LINK_0>" + token + "&metric_type=" + metricType + "&end_user_id=" + endUserId + "&end_user_email=" + endUserEmail + "&unique_link=" + uniqueLink + "&opt_out_token=" + optOutToken; Intent optOut = new Intent(Intent.ACTION_VIEW, Uri.parse(optOutUrl)); startActivity(optOut); }

Target:
private void optOut() { String optOutUrl = "<LINK_0>" + mUser.getAccountToken() + "&metric_type=" + mSettings.getSurveyType() + "&end_user_id=" + Long.toString(mEndUser.getId()) + "&end_user_email=" + mEndUser.getEmail() + "&unique_link=" + mUniqueLink + "&opt_out_token=" + mAccessToken; Intent optOut = new Intent(Intent.ACTION_VIEW, Uri.parse(optOutUrl)); startActivity(optOut); dismiss(); }
Source:
public void testSimple() { CachingConnectionFactory cf = new CachingConnectionFactory("localhost"); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setThreadNamePrefix("client-"); executor.afterPropertiesSet(); cf.setExecutor(executor); DirectMessageListenerContainer container = new DirectMessageListenerContainer(cf); container.setQueueNames(Q1, Q2); container.setConsumersPerQueue(2); container.setMessageListener(new MessageListenerAdapter((ReplyingMessageListener<String, String>) in -> { LogFactory.getLog(this.getClass()).info(in); if ("foo".equals(in) || "bar".equals(in)) { return in.toUpperCase(); } else { return null; } })); container.afterPropertiesSet(); container.start(); RabbitTemplate template = new RabbitTemplate(cf); assertEquals("FOO", template.convertSendAndReceive(Q1, "foo")); assertEquals("BAR", template.convertSendAndReceive(Q2, "bar")); }

Target:
public void testSimple() { CachingConnectionFactory cf = new CachingConnectionFactory("localhost"); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setThreadNamePrefix("client-"); executor.afterPropertiesSet(); cf.setExecutor(executor); DirectMessageListenerContainer container = new DirectMessageListenerContainer(cf); container.setQueueNames(Q1, Q2); container.setConsumersPerQueue(2); container.setMessageListener(new MessageListenerAdapter((ReplyingMessageListener<String, String>) in -> { if ("foo".equals(in) || "bar".equals(in)) { return in.toUpperCase(); } else { return null; } })); container.afterPropertiesSet(); container.start(); RabbitTemplate template = new RabbitTemplate(cf); assertEquals("FOO", template.convertSendAndReceive(Q1, "foo")); assertEquals("BAR", template.convertSendAndReceive(Q2, "bar")); }
Source:
public void testFreeStyleAntOnSlave() throws Exception { Assume.assumeTrue((jenkins.getDescriptorByType(Ant.DescriptorImpl.class).getInstallations().length > 0); FreeStyleProject project = createFreeStyleProject(); project.setJDK(jenkins.getJDK("varJDK")); project.setScm(new ExtractResourceSCM(getClass().getResource( "/simple-projects.zip"))); String buildFile = "build.xml${" + DUMMY_LOCATION_VARNAME + "}"; project.getBuildersList().add( new Ant("-Dtest.property=cor${" + DUMMY_LOCATION_VARNAME + "}rect", "varAnt", "", buildFile, "")); project.setAssignedLabel(slaveRegular.getSelfLabel()); FreeStyleBuild build = project.scheduleBuild2(0).get(); System.out.println(build.getDisplayName() + " completed"); assertBuildStatus(Result.FAILURE, build); String buildLogRegular = getBuildLog(build); assertTrue(buildLogRegular.contains(Ant_ExecutableNotFound("varAnt"))); project.setAssignedLabel(slaveEnv.getSelfLabel()); build = project.scheduleBuild2(0).get(); System.out.println(build.getDisplayName() + " completed"); assertBuildStatusSuccess(build); String buildLogEnv = getBuildLog(build); System.out.println(buildLogEnv); assertTrue(buildLogEnv.contains("Ant home: ")); assertTrue(buildLogEnv.contains("Test property: correct")); assertFalse(buildLogEnv.matches("(?s)^.*Ant home: [^\\n\\r]*" + DUMMY_LOCATION_VARNAME + ".*$")); assertFalse(buildLogEnv.matches("(?s)^.*Test property: [^\\n\\r]*" + DUMMY_LOCATION_VARNAME + ".*$")); }

Target:
public void testFreeStyleAntOnSlave() throws Exception { Assume.assumeFalse( "Cannot do testFreeStyleAntOnSlave without ANT_HOME", jenkins.getDescriptorByType(Ant.DescriptorImpl.class).getInstallations().length == 0 ); FreeStyleProject project = createFreeStyleProject(); project.setJDK(jenkins.getJDK("varJDK")); project.setScm(new ExtractResourceSCM(getClass().getResource( "/simple-projects.zip"))); String buildFile = "build.xml${" + DUMMY_LOCATION_VARNAME + "}"; project.getBuildersList().add( new Ant("-Dtest.property=cor${" + DUMMY_LOCATION_VARNAME + "}rect", "varAnt", "", buildFile, "")); project.setAssignedLabel(slaveRegular.getSelfLabel()); FreeStyleBuild build = project.scheduleBuild2(0).get(); System.out.println(build.getDisplayName() + " completed"); assertBuildStatus(Result.FAILURE, build); String buildLogRegular = getBuildLog(build); assertTrue(buildLogRegular.contains(Ant_ExecutableNotFound("varAnt"))); project.setAssignedLabel(slaveEnv.getSelfLabel()); build = project.scheduleBuild2(0).get(); System.out.println(build.getDisplayName() + " completed"); assertBuildStatusSuccess(build); String buildLogEnv = getBuildLog(build); System.out.println(buildLogEnv); assertTrue(buildLogEnv.contains("Ant home: ")); assertTrue(buildLogEnv.contains("Test property: correct")); assertFalse(buildLogEnv.matches("(?s)^.*Ant home: [^\\n\\r]*" + DUMMY_LOCATION_VARNAME + ".*$")); assertFalse(buildLogEnv.matches("(?s)^.*Test property: [^\\n\\r]*" + DUMMY_LOCATION_VARNAME + ".*$")); }
Source:
public int read() throws IOException { try { return RetryUtils.retry( delegate::read, retryCondition, maxTry ); } catch (Exception e) { throw new IOException(e); } }

Target:
public int read() throws IOException { for (int nTry = 0; nTry < maxRetry; nTry++) { try { return delegate.read(); } catch (Throwable t) { waitOrThrow(t, nTry); } } return delegate.read(); }
Source:
public static void main(String[] args) throws InterruptedException { String connectionString = "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};" + "SharedAccessKey={key}"; ServiceBusSessionReceiverAsyncClient sessionReceiver = new ServiceBusClientBuilder() .connectionString(connectionString) .sessionReceiver() .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .topicName("<<topic-name>>") .subscriptionName("<<subscription-name>>") .buildAsyncClient(); Mono<ServiceBusReceiverAsyncClient> receiverMono = sessionReceiver.acceptNextSession(); Disposable subscription = receiverMono.flatMapMany(receiver -> receiver.receiveMessages()) .subscribe(message -> { System.out.printf("Session: %s. Sequence #: %s. Contents: %s%n", message.getSessionId(), message.getSequenceNumber(), message.getBody()); }, error -> System.err.println("Error occurred: " + error)); TimeUnit.SECONDS.sleep(60); subscription.dispose(); sessionReceiver.close(); }

Target:
public static void main(String[] args) throws InterruptedException { String connectionString = "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};" + "SharedAccessKey={key}"; ServiceBusSessionReceiverAsyncClient sessionReceiver = new ServiceBusClientBuilder() .connectionString(connectionString) .sessionReceiver() .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .topicName("<<topic-name>>") .subscriptionName("<<subscription-name>>") .buildAsyncClient(); Mono<ServiceBusReceiverAsyncClient> receiverMono = sessionReceiver.acceptNextSession(); Disposable subscription = Flux.usingWhen(receiverMono, receiver -> receiver.receiveMessages(), receiver -> Mono.fromRunnable(() -> receiver.close())) .subscribe(message -> { System.out.printf("Session: %s. Sequence #: %s. Contents: %s%n", message.getSessionId(), message.getSequenceNumber(), message.getBody()); }, error -> System.err.println("Error occurred: " + error)); TimeUnit.SECONDS.sleep(60); subscription.dispose(); sessionReceiver.close(); }
Source:
public RepositoryGroups() { List<String> groups = split( preferences.get(PREFS_GROUPS, EMPTY_STRING)); for (String groupUUIDString : groups) { UUID groupUUIDuuid = UUID.fromString(groupUUIDString); String name = preferences .get(PREFS_GROUP_NAME_PREFIX + groupUUIDString, EMPTY_STRING); List<String> repos = split( preferences.get(PREFS_GROUP_PREFIX + groupUUIDString, EMPTY_STRING)); RepositoryGroup group = new RepositoryGroup(groupUUIDuuid, name, repos); groupMap.put(groupUUIDuuid, group); } }

Target:
public RepositoryGroups() { List<String> groups = split( preferences.get(PREFS_GROUPS, EMPTY_STRING)); for (String groupIdString : groups) { UUID groupId = UUID.fromString(groupIdString); String name = preferences .get(PREFS_GROUP_NAME_PREFIX + groupIdString, EMPTY_STRING); List<String> repos = split(preferences .get(PREFS_GROUP_PREFIX + groupIdString, EMPTY_STRING)); RepositoryGroup group = new RepositoryGroup(groupId, name, repos); groupMap.put(groupId, group); } }
Source:
protected Function<Object, IterableWithMarker<Image>> markerToNextForArgs(final List<Object> args) { if (args == null || args.isEmpty()) throw new IllegalStateException("Can't advance the PagedIterable"); final String regionId = args.get(0).toString(); final Optional<Object> optionalPaginationOptions = Optional.fromNullable(!args.isEmpty() && args.size() == 2 ? args.get(1) : null); final ListImagesOptions original = (ListImagesOptions) optionalPaginationOptions.orNull(); return new Function<Object, IterableWithMarker<Image>>() { @Override public IterableWithMarker<Image> apply(Object input) { ListImagesOptions options = original == null ? ListImagesOptions.Builder.paginationOptions(PaginationOptions.class.cast(input)) : original.paginationOptions(PaginationOptions.class.cast(input)); return api.imageApi().list(regionId, options); } }; }

Target:
protected Function<Object, IterableWithMarker<Image>> markerToNextForArgs(final List<Object> args) { if (args == null || args.isEmpty()) throw new IllegalStateException("Can't advance the PagedIterable"); final String regionId = args.get(0).toString(); final ListImagesOptions original = (ListImagesOptions) Iterables.tryFind(args, Predicates.instanceOf(ListImagesOptions.class)).orNull(); return new Function<Object, IterableWithMarker<Image>>() { @Override public IterableWithMarker<Image> apply(Object input) { ListImagesOptions options = original == null ? ListImagesOptions.Builder.paginationOptions(PaginationOptions.class.cast(input)) : original.paginationOptions(PaginationOptions.class.cast(input)); return api.imageApi().list(regionId, options); } }; }
Source:
public void validate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject originalObject = update.getReferenceObject(); if (! OrgType.LIR.getName().equals(originalObject.getValueForAttribute(AttributeType.ORG_TYPE))) { return; } final RpslObject updatedObject = update.getUpdatedObject(); final Collection<CIString> userMntner = filterUserMntner(updatedObject); if (userMntner.size() > 1) { updateContext.addMessage(update, UpdateMessages.multipleUserMntBy(userMntner)); } }

Target:
public void validate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject originalObject = update.getReferenceObject(); if (!isLir(originalObject)) { return; } final RpslObject updatedObject = update.getUpdatedObject(); final Collection<CIString> userMntner = filterUserMntner(updatedObject); if (userMntner.size() > 1) { updateContext.addMessage(update, UpdateMessages.multipleUserMntBy(userMntner)); } }
Source:
private void nativeOpenFile(String filePath) { if (Desktop.isDesktopSupported()) { new Thread(() -> { try { File file = new File(filePath); Desktop.getDesktop().open(file); LOGGER.info("Opened file with Desktop integration"); } catch (Exception e) { LOGGER.error("Open operation not successful: " + e.getMessage()); } }).start(); } else { LOGGER.error("No operation possible"); } }

Target:
private void nativeOpenFile(String filePath) { JabRefExecutorService.INSTANCE.execute(() -> { try { File file = new File(filePath); Desktop.getDesktop().open(file); System.out.println("Open file in default application with Desktop integration"); } catch (IllegalArgumentException e) { System.out.println("Fail back to xdg-open"); try { String[] cmd = {"xdg-open", filePath}; Runtime.getRuntime().exec(cmd); } catch (Exception e2) { System.out.println("Open operation not successful: " + e2); } } catch (IOException e) { System.out.println("Native open operation not successful: " + e); } }); }
Source:
public String value() { this.lastAccessTime = System.currentTimeMillis(); return this.value; }

Target:
public String value() { return this.value; }
Source:
private String uriToPath(final String URI) { if (URI.startsWith(baseUri)) { return URI.substring(baseUri.length()); } else { return URI; } }

Target:
private String uriToPath(final String URI) { if (URI.startsWith(baseUri)) { return URI.substring(baseUri.length()); } return URI; }
Source:
public IBuildConfiguration[] getAllBuildConfigReferences(String configName, boolean makeCopy) { if (!hasBuildConfig(configName)) return EMPTY_BUILD_CONFIG_REFERENCE_ARRAY; IBuildConfiguration[] refs = cachedConfigRefs.get(configName); if (refs == null) { Set<IBuildConfiguration> references = new LinkedHashSet<>(); IBuildConfiguration[] dynamicBuildConfigs = dynamicConfigRefs.containsKey(configName) ? dynamicConfigRefs.get(configName) : EMPTY_BUILD_CONFIG_REFERENCE_ARRAY; Collection<BuildConfiguration> dynamic = getBuildConfigReferencesFromProjects(ProjectDescription.computeDynamicReferencesForProject(getName(), configName, getBuildSpec())); Collection<BuildConfiguration> legacyDynamic = getBuildConfigReferencesFromProjects(dynamicRefs); Collection<BuildConfiguration> statik = getBuildConfigReferencesFromProjects(staticRefs); references.addAll(Arrays.asList(dynamicBuildConfigs)); references.addAll(statik); references.addAll(legacyDynamic); references.addAll(dynamic); refs = references.toArray(new IBuildConfiguration[references.size()]); cachedConfigRefs.put(configName, refs); } return makeCopy ? (IBuildConfiguration[]) refs.clone() : refs; }

Target:
public IBuildConfiguration[] getAllBuildConfigReferences(String configName, boolean makeCopy) { if (!hasBuildConfig(configName)) return EMPTY_BUILD_CONFIG_REFERENCE_ARRAY; IBuildConfiguration[] refs = cachedConfigRefs.get(configName); if (refs == null) { Set<IBuildConfiguration> references = new LinkedHashSet<>(); IBuildConfiguration[] dynamicBuildConfigs = dynamicConfigRefs.containsKey(configName) ? dynamicConfigRefs.get(configName) : EMPTY_BUILD_CONFIG_REFERENCE_ARRAY; IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(getName()); Collection<BuildConfiguration> dynamic; try { IBuildConfiguration buildConfig = project.getBuildConfig(configName); dynamic = getBuildConfigReferencesFromProjects(computeDynamicReferencesForProject(buildConfig, getBuildSpec())); } catch (CoreException e) { dynamic = Collections.emptyList(); } Collection<BuildConfiguration> legacyDynamic = getBuildConfigReferencesFromProjects(dynamicRefs); Collection<BuildConfiguration> statik = getBuildConfigReferencesFromProjects(staticRefs); references.addAll(Arrays.asList(dynamicBuildConfigs)); references.addAll(statik); references.addAll(legacyDynamic); references.addAll(dynamic); refs = references.toArray(new IBuildConfiguration[references.size()]); cachedConfigRefs.put(configName, refs); } return makeCopy ? (IBuildConfiguration[]) refs.clone() : refs; }
Source:
public static Object valuesFor(DCValue[] values) { if (values.length == 0) { return null; } if (values.length ==1 ) { return values[0].value; } String vals[] = new String[values.length]; for (int i = 0; i < values.length; i++) { vals[i] = values[i].value; } return vals; }

Target:
public static String[] valuesFor(DCValue[] values) { String vals[] = new String[values.length]; for (int i = 0; i < values.length; i++) { vals[i] = values[i].value; } return vals; }
Source:
public static void copyStreamAndClose(@Nonnull Reader in, @Nonnull Writer out) throws IOException { try { copyStream(in,out); } finally { in.close(); out.close(); } }

Target:
public static void copyStreamAndClose(@Nonnull Reader in, @Nonnull Writer out) throws IOException { try (Reader _in = in; Writer _out = out) { copyStream(in,out); } }
Source:
private void clickPopup(final int buttonNo) { if (AbstractScene.getPopup() != null) { ObservableList<Node> buttons; sleep(1); buttons = ((VBox) AbstractScene.getPopup().getContent().get(1)) .getChildren(); buttons = ((HBox) buttons.get(buttons.size() - 1)).getChildren(); try { clickOn(buttons.get(buttonNo), MouseButton.PRIMARY); } catch (ArrayIndexOutOfBoundsException e) { fail("ButtonNo " + buttonNo + " does not exist"); } sleep(SHORT); } }

Target:
private void clickPopup(final int buttonNo) { if (AbstractScene.getPopup() == null) { fail("There is no popup available in AbstractScene!"); } else { ObservableList<Node> buttons; sleep(1); buttons = ((VBox) AbstractScene.getPopup().getContent().get(1)) .getChildren(); buttons = ((HBox) buttons.get(buttons.size() - 1)).getChildren(); try { clickOn(buttons.get(buttonNo), MouseButton.PRIMARY); } catch (ArrayIndexOutOfBoundsException e) { fail("ButtonNo " + buttonNo + " does not exist"); } sleep(SHORT); } }
Source:
private void fireContainerInitializedEvent() { beanManager().fireEvent(new ContainerInitialized(id), Initialized.Literal.APPLICATION); WeldSELogger.LOG.weldContainerInitialized(id); }

Target:
private void fireContainerInitializedEvent() { WeldSELogger.LOG.weldContainerInitialized(id); beanManager().fireEvent(new ContainerInitialized(id), Initialized.Literal.APPLICATION); }
Source:
private static List<SiteModel> getSelfHostedSitesFromDeprecatedDB(Context context) { List<SiteModel> siteList = new ArrayList<>(); try { SQLiteDatabase db = context.getApplicationContext().openOrCreateDatabase(DEPRECATED_DATABASE_NAME, 0, null); String[] fields = new String[]{"username", "password", "url"}; String byString = "dotcomFlag=0"; Cursor c = db.query(DEPRECATED_BLOGS_TABLE, fields, byString, null, null, null, null); int numRows = c.getCount(); c.moveToFirst(); for (int i = 0; i < numRows; i++) { SiteModel siteModel = new SiteModel(); siteModel.setUsername(c.getString(0)); siteModel.setPassword(c.getString(1)); siteModel.setUrl(c.getString(2)); siteList.add(siteModel); c.moveToNext(); } c.close(); } catch (SQLException e) { } return siteList; }

Target:
private static List<SiteModel> getSelfHostedSitesFromDeprecatedDB(Context context) { List<SiteModel> siteList = new ArrayList<>(); try { SQLiteDatabase db = context.getApplicationContext().openOrCreateDatabase(DEPRECATED_DATABASE_NAME, 0, null); String[] fields = new String[]{"username", "password", "url"}; String byString = String.format("dotcomFlag=0 AND NOT(dotcomFlag=0 AND password='%s')", encryptPassword("")); Cursor c = db.query(DEPRECATED_BLOGS_TABLE, fields, byString, null, null, null, null); int numRows = c.getCount(); c.moveToFirst(); for (int i = 0; i < numRows; i++) { SiteModel siteModel = new SiteModel(); siteModel.setUsername(c.getString(0)); String encryptedPwd = c.getString(1); siteModel.setPassword(decryptPassword(encryptedPwd)); String url = c.getString(2); siteModel.setUrl(url); siteModel.setXmlRpcUrl(url); siteList.add(siteModel); c.moveToNext(); } c.close(); } catch (SQLException e) { } return siteList; }
Source:
public synchronized void handleDataDeleted(String s) throws Exception { if (_zkClient.isClosed()) { return; } _zkClient.unsubscribeAll(); _zkClient.subscribeChildChanges(MetadataStoreRoutingConstants.ROUTING_DATA_PATH, this); for (String child : _zkClient.getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH)) { _zkClient.subscribeDataChanges(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + child, this); } _routingDataListener.updateRoutingData(_namespace); }

Target:
public synchronized void handleDataDeleted(String s) throws Exception { if (_zkClient.isClosed()) { return; } _zkClient.subscribeChildChanges(MetadataStoreRoutingConstants.ROUTING_DATA_PATH, this); for (String child : _zkClient.getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH)) { _zkClient.subscribeDataChanges(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + child, this); } _routingDataListener.refreshRoutingData(_namespace); }
Source:
public void deserializationHandlesNullRoles() throws Exception { CrewMember crewMember = new CrewMember("uri", "", Publisher.METABROADCAST); crewMember.withRole(null); assertThat( serialization.deserialize( serialization.serialize( crewMember ) ) .role(), is(nullValue()) ); }

Target:
public void deserializationHandlesNullRoles() throws Exception { @SuppressWarnings("ConstantConditions") CrewMember crewMember = new CrewMember("uri", "", Publisher.METABROADCAST) .withRole(null); assertThat( serialization.deserialize( serialization.serialize( crewMember ) ) .role(), is(nullValue()) ); }
Source:
public void linkRequested() { assertLockHeld(); Binding<?> binding; while ((binding = toLink.poll()) != null) { if (binding instanceof DeferredBinding) { DeferredBinding deferredBinding = (DeferredBinding) binding; String key = deferredBinding.deferredKey; boolean mustBeInjectable = deferredBinding.mustBeInjectable; if (bindings.containsKey(key)) { continue; } try { Binding<?> jitBinding = createJitBinding(key, binding.requiredBy, mustBeInjectable); jitBinding.setNecessary(binding.necessary()); jitBinding.setDependedOn(binding.dependedOn()); if (!key.equals(jitBinding.provideKey) && !key.equals(jitBinding.membersKey)) { throw new IllegalStateException("Unable to create binding for " + key); } Binding<?> scopedJitBinding = scope(jitBinding); toLink.add(scopedJitBinding); putBinding(scopedJitBinding); } catch (Exception e) { if (e.getMessage() != null) { addError(e.getMessage() + " required by " + binding.requiredBy); bindings.put(key, Binding.UNRESOLVED); } else if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new RuntimeException(e); } } } else { attachSuccess = true; binding.attach(this); if (attachSuccess) { binding.setLinked(); } else { toLink.add(binding); } } } try { errorHandler.handleErrors(errors); } finally { errors.clear(); } }

Target:
public void linkRequested() { assertLockHeld(); Binding<?> binding; while ((binding = toLink.poll()) != null) { if (binding instanceof DeferredBinding) { DeferredBinding deferredBinding = (DeferredBinding) binding; String key = deferredBinding.deferredKey; boolean mustBeInjectable = deferredBinding.mustBeInjectable; if (bindings.containsKey(key)) { continue; } try { Binding<?> jitBinding = createJitBinding(key, binding.requiredBy, mustBeInjectable); jitBinding.setLibrary(binding.library()); jitBinding.setDependedOn(binding.dependedOn()); if (!key.equals(jitBinding.provideKey) && !key.equals(jitBinding.membersKey)) { throw new IllegalStateException("Unable to create binding for " + key); } Binding<?> scopedJitBinding = scope(jitBinding); toLink.add(scopedJitBinding); putBinding(scopedJitBinding); } catch (Exception e) { if (e.getMessage() != null) { addError(e.getMessage() + " required by " + binding.requiredBy); bindings.put(key, Binding.UNRESOLVED); } else if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new RuntimeException(e); } } } else { attachSuccess = true; binding.attach(this); if (attachSuccess) { binding.setLinked(); } else { toLink.add(binding); } } } try { errorHandler.handleErrors(errors); } finally { errors.clear(); } }
Source:
public static boolean isSystemProtocol(Collaboration element) { return (UMLUtil.getStereotypeApplication(element, SystemProtocol.class) != null) ? true : false; }

Target:
public static boolean isSystemProtocol(Collaboration element) { return (UMLUtil.getStereotypeApplication(element, SystemProtocol.class) != null); }
Source:
public void commit() throws TransactionException { final MessagingTransaction transaction = getCurrentTransaction(); logger.trace("Committing transaction: " + transaction.transactionId()); transaction.applyActions(messagePublisher); currentTransaction.remove(); logger.trace("Transaction successfully commit: " + transaction.transactionId()); }

Target:
public void commit() throws TransactionException { final MessagingTransaction transaction = getCurrentTransaction(); logger.trace("Committing transaction: " + transaction.transactionId()); transaction.applyActions(messagePublisher); currentTransaction.remove(); logger.trace("Transaction successfully committed: " + transaction.transactionId()); }
Source:
static Platform parsePlatform(@Nullable PlatformInfo executionPlatform, @Nullable String defaultPlatformProperties) { Platform.Builder platformBuilder = Platform.newBuilder(); if (executionPlatform != null && !Strings.isNullOrEmpty(executionPlatform.remoteExecutionProperties())) { try { TextFormat.getParser().merge(executionPlatform.remoteExecutionProperties(), platformBuilder); } catch (ParseException e) { throw new IllegalArgumentException( String.format( "Failed to parse remote_execution_properties from platform %s", executionPlatform.label()), e); } } else if (!Strings.isNullOrEmpty(defaultPlatformProperties)) { try { TextFormat.getParser().merge(defaultPlatformProperties, platformBuilder); } catch (ParseException e) { throw new IllegalArgumentException( String.format("Failed to parse --remote_default_platform_properties %s", defaultPlatformProperties), e); } } List<Platform.Property> properties = platformBuilder.getPropertiesList(); platformBuilder.clearProperties(); platformBuilder.addAllProperties( Ordering.from(Comparator.comparing(Platform.Property::getName)).sortedCopy(properties)); return platformBuilder.build(); }

Target:
static Platform parsePlatform( @Nullable PlatformInfo executionPlatform, @Nullable String defaultPlatformProperties) throws UserExecException { if (executionPlatform == null && Strings.isNullOrEmpty(defaultPlatformProperties)) { return null; } Platform.Builder platformBuilder = Platform.newBuilder(); if (executionPlatform != null && !Strings.isNullOrEmpty(executionPlatform.remoteExecutionProperties())) { try { TextFormat.getParser().merge(executionPlatform.remoteExecutionProperties(), platformBuilder); } catch (ParseException e) { throw new UserExecException( String.format( "Failed to parse remote_execution_properties from platform %s", executionPlatform.label()), e); } } else if (!Strings.isNullOrEmpty(defaultPlatformProperties)) { try { TextFormat.getParser().merge(defaultPlatformProperties, platformBuilder); } catch (ParseException e) { throw new UserExecException( String.format( "Failed to parse --remote_default_platform_properties %s", defaultPlatformProperties), e); } } List<Platform.Property> properties = platformBuilder.getPropertiesList(); platformBuilder.clearProperties(); platformBuilder.addAllProperties( Ordering.from(Comparator.comparing(Platform.Property::getName)).sortedCopy(properties)); return platformBuilder.build(); }
Source:
public boolean isValid() { Token userToken = getSyncUser().getUserToken(); return syncUser.isLoggedIn() && SyncManager.getUserStore().isActive(syncUser.getIdentity()) && userToken != null && userToken.expiresMs() > System.currentTimeMillis(); }

Target:
public boolean isValid() { Token userToken = getSyncUser().getUserToken(); return syncUser.isLoggedIn() && userToken != null && userToken.expiresMs() > System.currentTimeMillis() && SyncManager.getUserStore().isActive(syncUser.getIdentity()); }
Source:
default String headerFormat() { StringBuilder builder = new StringBuilder(serviceName()); instanceId().ifPresent(id -> builder.append("/").append(id)); builder.append(" (").append(version()).append(")"); return builder.toString(); }

Target:
default String headerFormat() { return Joiner.on(", ").join(Lists.transform(agents(), Agent::headerFormat)); }
Source:
private String cacheSensorPrefix(final String threadId, final String taskId, final String cacheName) { return taskSensorPrefix(threadId, taskId) + SENSOR_PREFIX_DELIMITER + "cache" + SENSOR_PREFIX_DELIMITER + cacheName; }

Target:
private String cacheSensorPrefix(final String threadId, final String taskId, final String cacheName) { return taskSensorPrefix(threadId, taskId) + SENSOR_PREFIX_DELIMITER + SENSOR_CACHE_LABEL + SENSOR_PREFIX_DELIMITER + cacheName; }
Source:
public void work() { openSystemSession(); RetentionManager retentionManager = Framework.getService(RetentionManager.class); for (String string : docIds) { DocumentModel doc; try { doc = session.getDocument(new IdRef(string)); } catch (DocumentNotFoundException e) { log.warn("Document impacted by retention no longer exists {}", string); continue; } Record record = doc.getAdapter(Record.class); if (record == null) { log.warn("Document should be impacted by retention but is no longer a Record: {}", string); continue; } retentionManager.evalExpressionEventBasedRules(record, docsToCheckAndEvents.get(string), session); } }

Target:
public void work() { openSystemSession(); RetentionManager retentionManager = Framework.getService(RetentionManager.class); for (String docId : docIds) { DocumentModel doc; try { doc = session.getDocument(new IdRef(docId)); } catch (DocumentNotFoundException e) { log.warn("Document impacted by retention no longer exists {}", docId); continue; } Record record = doc.getAdapter(Record.class); if (record == null) { log.warn("Document should be impacted by retention but is no longer a Record: {}", docId); continue; } retentionManager.evalExpressionEventBasedRules(record, docsToCheckAndEvents.get(docId), session); } }
Source:
public void handle(Request request, Response response) throws Exception { String projectKey = request.mandatoryParam(PARAM_PROJECT); List<String> tags = request.mandatoryParamAsStrings(PARAM_TAGS).stream() .filter(StringUtils::isNotBlank) .map(t -> t.toLowerCase(Locale.ENGLISH)) .map(SetAction::checkTag) .distinct() .collect(Collectors.toList()); try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto project = componentFinder.getByKey(dbSession, projectKey); checkRequest(Qualifiers.PROJECT.equals(project.qualifier()), "Component '%s' is not a project", project.key()); userSession.checkComponentUuidPermission(UserRole.ADMIN, project.uuid()); project.setTags(tags); dbClient.componentDao().updateTags(dbSession, project); dbSession.commit(); indexers.forEach(i -> i.indexProject(project.uuid(), PROJECT_TAGS_UPDATE)); } response.noContent(); }

Target:
public void handle(Request request, Response response) throws Exception { String projectKey = request.mandatoryParam(PARAM_PROJECT); List<String> tags = request.mandatoryParamAsStrings(PARAM_TAGS).stream() .filter(StringUtils::isNotBlank) .map(t -> t.toLowerCase(Locale.ENGLISH)) .map(SetAction::checkTag) .distinct() .collect(Collectors.toList()); try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto project = componentFinder.getByKey(dbSession, projectKey); checkRequest(PROJECT.equals(project.qualifier()), "Component '%s' is not a project", project.key()); userSession.checkComponentUuidPermission(UserRole.ADMIN, project.uuid()); project.setTags(tags); dbClient.componentDao().updateTags(dbSession, project); dbSession.commit(); indexers.forEach(i -> i.indexProject(project.uuid(), PROJECT_TAGS_UPDATE)); } response.noContent(); }
Source:
void handleTermination(final SchedulingService service) throws IOException, ClassNotFoundException { for (TaskTerminationData taskToTerminate : tasksToTerminate.values()) { RunningTaskData taskData = taskToTerminate.taskData; if (!taskToTerminate.killedWhileNotRunning()) { Map<String, String> genericInformation = new HashMap<>(); VariablesMap variables = null; if (taskToTerminate.internalJob != null) { genericInformation = taskData.getTask().getRuntimeGenericInformation(); } try { variables = getStringSerializableMap(service, taskToTerminate); } catch (Exception e) { logger.error("Exception occurred, fail to get variables into the cleaning script: ", e); } try { if (!taskToTerminate.normalTermination) { taskData.getLauncher().kill(); } } catch (Throwable t) { logger.info("Cannot terminate task launcher for task '" + taskData.getTask().getId() + "'", t); try { logger.info("Task launcher that cannot be terminated is identified by " + taskData.getLauncher().toString()); } catch (Throwable ignore) { logger.info("Getting information about Task launcher failed (remote object not accessible?)"); } } try { logger.debug("Releasing nodes for task '" + taskData.getTask().getId() + "'"); RMProxiesManager proxiesManager = service.getInfrastructure().getRMProxiesManager(); proxiesManager.getUserRMProxy(taskData.getUser(), taskData.getCredentials()) .releaseNodes(taskData.getNodes(), taskData.getTask().getCleaningScript(), variables, genericInformation, taskToTerminate.taskData.getTask().getId()); } catch (Throwable t) { logger.info("Failed to release nodes for task '" + taskData.getTask().getId() + "'", t); } } } for (final TaskRestartData restartData : tasksToRestart.values()) { service.getInfrastructure().schedule(new Runnable() { public void run() { service.getJobs().restartWaitingTask(restartData.taskId); } }, restartData.waitTime); } for (JobId jobId : jobsToTerminate) { service.terminateJobHandling(jobId); } }

Target:
void handleTermination(final SchedulingService service) throws IOException, ClassNotFoundException { for (TaskTerminationData taskToTerminate : tasksToTerminate.values()) { RunningTaskData taskData = taskToTerminate.taskData; if (taskToTerminate.terminatedWhileRunning()) { terminateRunningTask(service, taskToTerminate, taskData); } } for (final TaskRestartData restartData : tasksToRestart.values()) { service.getInfrastructure().schedule(new Runnable() { public void run() { service.getJobs().restartWaitingTask(restartData.taskId); } }, restartData.waitTime); } for (JobId jobId : jobsToTerminate) { service.terminateJobHandling(jobId); } }
Source:
public void verifyResendPublishedEmailButtonExists(String courseId, String evalName) { int rowId = getEvaluationRowId(courseId, evalName); waitForElementPresence(By.id("session" + rowId)); WebElement sessionRow = browser.driver.findElement(By.id("session" + rowId)); String resendLinksClassNamePrefix = "session-resend-published-email-for-test"; verifyElementContainsElement(sessionRow, By.className(resendLinksClassNamePrefix)); }

Target:
public void verifyResendPublishedEmailButtonExists(String courseId, String evalName) { WebElement sessionRow = waitForElementPresence(By.id("session" + getEvaluationRowId(courseId, evalName))); verifyElementContainsElement(sessionRow, By.className("session-resend-published-email-for-test")); }
Source:
public void click() { WebElement we = resolve(); waitFor(we). withTimeout(time.seconds(1), TimeUnit.MILLISECONDS). pollingEvery(time.milliseconds(100), TimeUnit.MILLISECONDS). ignoring(ElementClickInterceptedException.class). until(() -> {we.click(); return true;}); }

Target:
public void click() { WebElement we = resolve(); waitFor(we). withTimeout(1, TimeUnit.SECONDS). pollingEvery(100, TimeUnit.MILLISECONDS). ignoring(ElementClickInterceptedException.class). until(() -> {we.click(); return true;}); }
Source:
private void checkComments(RevisionResource revision, Map<String, List<Comment>> in) throws BadRequestException, OrmException { Iterator<Map.Entry<String, List<Comment>>> mapItr = in.entrySet().iterator(); List<String> filePaths = changeDataFactory.create(db.get(), revision.getChange()).filePaths( revision.getPatchSet()); while (mapItr.hasNext()) { Map.Entry<String, List<Comment>> ent = mapItr.next(); String path = ent.getKey(); if (!filePaths.contains(path) && !Patch.COMMIT_MSG.equals(path)) { throw new BadRequestException(String.format( "file %s not found in patch set %s", path, change.currentPatchSetId())); } List<Comment> list = ent.getValue(); if (list == null) { mapItr.remove(); continue; } Iterator<Comment> listItr = list.iterator(); while (listItr.hasNext()) { Comment c = listItr.next(); if (c.line < 0) { throw new BadRequestException(String.format( "negative line number %d not allowed on %s", c.line, path)); } c.message = Strings.emptyToNull(c.message).trim(); if (c.message.isEmpty()) { listItr.remove(); } } if (list.isEmpty()) { mapItr.remove(); } } }

Target:
private void checkComments(RevisionResource revision, Map<String, List<Comment>> in) throws BadRequestException, OrmException { Iterator<Map.Entry<String, List<Comment>>> mapItr = in.entrySet().iterator(); Set<String> filePaths = Sets.newHashSet(changeDataFactory.create( db.get(), revision.getChange()).filePaths( revision.getPatchSet())); while (mapItr.hasNext()) { Map.Entry<String, List<Comment>> ent = mapItr.next(); String path = ent.getKey(); if (!filePaths.contains(path) && !Patch.COMMIT_MSG.equals(path)) { throw new BadRequestException(String.format( "file %s not found in revision %s", path, change.currentPatchSetId())); } List<Comment> list = ent.getValue(); if (list == null) { mapItr.remove(); continue; } Iterator<Comment> listItr = list.iterator(); while (listItr.hasNext()) { Comment c = listItr.next(); if (c.line < 0) { throw new BadRequestException(String.format( "negative line number %d not allowed on %s", c.line, path)); } c.message = Strings.emptyToNull(c.message).trim(); if (c.message.isEmpty()) { listItr.remove(); } } if (list.isEmpty()) { mapItr.remove(); } } }
Source:
protected boolean validate() { VnicProfileValidator validator = createVnicProfileValidator(); return validate(validator.vnicProfileIsSet()) && validate(validator.vnicProfileExists()) && validate(validator.vnicProfileNameNotUsed()) && validate(validator.networkNotChanged()) && validate(validator.networkQosExistsOrNull()) && validate(validator.portMirroringNotChangedIfUsedByVms()) && validate(validator.portMirroringNotSetIfExternalNetwork()) && validator.validateCustomProperties(getReturnValue().getValidationMessages()) && validate(validator.passthroughNotChangedIfUsedByVms()) && validate(validator.passthroughProfileContainsSupportedProperties()) && validate(validator.validNetworkFilterId()) && validate(validator.validNetworkFilterForPassthroughProfile(false)); }

Target:
protected boolean validate() { VnicProfileValidator validator = createVnicProfileValidator(); return validate(validator.vnicProfileIsSet()) && validate(validator.vnicProfileExists()) && validate(validator.vnicProfileNameNotUsed()) && validate(validator.networkNotChanged()) && validate(validator.networkQosExistsOrNull()) && validate(validator.portMirroringNotChangedIfUsedByVms()) && validate(validator.portMirroringNotSetIfExternalNetwork()) && validator.validateCustomProperties(getReturnValue().getValidationMessages()) && validate(validator.passthroughNotChangedIfUsedByVms()) && validate(validator.passthroughProfileContainsSupportedProperties(false)) && validate(validator.validNetworkFilterId()); }
Source:
public void run() { Cluster cluster = wantsRuntimeConfig ? getRuntimeCluster(node) : getUpcomingCluster(node); TreeMap<String, String> properties = new TreeMap<>(); cluster.toProperties(false, true).forEach((k, v) -> properties.put(k.toString(), v.toString())); cluster.toProperties(true, true).forEach((k, v) -> properties.put(k.toString(), v.toString())); TreeMap<String, String> output = new TreeMap<>(); configurations.forEach(configuration -> { properties.forEach((k, v) -> { if (configuration.matchConfigPropertyKey(k)) { output.put(k, v); } }); }); String lines = output.entrySet() .stream() .map(e -> e.getKey() + "=" + e.getValue()) .collect(Collectors.joining(lineSeparator())); if (lines.isEmpty()) { throw new ParameterException("No configuration found for: " + configurations.stream().map(Configuration::toString).collect(Collectors.joining(", "))); } logger.info(lines); }

Target:
public void run() { Cluster cluster = wantsRuntimeConfig ? getRuntimeCluster(node) : getUpcomingCluster(node); Properties properties = new Properties(); properties.putAll(cluster.toProperties(false, true)); properties.putAll(cluster.toProperties(true, true)); String output = properties.entrySet() .stream() .filter(e -> acceptKey(e.getKey().toString())) .map(e -> e.getKey() + "=" + e.getValue()) .sorted() .reduce((result, line) -> result + System.lineSeparator() + line) .orElseThrow(() -> new ParameterException("No configuration found")); logger.info(output); }
Source:
public void testNetworkTypes() { assertTrue(mCm.isNetworkSupported(TYPE_WIFI)); assertTrue(mCm.isNetworkSupported(TYPE_MOBILE)); assertTrue(mCm.isNetworkSupported(TYPE_ETHERNET)); }

Target:
public void testNetworkTypes() { assertTrue(mCm.isNetworkSupported(TYPE_WIFI)); assertTrue(mCm.isNetworkSupported(TYPE_MOBILE)); assertTrue(mCm.isNetworkSupported(TYPE_MOBILE_MMS)); assertFalse(mCm.isNetworkSupported(TYPE_MOBILE_FOTA)); assertTrue(mCm.isNetworkSupported(TYPE_ETHERNET)); }
Source:
public ArrayList<InstanceInfo> inflateForKey (JSONObject data, String key) { ArrayList<InstanceInfo> instanceInfos = new ArrayList<InstanceInfo>(); JSONArray instances = data.optJSONArray(key); if (instances != null) { for (int i = 0; i < instances.length(); i++) { InstanceInfo instanceInfo = new InstanceInfo(); try { instanceInfo.setData(instances.getJSONObject(i)); instanceInfos.add(instanceInfo); } catch (JSONException e) { e.printStackTrace(); } } } return instanceInfos; }

Target:
public ArrayList<InstanceInfo> inflateForKey(JSONObject data, String key) { ArrayList<InstanceInfo> instanceInfos = new ArrayList<InstanceInfo>(); JSONArray instances = data.optJSONArray(key); if (instances != null) { for (int i = 0; i < instances.length(); i++) { InstanceInfo instanceInfo = new InstanceInfo(); try { instanceInfo.setData(instances.getJSONObject(i)); instanceInfos.add(instanceInfo); } catch (JSONException e) { } } } return instanceInfos; }
Source:
public synchronized PublisherSession reconnectSession(String sessionId) throws ServiceNotAuthorizedException, ServiceNotEnabledException { PublisherSession state = sessions.get(sessionId); if (state == null || !state.stopDeleteTimer()) return null; return state; }

Target:
public synchronized PublisherSession reconnectSession(String sessionId) throws ServiceNotAuthorizedException, ServiceNotEnabledException { PublisherSession state = sessions.get(sessionId); if (state == null || !state.cancelDeleteTimer()) return null; return state; }
Source:
public boolean isUeberPool() { return product.getName().equals(Product.ueberProductNameForOwner(owner)); }

Target:
public boolean isUeberPool() { return product != null && Product.ueberProductNameForOwner(owner).equals(product.getName()); }
Source:
public void click(final int line, final int column, final int modifierKey) { if (!KeyLookupFactory.getDefault().isModifierKey(modifierKey)) { log.error(MessageFormat.format("{0} is not a modifier key.", modifierKey)); return; } log.debug(MessageFormat.format("Clicking on {0} with modifier key {1}", this, modifierKey)); notify(SWT.MouseEnter); notify(SWT.FocusIn); notify(SWT.Activate); int lineAtNextColumn = syncExec(new IntResult() { @Override public Integer run() { return widget.getLineAtOffset(offset(line, column + 1, true)); } }); int navigateToColumn = (line == lineAtNextColumn) ? column + 1 : column; navigateTo(line, navigateToColumn, true); final Point p = getXY(line, column); syncExec(new VoidResult() { @Override public void run() { Point originalCursorLocation = display.getCursorLocation(); Point absolutePoint = widget.toDisplay(p); moveMouse(absolutePoint.x, absolutePoint.y); notifyStyledText(SWT.MouseDown, createMouseEvent(p.x, p.y, 1, SWT.NONE | modifierKey, 1)); notifyStyledText(SWT.MouseUp, createMouseEvent(p.x, p.y, 1, SWT.BUTTON1 | modifierKey, 1)); moveMouse(originalCursorLocation.x, originalCursorLocation.y); } }); log.debug(MessageFormat.format("Clicked on {0} with modifier key {1}", this, modifierKey)); }

Target:
public void click(final int line, final int column, final int modifierKey) { if (!KeyLookupFactory.getDefault().isModifierKey(modifierKey) && modifierKey != 0) { log.error(MessageFormat.format("{0} is not a modifier key.", modifierKey)); return; } log.debug(MessageFormat.format("Clicking on {0} with modifier key {1}", this, modifierKey)); notify(SWT.MouseEnter); notify(SWT.FocusIn); notify(SWT.Activate); syncExec(new VoidResult() { @Override public void run() { Point originalCursorLocation = display.getCursorLocation(); widget.setTopIndex(line); widget.setHorizontalIndex(column); Point p = getXY(line, column); Point absolutePoint = widget.toDisplay(p); moveMouse(absolutePoint.x, absolutePoint.y); notifyStyledText(SWT.MouseDown, createMouseEvent(p.x, p.y, 1, SWT.NONE | modifierKey, 1)); notifyStyledText(SWT.MouseUp, createMouseEvent(p.x, p.y, 1, SWT.BUTTON1 | modifierKey, 1)); moveMouse(originalCursorLocation.x, originalCursorLocation.y); } }); log.debug(MessageFormat.format("Clicked on {0} with modifier key {1}", this, modifierKey)); }