auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean isUtilityClass(ASTAnyTypeDeclaration node) { if (node.getTypeKind() != TypeKind.CLASS) { return false; } boolean hasAny = false; for (ASTAnyTypeBodyDeclaration decl : node.getDeclarations()) { AccessNode accessNode = decl.getFirstChildOfType(AccessNode.class); ASTInitializer initializer = decl.getFirstChildOfType(ASTInitializer.class); if (accessNode != null && !(accessNode instanceof ASTConstructorDeclaration)) { hasAny = true; if (!accessNode.isStatic()) { return false; } } if (initializer != null && !initializer.isStatic()) { return false; } } return hasAny; }

Target:
private boolean isUtilityClass(ASTAnyTypeDeclaration node) { if (node.getTypeKind() != TypeKind.CLASS) { return false; } boolean hasAny = false; for (ASTAnyTypeBodyDeclaration decl : node.getDeclarations()) { switch (decl.getKind()) { case FIELD: case METHOD: hasAny = true; if (!((AccessNode) decl.getDeclarationNode()).isStatic()) { return false; } break; default: break; } } return hasAny; }
Source:
protected void onInitUI() { super.onInitUI(); addPanel = new FlowPanel(); addPanel.setStyleName(Gerrit.RESOURCES.css().addSshKeyPanel()); final Grid addGrid = new Grid(2, 2); nameTxtBox = new HintTextBox(); nameTxtBox.setVisibleLength(50); nameTxtBox.setHintText(Util.C.defaultBranchName()); nameTxtBox.setHintStyleName(Gerrit.RESOURCES.css().inputFieldTypeHint()); nameTxtBox.addKeyPressHandler(new KeyPressHandler() { @Override public void onKeyPress(KeyPressEvent event) { if (event.getCharCode() == KeyCodes.KEY_ENTER) { doAddNewBranch(); } } }); addGrid.setText(0, 0, Util.C.columnBranchName() + ":"); addGrid.setWidget(0, 1, nameTxtBox); irevTxtBox = new HintTextBox(); irevTxtBox.setVisibleLength(50); irevTxtBox.setHintText(Util.C.defaultRevisionSpec()); irevTxtBox.setHintStyleName(Gerrit.RESOURCES.css().inputFieldTypeHint()); irevTxtBox.addKeyPressHandler(new KeyPressHandler() { @Override public void onKeyPress(KeyPressEvent event) { if (event.getCharCode() == KeyCodes.KEY_ENTER) { doAddNewBranch(); } } }); addGrid.setText(1, 0, Util.C.initialRevision() + ":"); addGrid.setWidget(1, 1, irevTxtBox); addBranch = new Button(Util.C.buttonAddBranch()); addBranch.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { doAddNewBranch(); } }); addPanel.add(addGrid); addPanel.add(addBranch); branches = new BranchesTable(); delBranch = new Button(Util.C.buttonDeleteBranch()); delBranch.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { branches.deleteChecked(); } }); add(branches); add(delBranch); add(addPanel); }

Target:
protected void onInitUI() { super.onInitUI(); addPanel = new FlowPanel(); addPanel.setStyleName(Gerrit.RESOURCES.css().addSshKeyPanel()); final Grid addGrid = new Grid(2, 2); nameTxtBox = new HintTextBox(); nameTxtBox.setVisibleLength(50); nameTxtBox.setHintText(Util.C.defaultBranchName()); nameTxtBox.addKeyPressHandler(new KeyPressHandler() { @Override public void onKeyPress(KeyPressEvent event) { if (event.getCharCode() == KeyCodes.KEY_ENTER) { doAddNewBranch(); } } }); addGrid.setText(0, 0, Util.C.columnBranchName() + ":"); addGrid.setWidget(0, 1, nameTxtBox); irevTxtBox = new HintTextBox(); irevTxtBox.setVisibleLength(50); irevTxtBox.setHintText(Util.C.defaultRevisionSpec()); irevTxtBox.addKeyPressHandler(new KeyPressHandler() { @Override public void onKeyPress(KeyPressEvent event) { if (event.getCharCode() == KeyCodes.KEY_ENTER) { doAddNewBranch(); } } }); addGrid.setText(1, 0, Util.C.initialRevision() + ":"); addGrid.setWidget(1, 1, irevTxtBox); addBranch = new Button(Util.C.buttonAddBranch()); addBranch.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { doAddNewBranch(); } }); addPanel.add(addGrid); addPanel.add(addBranch); branches = new BranchesTable(); delBranch = new Button(Util.C.buttonDeleteBranch()); delBranch.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { branches.deleteChecked(); } }); add(branches); add(delBranch); add(addPanel); }
Source:
public List<V> asImmutableCopy() { try { return ImmutableList.copyOf(this); } catch (Exception e) { log.warn("Error converting list to Immutable, using unmodifiable instead: "+e, e); return asUnmodifiableCopy(); } }

Target:
public List<V> asImmutableCopy() { try { return ImmutableList.copyOf(this); } catch (Exception e) { Exceptions.propagateIfFatal(e); log.warn("Error converting list to Immutable, using unmodifiable instead: "+e, e); return asUnmodifiableCopy(); } }
Source:
public TexParserResult parse(List<Path> texFiles) { texParserResult.addFiles(texFiles); List<Path> referencedFiles = new ArrayList<>(); for (Path file : texFiles) { if (!file.toFile().exists()) { LOGGER.error(String.format("File does not exist: %s", file)); continue; } try ( InputStream inputStream = Files.newInputStream(file); Reader reader = new InputStreamReader(inputStream); LineNumberReader lineNumberReader = new LineNumberReader(reader)) { for (String line = lineNumberReader.readLine(); line != null; line = lineNumberReader.readLine()) { if (line.trim().isEmpty() || line.trim().charAt(0) == '%') { continue; } matchCitation(file, lineNumberReader.getLineNumber(), line); matchNestedFile(file, texFiles, referencedFiles, line); } } catch (ClosedChannelException e) { LOGGER.info("Parsing has been interrupted"); } catch (IOException | UncheckedIOException e) { LOGGER.info("Error while parsing file {}", file, e); } } if (!referencedFiles.isEmpty()) { parse(referencedFiles); } return texParserResult; }

Target:
public TexParserResult parse(List<Path> texFiles) { texParserResult.addFiles(texFiles); List<Path> referencedFiles = new ArrayList<>(); for (Path file : texFiles) { if (!file.toFile().exists()) { LOGGER.error(String.format("File does not exist: %s", file)); continue; } try ( InputStream inputStream = Files.newInputStream(file); Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); LineNumberReader lineNumberReader = new LineNumberReader(reader)) { for (String line = lineNumberReader.readLine(); line != null; line = lineNumberReader.readLine()) { if (line.trim().isEmpty() || line.trim().charAt(0) == '%') { continue; } matchCitation(file, lineNumberReader.getLineNumber(), line); matchNestedFile(file, texFiles, referencedFiles, line); } } catch (ClosedChannelException e) { LOGGER.info("Parsing has been interrupted"); } catch (IOException | UncheckedIOException e) { LOGGER.info("Error while parsing file {}", file, e); } } if (!referencedFiles.isEmpty()) { parse(referencedFiles); } return texParserResult; }
Source:
default EventProcessingConfiguration eventProcessingConfiguration() { List<EventProcessingConfiguration> modules = getModules().stream() .filter(m -> m.instance() instanceof EventProcessingConfiguration) .map(m -> (EventProcessingConfiguration) m.instance()) .collect(Collectors.toList()); if (modules.size() > 1) { throw new IllegalStateException("Found more than one EventProcessingConfiguration modules"); } return modules.get(0); }

Target:
default EventProcessingConfiguration eventProcessingConfiguration() { List<EventProcessingConfiguration> modules = findModules(EventProcessingConfiguration.class); switch (modules.size()) { case 0: return null; case 1: return modules.get(0); default: throw new AxonConfigurationException("Found more than one EventProcessingConfiguration modules"); } }
Source:
private void validateCascadedConstraints(ValidationContext<?> validationContext, ValueContext<?, Object> valueContext) { Validatable validatable = valueContext.getCurrentValidatable(); ValueContext.ValueState<Object> originalValueState = valueContext.getCurrentValueState(); for ( Cascadable cascadable : validatable.getCascadables() ) { valueContext.appendNode( cascadable ); ElementType elementType = cascadable.getElementType(); if ( isCascadeRequired( validationContext, valueContext.getCurrentBean(), valueContext.getPropertyPath(), elementType ) ) { Object value = getCascadableValue( validationContext, valueContext.getCurrentBean(), cascadable ); CascadingMetaData cascadingMetaData = cascadable.getCascadingMetaData(); if ( value != null ) { CascadingMetaData effectiveCascadingMetaData = cascadingMetaData.addRuntimeContainerSupport( value.getClass(), valueExtractorManager ); if ( effectiveCascadingMetaData.isCascading() ) { validateCascadedAnnotatedObjectForCurrentGroup( value, validationContext, valueContext, effectiveCascadingMetaData ); } if ( effectiveCascadingMetaData.isContainer() ) { ContainerCascadingMetaData containerCascadingMetaData = effectiveCascadingMetaData.as( ContainerCascadingMetaData.class ); if ( containerCascadingMetaData.hasContainerElementsMarkedForCascading() ) { validateCascadedContainerElementsForCurrentGroup( value, validationContext, valueContext, containerCascadingMetaData.getContainerElementTypesCascadingMetaData() ); } } } } valueContext.resetValueState( originalValueState ); } }

Target:
private void validateCascadedConstraints(ValidationContext<?> validationContext, ValueContext<?, Object> valueContext) { Validatable validatable = valueContext.getCurrentValidatable(); ValueContext.ValueState<Object> originalValueState = valueContext.getCurrentValueState(); for ( Cascadable cascadable : validatable.getCascadables() ) { valueContext.appendNode( cascadable ); ElementType elementType = cascadable.getElementType(); if ( isCascadeRequired( validationContext, valueContext.getCurrentBean(), valueContext.getPropertyPath(), elementType ) ) { Object value = getCascadableValue( validationContext, valueContext.getCurrentBean(), cascadable ); CascadingMetaData cascadingMetaData = cascadable.getCascadingMetaData(); if ( value != null ) { CascadingMetaData effectiveCascadingMetaData = cascadingMetaData.addRuntimeContainerSupport( valueExtractorManager, value.getClass() ); if ( effectiveCascadingMetaData.isCascading() ) { validateCascadedAnnotatedObjectForCurrentGroup( value, validationContext, valueContext, effectiveCascadingMetaData ); } if ( effectiveCascadingMetaData.isContainer() ) { ContainerCascadingMetaData containerCascadingMetaData = effectiveCascadingMetaData.as( ContainerCascadingMetaData.class ); if ( containerCascadingMetaData.hasContainerElementsMarkedForCascading() ) { validateCascadedContainerElementsForCurrentGroup( value, validationContext, valueContext, containerCascadingMetaData.getContainerElementTypesCascadingMetaData() ); } } } } valueContext.resetValueState( originalValueState ); } }
Source:
public Object convertToBackendType(String entityType, List<String> propertyPath, Object value) { if ( value instanceof String && ( (String) value ).startsWith( ":" ) ) { return value; } Type propertyType = getPropertyType( entityType, propertyPath ); if ( isElementCollection( propertyType ) ) { propertyType = ( (CollectionType) propertyType ).getElementType( sessionFactory ); } GridType ogmType = sessionFactory.getServiceRegistry().getService( TypeTranslator.class ).getType( propertyType ); return ogmType.convertToBackendType( value, sessionFactory ); }

Target:
public Object convertToBackendType(String entityType, List<String> propertyPath, Object value) { if ( value instanceof InfinispanRemoteQueryParameter ) { return value; } Type propertyType = getPropertyType( entityType, propertyPath ); if ( isElementCollection( propertyType ) ) { propertyType = ( (CollectionType) propertyType ).getElementType( sessionFactory ); } GridType ogmType = sessionFactory.getServiceRegistry().getService( TypeTranslator.class ).getType( propertyType ); return ogmType.convertToBackendType( value, sessionFactory ); }
Source:
public static void addColumnMinMaxValueInfo(PropertiesConfiguration properties, String column, String minValue, String maxValue) { properties.setProperty(getKeyFor(column, MIN_VALUE), escapeSpecialCharacter(minValue)); properties.setProperty(getKeyFor(column, MAX_VALUE), escapeSpecialCharacter(maxValue)); }

Target:
public static void addColumnMinMaxValueInfo(PropertiesConfiguration properties, String column, String minValue, String maxValue) { if (isValidPropertyValue(minValue)) { properties.setProperty(getKeyFor(column, MIN_VALUE), minValue); } if (isValidPropertyValue(maxValue)) { properties.setProperty(getKeyFor(column, MAX_VALUE), maxValue); } }
Source:
private PeriodicResolver(final String srvName, final String domain, final Resolver resolver, final ScheduledExecutorService executorService) { endpoints = resolver.supplier(srvName, domain).get(); executorService.scheduleWithFixedDelay(() -> endpoints = resolver.supplier(srvName, domain).get(), 0, 1, TimeUnit.MINUTES); }

Target:
private PeriodicResolver(final String srvName, final String domain, final Resolver resolver, final ScheduledExecutorService executorService) { endpoints = resolver.resolve(srvName, domain); executorService.scheduleWithFixedDelay(() -> endpoints = resolver.resolve(srvName, domain), 0, 1, TimeUnit.MINUTES); }
Source:
List<String> getSnapshotsInProgress() throws IOException { List<String> snapshotInProgress = Lists.newArrayList(); FileStatus[] snapshotsInProgress = CommonFSUtils.listStatus(fs, new Path(snapshotDir, SnapshotDescriptionUtils.SNAPSHOT_TMP_DIR_NAME)); if (!ArrayUtils.isEmpty(snapshotsInProgress)) { for (FileStatus snapshot : snapshotsInProgress) { try { snapshotInProgress.addAll(fileInspector.filesUnderSnapshot(snapshot.getPath())); } catch (CorruptedSnapshotException cse) { LOG.debug("Corrupted in-progress snapshot file exception, ignored.", cse); } } } return snapshotInProgress; }

Target:
List<String> getSnapshotsInProgress() throws IOException { List<String> snapshotInProgress = Lists.newArrayList(); FileStatus[] snapshotsInProgress = CommonFSUtils.listStatus(this.workingFs, this.workingSnapshotDir); if (!ArrayUtils.isEmpty(snapshotsInProgress)) { for (FileStatus snapshot : snapshotsInProgress) { try { snapshotInProgress.addAll(fileInspector.filesUnderSnapshot(workingFs, snapshot.getPath())); } catch (CorruptedSnapshotException cse) { LOG.info("Corrupted in-progress snapshot file exception, ignored.", cse); } } } return snapshotInProgress; }
Source:
public @NonNull Map<@NonNull String, @NonNull String> getProperties() { Map<@NonNull String, @NonNull String> properties = new HashMap<>(); properties.put(NonNullUtils.checkNotNull(Messages.XmlModuleHelper_PropertyFile), NonNullUtils.checkNotNull(fSourceFile.getName())); properties.put(NonNullUtils.checkNotNull(Messages.XmlModuleHelper_PropertyType), NonNullUtils.checkNotNull(fType.name())); return properties; }

Target:
public @NonNull Map<@NonNull String, @NonNull String> getProperties() { Map<@NonNull String, @NonNull String> properties = new HashMap<>(); properties.put(NonNullUtils.checkNotNull(Messages.XmlModuleHelper_PropertyFile), fSourceFile.getName()); properties.put(NonNullUtils.checkNotNull(Messages.XmlModuleHelper_PropertyType), fType.name()); return properties; }
Source:
public void testConvertToDataModelType() { uk.ac.ebi.eva.commons.models.converters.data.DBObjectToVariantStatsConverter converter = new uk.ac.ebi.eva.commons.models.converters.data.DBObjectToVariantStatsConverter(); VariantStats converted = converter.convert(mongoStats); assertEquals(stats, converted); }

Target:
public void testConvertToDataModelType() { DBObjectToVariantStatsConverter converter = new DBObjectToVariantStatsConverter(); VariantStats converted = converter.convert(mongoStats); assertEquals(stats, converted); }
Source:
public void start(ComponentContext context) { super.start(context); jsonFactoryManager = Framework.getService(JsonFactoryManager.class); codecs = new ObjectCodecService(jsonFactoryManager.getJsonFactory()); List<CodecDescriptor> descriptors = getDescriptors(XP_CODECS); descriptors.forEach(d -> { try { codecs.addCodec(d.klass.newInstance()); } catch (ReflectiveOperationException e) { getLog().error(e); } }); codecs.postInit(); }

Target:
public void start(ComponentContext context) { super.start(context); jsonFactoryManager = Framework.getService(JsonFactoryManager.class); codecs = new ObjectCodecService(jsonFactoryManager.getJsonFactory()); List<CodecDescriptor> descriptors = getDescriptors(XP_CODECS); descriptors.forEach(d -> { try { codecs.addCodec(d.klass.getDeclaredConstructor().newInstance()); } catch (ReflectiveOperationException e) { getLog().error(e,e); } }); codecs.postInit(); }
Source:
public DefaultTier(Tier in, TierPriceOverride override, Currency currency) { this.limits = (DefaultLimit[])in.getLimits(); this.blocks = new DefaultTieredBlock[in.getTieredBlocks().length]; for (int i = 0; i < in.getTieredBlocks().length; i++) { if(override != null && override.getTieredBlockPriceOverrides().get(i)!=null) blocks[i] = new DefaultTieredBlock(in.getTieredBlocks()[i], override.getTieredBlockPriceOverrides().get(i), currency) ; else blocks[i] = (DefaultTieredBlock) in.getTieredBlocks()[i]; } }

Target:
public DefaultTier(Tier in, TierPriceOverride override, Currency currency) { this.limits = (DefaultLimit[])in.getLimits(); this.blocks = new DefaultTieredBlock[in.getTieredBlocks().length]; for (int i = 0; i < in.getTieredBlocks().length; i++) { if(override != null && override.getTieredBlockPriceOverrides() != null) { final TieredBlock curTieredBlock = in.getTieredBlocks()[i]; final TieredBlockPriceOverride overriddenTierBlock = Iterables.tryFind(override.getTieredBlockPriceOverrides(), new Predicate<TieredBlockPriceOverride>() { @Override public boolean apply(final TieredBlockPriceOverride input) { return (input != null && input.getUnitName().equals(curTieredBlock.getUnit().getName()) && Double.compare(input.getSize(), curTieredBlock.getSize()) == 0 && Double.compare(input.getMax(), curTieredBlock.getMax()) == 0); } }).orNull(); blocks[i] = (overriddenTierBlock != null) ? new DefaultTieredBlock(in.getTieredBlocks()[i], overriddenTierBlock, currency) : (DefaultTieredBlock) in.getTieredBlocks()[i]; } else { blocks[i] = (DefaultTieredBlock) in.getTieredBlocks()[i]; } } }
Source:
public boolean barrierAnnouncement( InputChannelInfo channelInfo, CheckpointBarrier announcedBarrier, int sequenceNumber) throws IOException { inputs[channelInfo.getGateIdx()].convertToPriorityEvent(channelInfo.getInputChannelIdx(), sequenceNumber); return false; }

Target:
public void barrierAnnouncement( InputChannelInfo channelInfo, CheckpointBarrier announcedBarrier, int sequenceNumber) throws IOException { inputs[channelInfo.getGateIdx()].convertToPriorityEvent( channelInfo.getInputChannelIdx(), sequenceNumber); }
Source:
public void theDeviceDebugInformationShouldBeDisabled() throws Throwable { final DlmsDevice device = dlmsDeviceRepository.findByDeviceIdentification(PROPERTIES_MAP.put( Keys.KEY_DEVICE_IDENTIFICATION, ScenarioContext.Current().get(Keys.KEY_DEVICE_IDENTIFICATION) .toString())); assertFalse("Debug mode", device.isInDebugMode()); }

Target:
public void theDeviceDebugInformationShouldBeDisabled() throws Throwable { final DlmsDevice device = dlmsDeviceRepository.findByDeviceIdentification(ScenarioContext.Current() .get(Keys.KEY_DEVICE_IDENTIFICATION).toString()); assertFalse("Debug mode", device.isInDebugMode()); }
Source:
public Result<Void> create(final EventTypeBase eventType) { final TopicRepository topicRepository = timelineService.getDefaultTopicRepository(); try { validateSchema(eventType); enrichment.validate(eventType); partitionResolver.validate(eventType); final String topicName = topicRepository.createTopic( partitionsCalculator.getBestPartitionsCount(eventType.getDefaultStatistic()), eventType.getOptions().getRetentionTime()); eventType.setTopic(topicName); eventTypeRepository.saveEventType(eventType); return Result.ok(); } catch (final InvalidEventTypeException | NoSuchPartitionStrategyException | DuplicatedEventTypeNameException e) { LOG.debug("Failed to create EventType.", e); if (null != eventType.getTopic()) { try { topicRepository.deleteTopic(eventType.getTopic()); } catch (final TopicDeletionException ex) { LOG.warn("failed to delete topic for event type that failed to be created", ex); } } return Result.problem(e.asProblem()); } catch (final NakadiException e) { LOG.error("Error creating event type " + eventType, e); return Result.problem(e.asProblem()); } }

Target:
public Result<Void> create(final EventTypeBase eventType) { final TopicRepository topicRepository = timelineService.getDefaultTopicRepository(); try { validateSchema(eventType); enrichment.validate(eventType); partitionResolver.validate(eventType); final String topicName = topicRepository.createTopic( partitionsCalculator.getBestPartitionsCount(eventType.getDefaultStatistic()), eventType.getOptions().getRetentionTime()); eventType.setTopic(topicName); boolean eventTypeCreated = false; try { eventTypeRepository.saveEventType(eventType); eventTypeCreated = true; } finally { if (!eventTypeCreated) { try { topicRepository.deleteTopic(eventType.getTopic()); } catch (final TopicDeletionException ex) { LOG.error("failed to delete topic for event type that failed to be created", ex); } } } return Result.ok(); } catch (final InvalidEventTypeException | NoSuchPartitionStrategyException | DuplicatedEventTypeNameException e) { LOG.debug("Failed to create EventType.", e); return Result.problem(e.asProblem()); } catch (final NakadiException e) { LOG.error("Error creating event type " + eventType, e); return Result.problem(e.asProblem()); } }
Source:
public Observable<ResultSet> updateStatusToFinished(Date timeSlice, UUID jobId) { return session.executeAndFetch(findByIdAndSlice.bind(timeSlice, jobId)) .isEmpty() .flatMap(empty -> { if (empty) { logger.warnf("Attempt to update status of non-exist job with id %s", jobId); return Observable.empty(); } else { return session.execute(updateStatus.bind((byte) 1, timeSlice, jobId)) .doOnError(t -> logger .warnf("There was an error updating the status to finished for %s in time " + "slice [%s]", jobId, timeSlice.getTime())); } }); }

Target:
public Observable<ResultSet> updateStatusToFinished(Date timeSlice, UUID jobId) { return session.executeAndFetch(findByIdAndSlice.bind(timeSlice, jobId)) .flatMap(jobRow -> session.execute(updateStatus.bind((byte) 1, timeSlice, jobId)) .doOnError(t -> logger .warnf("There was an error updating the status to finished for %s in time " + "slice [%s]", jobId, timeSlice.getTime())) ) .switchIfEmpty(Observable.<ResultSet>empty().doOnCompleted(() -> logger.warnf( "Attempt to update the status of a non-exist job [%s] " + "in time slice [%s]", jobId, timeSlice.getTime()))); }
Source:
public Trigger(Trigger trigger) { if (trigger == null) { throw new IllegalArgumentException("trigger must be not null"); } this.tenantId = trigger.getTenantId(); this.id = trigger.getId(); this.name = trigger.getName(); this.context = new HashMap<>(trigger.getContext()); this.tags = new HashMap<>(trigger.getTags()); this.actions = new HashSet<>(); for (TriggerAction action : trigger.getActions()) { this.actions.add(new TriggerAction(action)); } this.autoDisable = trigger.isAutoDisable(); this.autoEnable = trigger.isAutoEnable(); this.autoResolve = trigger.isAutoResolve(); this.autoResolveAlerts = trigger.isAutoResolveAlerts(); this.autoResolveMatch = trigger.getAutoResolveMatch(); this.dataIdMap = new HashMap<>(trigger.getDataIdMap() != null ? trigger.getDataIdMap() : new HashMap<>()); this.eventCategory = trigger.getEventCategory(); this.eventText = trigger.getEventText(); this.eventType = trigger.getEventType(); this.memberOf = trigger.getMemberOf(); this.description = trigger.getDescription(); this.enabled = trigger.isEnabled(); this.firingMatch = trigger.getFiringMatch(); this.type = trigger.getType(); this.source = trigger.getSource(); this.severity = trigger.getSeverity(); this.match = trigger.getMatch() != null ? trigger.getMatch() : Match.ALL; this.mode = trigger.getMode() != null ? trigger.getMode() : Mode.FIRING; }

Target:
public Trigger(Trigger trigger) { if (trigger == null) { throw new IllegalArgumentException("trigger must be not null"); } this.tenantId = trigger.getTenantId(); this.id = trigger.getId(); this.name = trigger.getName(); this.context = new HashMap<>(trigger.getContext()); this.tags = new HashMap<>(trigger.getTags()); this.actions = new HashSet<>(); for (TriggerAction action : trigger.getActions()) { this.actions.add(new TriggerAction(action)); } this.autoDisable = trigger.isAutoDisable(); this.autoEnable = trigger.isAutoEnable(); this.autoResolve = trigger.isAutoResolve(); this.autoResolveAlerts = trigger.isAutoResolveAlerts(); this.autoResolveMatch = trigger.getAutoResolveMatch(); this.dataIdMap = new HashMap<>(trigger.getDataIdMap() != null ? trigger.getDataIdMap() : new HashMap<>()); this.eventCategory = trigger.getEventCategory(); this.eventText = trigger.getEventText(); this.eventType = trigger.getEventType(); this.memberOf = trigger.getMemberOf(); this.description = trigger.getDescription(); this.enabled = trigger.isEnabled(); this.firingMatch = trigger.getFiringMatch(); this.type = trigger.getType(); this.source = trigger.getSource(); this.severity = trigger.getSeverity(); this.mode = trigger.getMode() != null ? trigger.getMode() : Mode.FIRING; this.match = trigger.getMode() == Mode.FIRING ? trigger.getFiringMatch() : trigger.getAutoResolveMatch(); }
Source:
public List<T> values(final int state) { final int size = sharedList.size(); final ArrayList<T> list = new ArrayList<>(size); for (int i = 0; i < size; i++) { T entry = sharedList.get(i); if (entry.getState() == state) { list.add(entry); } } return list; }

Target:
public List<T> values(final int state) { final ArrayList<T> list = new ArrayList<>(sharedList.size()); for (final T reference : sharedList) { if (reference.getState() == state) { list.add(reference); } } return list; }
Source:
private List<Config> fetchRows(TDJobOperator job) { Config resultState = state.getNestedOrSetEmpty(RESULT); try { List<String> columnNames = job.getResultColumnNames(); return job.getResult(ite -> { List<Config> rows = new ArrayList<>(); while (ite.hasNext()) { rows.add(row(columnNames, ite.next().asArrayValue())); if (rows.size() > Limits.maxWorkflowTasks()) { TaskLimitExceededException cause = new TaskLimitExceededException("Too many tasks. Limit: " + Limits.maxWorkflowTasks()); throw new TaskExecutionException(cause, TaskExecutionException.buildExceptionErrorConfig(cause)); } } return rows; }); } catch (UncheckedIOException | TDClientException e) { if (isDeterministicClientException(e)) { throw new TaskExecutionException(e, TaskExecutionException.buildExceptionErrorConfig(e)); } int retry = resultState.get(RETRY, int.class, 0); resultState.set(RETRY, retry + 1); int interval = (int) Math.min(INITIAL_RETRY_INTERVAL * Math.pow(2, retry), MAX_RETRY_INTERVAL); logger.warn("Failed to download result of job '{}', retrying in seconds", job.getJobId(), interval, e); throw TaskExecutionException.ofNextPolling(interval, ConfigElement.copyOf(state)); } }

Target:
private List<Config> fetchRows(TDJobOperator job) { Config resultState = state.getNestedOrSetEmpty(RESULT); try { List<String> columnNames = job.getResultColumnNames(); List<Config> result = job.getResult(ite -> { List<Config> rows = new ArrayList<>(); while (ite.hasNext()) { rows.add(row(columnNames, ite.next().asArrayValue())); if (rows.size() > Limits.maxWorkflowTasks()) { TaskLimitExceededException cause = new TaskLimitExceededException("Too many tasks. Limit: " + Limits.maxWorkflowTasks()); throw new TaskExecutionException(cause, TaskExecutionException.buildExceptionErrorConfig(cause)); } } return rows; }); resultState.remove(RETRY); return result; } catch (UncheckedIOException | TDClientException e) { if (isDeterministicClientException(e)) { throw new TaskExecutionException(e, TaskExecutionException.buildExceptionErrorConfig(e)); } int retry = resultState.get(RETRY, int.class, 0); resultState.set(RETRY, retry + 1); int interval = (int) Math.min(INITIAL_RETRY_INTERVAL * Math.pow(2, retry), MAX_RETRY_INTERVAL); logger.warn("Failed to download result of job '{}', retrying in seconds", job.getJobId(), interval, e); throw TaskExecutionException.ofNextPolling(interval, ConfigElement.copyOf(state)); } }
Source:
private void restoreState(final Machine machine) { machineServiceClient.getProcesses(machine.getWorkspaceId(), machine.getId()).then(new Operation<List<MachineProcessDto>>() { @Override public void apply(List<MachineProcessDto> arg) throws OperationException { for (MachineProcessDto machineProcessDto : arg) { if (machineProcessDto.getCommandLine() != null && !machineProcessDto.getCommandLine().isEmpty() && machineProcessDto.getCommandLine().startsWith("#hidden")) { continue; } final CommandDto commandDto = dtoFactory.createDto(CommandDto.class) .withName(machineProcessDto.getName()) .withAttributes(machineProcessDto.getAttributes()) .withCommandLine(machineProcessDto.getCommandLine()) .withType(machineProcessDto.getType()); final CommandType type = commandTypeRegistry.getCommandTypeById(commandDto.getType()); if (type != null) { final CommandConfiguration configuration = type.getConfigurationFactory().createFromDto(commandDto); final CommandOutputConsole console = commandConsoleFactory.create(configuration, machine); console.listenToOutput(machineProcessDto.getOutputChannel()); console.attachToProcess(machineProcessDto); addCommandOutput(machine.getId(), console); } } } }).catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError arg) throws OperationException { notificationManager.notify(localizationConstant.failedToGetProcesses(machine.getId())); } }); }

Target:
private void restoreState(final Machine machine) { machineServiceClient.getProcesses(machine.getWorkspaceId(), machine.getId()).then(new Operation<List<MachineProcessDto>>() { @Override public void apply(List<MachineProcessDto> arg) throws OperationException { for (MachineProcessDto machineProcessDto : arg) { if (!Strings.isNullOrEmpty(machineProcessDto.getCommandLine()) && machineProcessDto.getCommandLine().startsWith("#hidden")) { continue; } final CommandDto commandDto = dtoFactory.createDto(CommandDto.class) .withName(machineProcessDto.getName()) .withAttributes(machineProcessDto.getAttributes()) .withCommandLine(machineProcessDto.getCommandLine()) .withType(machineProcessDto.getType()); final CommandType type = commandTypeRegistry.getCommandTypeById(commandDto.getType()); if (type != null) { final CommandConfiguration configuration = type.getConfigurationFactory().createFromDto(commandDto); final CommandOutputConsole console = commandConsoleFactory.create(configuration, machine); console.listenToOutput(machineProcessDto.getOutputChannel()); console.attachToProcess(machineProcessDto); addCommandOutput(machine.getId(), console); } } } }).catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError arg) throws OperationException { notificationManager.notify(localizationConstant.failedToGetProcesses(machine.getId())); } }); }
Source:
private static void startBootMicroservices() throws IOException, InterruptedException, ExecutionException { if (!(PASchedulerProperties.SCHEDULER_BOOT_MICROSERVICES_PATH.isSet() && PASchedulerProperties.SCHEDULER_HOME.isSet())) return; String paHome = PASchedulerProperties.getAbsolutePath(System.getProperty(PASchedulerProperties.SCHEDULER_HOME.getKey())); String microservicesPath = PASchedulerProperties.SCHEDULER_BOOT_MICROSERVICES_PATH.getValueAsString(); Process iamProcess = IAMStarter.INSTANCE.start(paHome, microservicesPath); bootMicroservicesProcesses.add(iamProcess); }

Target:
private static void startBootMicroservices() throws IOException, InterruptedException, ExecutionException { if (!(PASchedulerProperties.SCHEDULER_BOOT_MICROSERVICES_PATH.isSet() && PASchedulerProperties.SCHEDULER_HOME.isSet())) return; String paHome = PASchedulerProperties.SCHEDULER_HOME.getValueAsString(); String bootMicroservicesPath = PASchedulerProperties.getAbsolutePath(PASchedulerProperties.SCHEDULER_BOOT_MICROSERVICES_PATH.getValueAsString()); String bootConfigurationPath = PASchedulerProperties.getAbsolutePath(PASchedulerProperties.SCHEDULER_BOOT_CONFIGURATION_PATH.getValueAsString()); Process iamProcess = IAMStarter.start(paHome, bootMicroservicesPath, bootConfigurationPath); bootMicroservicesProcesses.add(iamProcess); }
Source:
public long getFreeMemory() throws InstanceNotFoundException, AttributeNotFoundException, MalformedObjectNameException, ReflectionException, MBeanException { return (long) mBeanServer.getAttribute(new ObjectName("java.lang","type","OperatingSystem"), "FreePhysicalMemorySize"); }

Target:
public long getFreeMemory() { try { return (long) mBeanServer.getAttribute(new ObjectName("java.lang","type","OperatingSystem"), "FreePhysicalMemorySize"); } catch (Exception e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("An exception occurred during memory check", e); } } return -1; }
Source:
public void transform(StructuredRecord structuredRecord, Emitter<StructuredRecord> emitter) throws Exception { outputSchema = outputSchema == null ? buildOutputSchema(structuredRecord.getSchema()) : outputSchema; StringBuilder executableCommand = new StringBuilder(); if (!Strings.isNullOrEmpty(config.fieldsToProcess)) { for (String inputField : Splitter.on(',').trimResults().split(config.fieldsToProcess)) { Schema inputFieldSchema = structuredRecord.getSchema().getField(inputField).getSchema(); Schema.Type inputFieldType = inputFieldSchema.isNullable() ? inputFieldSchema.getNonNullable().getType() : inputFieldSchema.getType(); if ((inputFieldType.equals(Schema.Type.STRING)) && ((String) (structuredRecord.get(inputField))).contains(" ")) { executableCommand.append("\""); executableCommand.append(structuredRecord.get(inputField)); executableCommand.append("\""); } else { executableCommand.append(structuredRecord.get(inputField)); } executableCommand.append(" "); } } if (!Strings.isNullOrEmpty(config.fixedArguments)) { executableCommand.append(config.fixedArguments); } SettableFuture<String> completion = SettableFuture.create(); executor.submit(executableCommand.toString().trim(), completion, emitter, structuredRecord, outputSchema); }

Target:
public void transform(StructuredRecord structuredRecord, Emitter<StructuredRecord> emitter) throws Exception { outputSchema = outputSchema == null ? buildOutputSchema(structuredRecord.getSchema()) : outputSchema; StringBuilder executableInputs = new StringBuilder(); for (String inputField : inputFieldsToProcess) { Schema inputFieldSchema = structuredRecord.getSchema().getField(inputField).getSchema(); Schema.Type inputFieldType = inputFieldSchema.isNullable() ? inputFieldSchema.getNonNullable().getType() : inputFieldSchema.getType(); if ((inputFieldType.equals(Schema.Type.STRING)) && ((String) (structuredRecord.get(inputField))).contains(" ")) { executableInputs.append("\""); executableInputs.append(structuredRecord.get(inputField)); executableInputs.append("\""); } else { executableInputs.append(structuredRecord.get(inputField)); } executableInputs.append(" "); } if (!Strings.isNullOrEmpty(config.fixedInputs)) { executableInputs.append(config.fixedInputs); } executor.submit(executableInputs.toString().trim(), emitter, structuredRecord, outputSchema); }
Source:
private void registerLeaderElectionService(TimeLockServerConfiguration configuration) { remoteServers = getRemoteServerPaths(configuration); LeaderConfig leaderConfig = getLeaderConfig(configuration); Set<String> paxosSubresourceUris = PaxosTimeLockUriUtils.getLeaderPaxosUris(remoteServers); Leaders.LocalPaxosServices localPaxosServices = Leaders.createLocalServices( leaderConfig, ImmutableRemotePaxosServerSpec.builder() .remoteLeaderUris(remoteServers) .remoteAcceptorUris(paxosSubresourceUris) .remoteLearnerUris(paxosSubresourceUris) .build()); leaderElectionService = localPaxosServices.leaderElectionService(); environment.jersey().register(leaderElectionService); environment.jersey().register(new LeadershipResource( localPaxosServices.ourAcceptor(), localPaxosServices.ourLearner())); environment.jersey().register(new NotCurrentLeaderExceptionMapper()); environment.jersey().register(new TooManyRequestsExceptionMapper()); }

Target:
private void registerLeaderElectionService(TimeLockServerConfiguration configuration) { remoteServers = getRemoteServerPaths(configuration); LeaderConfig leaderConfig = getLeaderConfig(configuration); Set<String> paxosSubresourceUris = PaxosTimeLockUriUtils.getLeaderPaxosUris(remoteServers); Leaders.LocalPaxosServices localPaxosServices = Leaders.createLocalServices( leaderConfig, ImmutableRemotePaxosServerSpec.builder() .remoteLeaderUris(remoteServers) .remoteAcceptorUris(paxosSubresourceUris) .remoteLearnerUris(paxosSubresourceUris) .build()); leaderElectionService = localPaxosServices.leaderElectionService(); environment.jersey().register(leaderElectionService); environment.jersey().register(new LeadershipResource( localPaxosServices.ourAcceptor(), localPaxosServices.ourLearner())); environment.jersey().register(new NotCurrentLeaderExceptionMapper()); }
Source:
void drawWidget (long id, NSGraphicsContext context, NSRect rect) { if (id != paintView().id) return; if (!hooks (SWT.Paint) && !filters (SWT.Paint)) return; if (ignorePaint) { if (++ignorePaintCount > 1) return; } GCData data = new GCData (); data.paintRect = rect; GC gc = GC.cocoa_new (this, data); Event event = new Event (); event.gc = gc; event.x = (int)rect.x; event.y = (int)rect.y; event.width = (int)rect.width; event.height = (int)rect.height; sendEvent (SWT.Paint, event); event.gc = null; gc.dispose (); }

Target:
void drawWidget (long id, NSGraphicsContext context, NSRect rect) { if (id != paintView().id) return; if (!hooks (SWT.Paint) && !filters (SWT.Paint)) return; if (ignorePaint) { if (!firstPaint) return; firstPaint = false; } GCData data = new GCData (); data.paintRect = rect; GC gc = GC.cocoa_new (this, data); Event event = new Event (); event.gc = gc; event.x = (int)rect.x; event.y = (int)rect.y; event.width = (int)rect.width; event.height = (int)rect.height; sendEvent (SWT.Paint, event); event.gc = null; gc.dispose (); }
Source:
private void updateLogViewer(List<LogEntry> entries) { elements.clear(); groups.clear(); group(entries); limitEntriesCount(); String titleSummary = getTitleSummary(); getDisplay().asyncExec(() -> { setContentDescription(titleSummary); if (fFilteredTree != null && !fFilteredTree.isDisposed()) { fFilteredTree.getViewer().refresh(); fFilteredTree.setEnabled(true); } }); }

Target:
private void updateLogViewer(List<LogEntry> entries) { elements.clear(); groups.clear(); group(entries); limitEntriesCount(); String titleSummary = getTitleSummary(); getDisplay().asyncExec(() -> { if (fFilteredTree == null || fFilteredTree.isDisposed()) { return; } setContentDescription(titleSummary); fFilteredTree.getViewer().refresh(); fFilteredTree.setEnabled(true); }); }
Source:
public void rightClickBlock(GlowPlayer player, GlowBlock target, BlockFace face, ItemStack holding, Vector clickedLoc, EquipmentSlot hand) { if (placeAs != null) { placeAs.rightClickBlock(player, target, face, holding, clickedLoc, hand); } }

Target:
public void rightClickBlock(GlowPlayer player, GlowBlock target, BlockFace face, ItemStack holding, Vector clickedLoc, EquipmentSlot hand) { if (placeAs != null) { Context context = placeAs.getContext(); if ((context == Context.ANY || context == Context.BLOCK)) { placeAs.rightClickBlock(player, target, face, holding, clickedLoc, hand); } } }
Source:
public void commitBlock(long sessionId, long blockId, boolean pinOnCreate) throws BlockAlreadyExistsException, InvalidWorkerStateException, BlockDoesNotExistException, IOException { LOG.debug("commitBlock: sessionId={}, blockId={}", sessionId, blockId); long lockId = mLockManager.lockBlock(sessionId, blockId, BlockLockType.WRITE); try { BlockStoreLocation loc = commitBlockInternal(sessionId, blockId, pinOnCreate); synchronized (mBlockStoreEventListeners) { for (BlockStoreEventListener listener : mBlockStoreEventListeners) { listener.onCommitBlock(sessionId, blockId, loc); } } } finally { mLockManager.unlockBlock(lockId); } }

Target:
public void commitBlock(long sessionId, long blockId, boolean pinOnCreate) throws BlockAlreadyExistsException, InvalidWorkerStateException, BlockDoesNotExistException, IOException { LOG.debug("commitBlock: sessionId={}, blockId={}, pinOnCreate={}", sessionId, blockId, pinOnCreate); long lockId = mLockManager.lockBlock(sessionId, blockId, BlockLockType.WRITE); try { BlockStoreLocation loc = commitBlockInternal(sessionId, blockId, pinOnCreate); synchronized (mBlockStoreEventListeners) { for (BlockStoreEventListener listener : mBlockStoreEventListeners) { listener.onCommitBlock(sessionId, blockId, loc); } } } finally { mLockManager.unlockBlock(lockId); } }
Source:
public DecorateBiomeEvent(World world, Random rand, BlockPos pos) { this.world = world; this.rand = rand; this.pos = pos; chunkPos = new BlockPos((pos.getX()/16)*16, (pos.getY()/16)*16, (pos.getZ()/16)*16); }

Target:
public DecorateBiomeEvent(World world, Random rand, BlockPos pos) { this.world = world; this.rand = rand; this.pos = pos; this.chunkPos = new ChunkPos(pos); }
Source:
public String getHibernateVersion() { if (launchConfiguration.exists()){ return getAttribute(IConsoleConfigurationLaunchConstants.HIBERNATE_VERSION, "3.5"); } return null; }

Target:
public String getHibernateVersion() { String defaultVersion = "3.5"; if (launchConfiguration.exists()){ return getAttribute(IConsoleConfigurationLaunchConstants.HIBERNATE_VERSION, defaultVersion); } return defaultVersion; }
Source:
public long executeLargeUpdate() throws SQLException { internalExecuteUpdate(); return getLargeUpdateCount(); }

Target:
public long executeLargeUpdate() throws SQLException { executeWithFlags(QueryExecutor.QUERY_NO_RESULTS); checkNoResultUpdate(); return getLargeUpdateCount(); }
Source:
protected ICommand getCallEventCommand(Classifier targetClassifier, Operation operation) { ICommand command = null; if (!callEventExist(targetClassifier.eContainer(), operation)) { try { TransactionalEditingDomain domain = ServiceUtilsForEObject.getInstance().getTransactionalEditingDomain(targetClassifier); CreateElementRequest createElementRequest = new CreateElementRequest(domain, targetClassifier.eContainer(), UMLElementTypes.CallEvent_2084); createElementRequest.setParameter(OWNED_OPERATION, operation); IElementEditService provider = ElementEditServiceUtils.getCommandProvider(targetClassifier); if (provider != null) { ICommand createCommand = provider.getEditCommand(createElementRequest); if (null != createCommand) { command = createCommand; } } } catch (ServiceException e) { Activator.log.error(e); } } return command; }

Target:
protected ICommand getCallEventCommand(Classifier targetClassifier, Operation operation) { ICommand command = null; if (!callEventExist(targetClassifier.eContainer(), operation)) { try { TransactionalEditingDomain domain = ServiceUtilsForEObject.getInstance().getTransactionalEditingDomain(targetClassifier); CreateElementRequest createElementRequest = new CreateElementRequest(domain, targetClassifier.eContainer(), UMLElementTypes.CallEvent_2084); createElementRequest.setParameter(OWNED_OPERATION, operation); IElementEditService provider = ElementEditServiceUtils.getCommandProvider(targetClassifier); if (null != provider) { ICommand createCommand = provider.getEditCommand(createElementRequest); if (null != createCommand) { command = createCommand; } } } catch (ServiceException e) { Activator.log.error(e); } } return command; }
Source:
public String generateFieldInfoInputs(Class<?> cls) { java.lang.reflect.Field[] fields = cls.getDeclaredFields(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < fields.length; i++) { java.lang.reflect.Field f = fields[i]; Class<?> c = ClassUtils.primitiveToWrapper(f.getType()); sb.append(f.getName() + FIELD_SEPARATOR + f.getName() + FIELD_SEPARATOR + c.getSimpleName().toUpperCase() + RECORD_SEPARATOR); } return sb.substring(0, sb.length() - 1).toString(); }

Target:
private String generateFieldInfoInputs(Class<?> cls) { java.lang.reflect.Field[] fields = cls.getDeclaredFields(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < fields.length; i++) { java.lang.reflect.Field f = fields[i]; Class<?> c = ClassUtils.primitiveToWrapper(f.getType()); sb.append(f.getName()).append(FIELD_SEPARATOR).append(f.getName()).append(FIELD_SEPARATOR) .append(c.getSimpleName().toUpperCase()).append(RECORD_SEPARATOR); } return sb.substring(0, sb.length() - 1); }
Source:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("\n"); builder.append(super.toString()); builder.append("\n"); ObjectDescriptor.toStringBuilder(checkpointsUuids, builder); ObjectDescriptor.toStringBuilder(error, builder); return builder.toString(); }

Target:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("\n"); builder.append(super.toString()); builder.append("\n"); ObjectDescriptor.toStringBuilder(checkpointsIds, builder); ObjectDescriptor.toStringBuilder(error, builder); return builder.toString(); }
Source:
protected AbstractSerialPort(String port, int baudRate, int receiveTimeout) { this.port = port; this.baudRate = baudRate; this.receiveTimeout = receiveTimeout; }

Target:
protected AbstractSerialPort(String port, int baudRate, int receiveTimeout) { this(port, new SerialPortParameters(baudRate, DEFAULT_DATA_BITS, DEFAULT_STOP_BITS, DEFAULT_PARITY, DEFAULT_FLOW_CONTROL), receiveTimeout); }
Source:
private void verifyRevenueScheduleTypeWithInvalidValue( String invalidValue ){ Subscription subscription = new Subscription(); try{ subscription.setRevenueScheduleType( invalidValue ); assertEquals(true, false ); } catch( IllegalArgumentException iae ){ } }

Target:
private void verifyRevenueScheduleTypeWithInvalidValue( String invalidValue ){ Subscription subscription = new Subscription(); try{ subscription.setRevenueScheduleType( invalidValue ); Assert.fail(); } catch( IllegalArgumentException iae ){ } }
Source:
public void testComposedStreamThatIsItselfDeployable() throws IOException { FileSink sink = newFileSink(); HttpSource httpSource = newHttpSource(); String streamName = getRandomStreamName(); stream().createDontDeploy(streamName, "%s | filter --expression=payload.contains('${word:foo}') | %s", httpSource, sink); stream().create(getRandomStreamName(), streamName); httpSource.postData("foobar"); httpSource.postData("hello"); httpSource.postData("custardfoo"); httpSource.postData("whisk"); assertThat(sink, eventually(hasContentsThat(equalTo("foobar\ncustardfoo\n")))); }

Target:
public void testComposedStreamThatIsItselfDeployable() throws IOException { FileSink sink = newFileSink(); HttpSource httpSource = newHttpSource(); String streamName = getStreamName(); stream().createDontDeploy(streamName, "%s | filter --expression=payload.contains('${word:foo}') | %s", httpSource, sink); stream().create(getStreamName(), streamName); httpSource.postData("foobar"); httpSource.postData("hello"); httpSource.postData("custardfoo"); httpSource.postData("whisk"); assertThat(sink, eventually(hasContentsThat(equalTo("foobar\ncustardfoo\n")))); }
Source:
public void testMultipleUpdates() throws Exception { Subscriber client1 = createSubscriber(new String[] { "refs/heads/*:refs/remotes/origin/*", "refs/tags/*:refs/tags/*" }); Thread.sleep(1000); Repository r = client1.getRepository("testrepository").getRepository(); Ref ref = r.getRef("refs/pubsub/origin/heads/master"); assertNotNull(ref); ObjectId master = triggerUpdate("refs/heads/master"); ObjectId branch1 = createRef( "refs/heads/master", "refs/heads/branch1"); branch1 = triggerUpdate("refs/heads/branch1"); master = triggerUpdate("refs/heads/master"); Thread.sleep(1000); ref = r.getRef("refs/pubsub/origin/heads/master"); assertEquals(master, ref.getObjectId()); ref = r.getRef("refs/pubsub/origin/heads/branch1"); assertEquals(branch1, ref.getObjectId()); }

Target:
public void testMultipleUpdates() throws Exception { setUpPublisher(1); TestSubscriber client1 = createSubscriber(new String[] { "refs/heads/*:refs/remotes/origin/*", "refs/tags/*:refs/tags/*" }, 5); connectLatch.await(); ObjectId master = triggerUpdate("refs/heads/master"); ObjectId branch1 = createBranch( "refs/heads/master", "refs/heads/branch1"); branch1 = triggerUpdate("refs/heads/branch1"); master = triggerUpdate("refs/heads/master"); client1.await(); Repository r = client1.getRepository("testrepository").getRepository(); Ref ref = r.getRef("refs/pubsub/origin/heads/master"); assertEquals(master, ref.getObjectId()); ref = r.getRef("refs/pubsub/origin/heads/branch1"); assertEquals(branch1, ref.getObjectId()); }