auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Object[] satelReadEvent( @ParamDoc(name = "eventIndex", text = "index of event to read, -1 for the most recent") int eventIndex) { if (!satelIsConnected()) { return null; } ReadEventCommand cmd = new ReadEventCommand(eventIndex); if (!SatelActionService.satelCommModule.sendCommand(cmd)) { logger.error("Unable to read record for given index: {}", eventIndex); return null; } else if (cmd.isEmpty()) { logger.warn("No record under given index: {}", eventIndex); return null; } else { EventDescription desc = getEventDescription(cmd.getEventCode(), cmd.isRestore()); return new Object[] { new DateTimeType(cmd.getTimestamp()), cmd.getPartition(), cmd.getEventClass(), cmd.getEventCode(), cmd.isRestore(), desc.eventText, desc.descKind, cmd.getSource(), cmd.getObject(), cmd.getUserControlNumber(), cmd.getNextIndex(), cmd.getCurrentIndex() }; } }

Target:
public static Object[] satelReadEvent( @ParamDoc(name = "eventIndex", text = "index of event to read, -1 for the most recent") int eventIndex) { if (!satelIsConnected()) { logger.warn("Not connected to communication module or Satel binding not available."); return null; } ReadEventCommand cmd = new ReadEventCommand(eventIndex); if (!SatelActionService.satelCommModule.sendCommand(cmd)) { logger.error("Unable to read record for given index: {}", eventIndex); return null; } else if (cmd.isEmpty()) { logger.warn("No record under given index: {}", eventIndex); return null; } else { EventDescription desc = getEventDescription(cmd.getEventCode(), cmd.isRestore()); return new Object[] { new DateTimeType(cmd.getTimestamp()), cmd.getPartition(), cmd.getEventClass(), cmd.getEventCode(), cmd.isRestore(), desc.eventText, desc.descKind, cmd.getSource(), cmd.getObject(), cmd.getUserControlNumber(), cmd.getNextIndex(), cmd.getCurrentIndex() }; } }
Source:
public void waitForTooYoungErrorMsg() { wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(tooYoungErrorMsg))); Assertion.assertTrue(tooYoungError.isDisplayed()); PageObjectLogging.log("typeInBirthDate ", "BirthDate field selected", true, driver); }

Target:
public void waitForTooYoungErrorMsg() { waitForElementByElement(tooYoungError); Assertion.assertTrue(tooYoungError.isDisplayed()); PageObjectLogging.log("typeInBirthDate ", "BirthDate field selected", true); }
Source:
public static Slice invalidReason(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { GeometryCursor cursor = deserialize(input).getEsriGeometryCursor(); NonSimpleResult result = new NonSimpleResult(); while (true) { com.esri.core.geometry.Geometry geometry = cursor.next(); if (geometry == null) { return null; } if (!OperatorSimplifyOGC.local().isSimpleOGC(geometry, null, true, result, null)) { String reasonText = NON_SIMPLE_REASONS.getOrDefault(result.m_reason, result.m_reason.name()); MultiVertexGeometry multiVertexGeometry = (MultiVertexGeometry) geometry; if (result.m_vertexIndex1 >= 0 && result.m_vertexIndex2 >= 0) { Point point1 = multiVertexGeometry.getPoint(result.m_vertexIndex1); Point point2 = multiVertexGeometry.getPoint(result.m_vertexIndex2); return utf8Slice(format("%s at or near (%s %s) and (%s %s)", reasonText, point1.getX(), point1.getY(), point2.getX(), point2.getY())); } if (result.m_vertexIndex1 >= 0) { Point point = multiVertexGeometry.getPoint(result.m_vertexIndex1); return utf8Slice(format("%s at or near (%s %s)", reasonText, point.getX(), point.getY())); } return utf8Slice(format("%s", reasonText)); } } }

Target:
public static Slice invalidReason(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { GeometryCursor cursor = deserialize(input).getEsriGeometryCursor(); NonSimpleResult result = new NonSimpleResult(); while (true) { com.esri.core.geometry.Geometry geometry = cursor.next(); if (geometry == null) { return null; } if (!OperatorSimplifyOGC.local().isSimpleOGC(geometry, null, true, result, null)) { String reasonText = NON_SIMPLE_REASONS.getOrDefault(result.m_reason, result.m_reason.name()); if (!(geometry instanceof MultiVertexGeometry)) { return utf8Slice(reasonText); } MultiVertexGeometry multiVertexGeometry = (MultiVertexGeometry) geometry; if (result.m_vertexIndex1 >= 0 && result.m_vertexIndex2 >= 0) { Point point1 = multiVertexGeometry.getPoint(result.m_vertexIndex1); Point point2 = multiVertexGeometry.getPoint(result.m_vertexIndex2); return utf8Slice(format("%s at or near (%s %s) and (%s %s)", reasonText, point1.getX(), point1.getY(), point2.getX(), point2.getY())); } if (result.m_vertexIndex1 >= 0) { Point point = multiVertexGeometry.getPoint(result.m_vertexIndex1); return utf8Slice(format("%s at or near (%s %s)", reasonText, point.getX(), point.getY())); } return utf8Slice(reasonText); } } }
Source:
private int outputLicense(Configuration config) { File licFH = new VoltFile(config.m_voltdbRoot.getParent(), "license.xml"); try { if (!licFH.isFile() || !licFH.canRead()) { consoleLog.fatal("Failed to get license. " + licFH.getAbsolutePath()); return -1; } config.m_pathToLicense = licFH.getCanonicalPath(); } catch (IOException e) { consoleLog.fatal("Failed to read license: " + e.getMessage()); return -1; } try { if ((new File(config.m_getOutput)).exists() && !config.m_forceGetCreate) { consoleLog.fatal("Failed to save license.xml, file already exists: " + config.m_getOutput); return -1; } try { File target = new File("./license.xml"); InputStream is = null; OutputStream os = null; try { is = new FileInputStream(licFH); os = new FileOutputStream(target); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } } finally { is.close(); os.close(); } } catch (IOException e) { consoleLog.fatal("Failed to copy license to " + config.m_getOutput + " : " + e.getMessage()); return -1; } consoleLog.info("license.xml saved in " + config.m_getOutput.trim()); } catch (Exception e) { consoleLog.fatal("Failed to get license. " + "Please make sure voltdbroot is a valid directory. " + e.getMessage()); return -1; } return 0; }

Target:
private int outputLicense(Configuration config) { File licFH = new VoltFile(config.m_pathToLicense); if (!licFH.isFile() || !licFH.canRead()) { consoleLog.fatal("Failed to get license. " + licFH.getAbsolutePath()); return -1; } try { if ((new File(config.m_getOutput)).exists() && !config.m_forceGetCreate) { consoleLog.fatal("Failed to save license.xml, file already exists: " + config.m_getOutput); return -1; } try { File target = new File(config.m_getOutput); InputStream is = null; OutputStream os = null; try { is = new FileInputStream(licFH); os = new FileOutputStream(target); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } } finally { is.close(); os.close(); } } catch (IOException e) { consoleLog.fatal("Failed to copy license to " + config.m_getOutput + " : " + e.getMessage()); return -1; } consoleLog.info("license saved as " + config.m_getOutput.trim()); } catch (Exception e) { consoleLog.fatal("Failed to get license. " + "Please make sure voltdbroot is a valid directory. " + e.getMessage()); return -1; } return 0; }
Source:
public DataRegistration<M, I> build() { validate(); this.container = Sponge.getCauseStackManager().getCurrentCause().first(PluginContainer.class).get(); return new SpongeDataRegistration<>(this); }

Target:
public DataRegistration<M, I> build() { validate(); this.container = Sponge.getCauseStackManager().getCurrentCause().first(PluginContainer.class) .orElseThrow(() -> new IllegalStateException("Cannot find a PluginContainer in the current Cause.")); return new SpongeDataRegistration<>(this); }
Source:
protected void onAddElement(Rule rule) throws IllegalArgumentException { Rule ruleWithUID = rule; if (rule.getUID() == null) { ruleWithUID = ruleEngine.initRuleId(rule); } String rUID = ruleWithUID.getUID(); postRuleAddedEvent(ruleWithUID); ruleEngine.addRule(ruleWithUID, (disabledRulesStorage != null && disabledRulesStorage.get(rUID) == null)); Rule resolvedRule = resolveRuleByTemplate(ruleWithUID); if (ruleWithUID != resolvedRule) { super.update(resolvedRule); } }

Target:
protected void onAddElement(Rule rule) throws IllegalArgumentException { String uid = rule.getUID(); ruleEngine.addRule(rule, (disabledRulesStorage != null && disabledRulesStorage.get(uid) == null)); String templateUID = rule.getTemplateUID(); if (templateUID != null) { synchronized (this) { Set<String> ruleUIDs = mapTemplateToRules.get(templateUID); if (ruleUIDs == null) { ruleUIDs = new HashSet<String>(11); mapTemplateToRules.put(templateUID, ruleUIDs); } ruleUIDs.add(uid); } } }
Source:
public void shutdown(final String taskId) { if (!started) { log.info("This TaskRunner is stopped. Ignoring shutdown command for task: %s", taskId); } else if (pendingTasks.remove(taskId) != null) { pendingTaskPayloads.remove(taskId); log.info("Removed task from pending queue: %s", taskId); } else if (completeTasks.containsKey(taskId)) { cleanup(taskId); } else { final ZkWorker zkWorker = findWorkerRunningTask(taskId); if (zkWorker == null) { log.info("Can't shutdown! No worker running task %s", taskId); return; } URL url = null; try { url = makeWorkerURL(zkWorker.getWorker(), String.format("/task/%s/shutdown", taskId)); final StatusResponseHolder response = httpClient.go( new Request(HttpMethod.POST, url), RESPONSE_HANDLER ).get(config.getTaskCleanupTimeout().getMillis(), TimeUnit.MILLISECONDS); log.info( "Sent shutdown message to worker: %s, status %s, response: %s", zkWorker.getWorker().getHost(), response.getStatus(), response.getContent() ); if (!response.getStatus().equals(HttpResponseStatus.ACCEPTED)) { log.error("Shutdown failed for %s! Are you sure the task was running?", taskId); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RE(e, "Timed out posting shutdown to [%s] for task [%s]", url, taskId); } catch (Exception e) { throw new RE(e, "Error in handling post to [%s] for task [%s]", zkWorker.getWorker().getHost(), taskId); } } }

Target:
public void shutdown(final String taskId) { if (!started) { log.info("This TaskRunner is stopped. Ignoring shutdown command for task: %s", taskId); } else if (pendingTasks.remove(taskId) != null) { pendingTaskPayloads.remove(taskId); log.info("Removed task from pending queue: %s", taskId); } else if (completeTasks.containsKey(taskId)) { cleanup(taskId); } else { final ZkWorker zkWorker = findWorkerRunningTask(taskId); if (zkWorker == null) { log.info("Can't shutdown! No worker running task %s", taskId); return; } URL url = null; try { url = makeWorkerURL(zkWorker.getWorker(), String.format("/task/%s/shutdown", taskId)); final StatusResponseHolder response = httpClient.go( new Request(HttpMethod.POST, url), RESPONSE_HANDLER, shutdownTimeout ).get(); log.info( "Sent shutdown message to worker: %s, status %s, response: %s", zkWorker.getWorker().getHost(), response.getStatus(), response.getContent() ); if (!response.getStatus().equals(HttpResponseStatus.ACCEPTED)) { log.error("Shutdown failed for %s! Are you sure the task was running?", taskId); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RE(e, "Interrupted posting shutdown to [%s] for task [%s]", url, taskId); } catch (Exception e) { throw new RE(e, "Error in handling post to [%s] for task [%s]", zkWorker.getWorker().getHost(), taskId); } } }
Source:
private void startTaskExecutorInContainer(Container container, TaskExecutorProcessSpec taskExecutorProcessSpec, ResourceID resourceId, CompletableFuture<YarnWorkerNode> requestResourceFuture) { final YarnWorkerNode yarnWorkerNode = new YarnWorkerNode(container, resourceId); try { ContainerLaunchContext taskExecutorLaunchContext = createTaskExecutorLaunchContext( resourceId, container.getNodeId().getHost(), taskExecutorProcessSpec); nodeManagerClient.startContainerAsync(container, taskExecutorLaunchContext); } catch (Throwable t) { requestResourceFuture.completeExceptionally(t); } requestResourceFuture.complete(yarnWorkerNode); }

Target:
private void startTaskExecutorInContainer(Container container, TaskExecutorProcessSpec taskExecutorProcessSpec, ResourceID resourceId, CompletableFuture<YarnWorkerNode> requestResourceFuture) { final YarnWorkerNode yarnWorkerNode = new YarnWorkerNode(container, resourceId); try { ContainerLaunchContext taskExecutorLaunchContext = createTaskExecutorLaunchContext( resourceId, container.getNodeId().getHost(), taskExecutorProcessSpec); nodeManagerClient.startContainerAsync(container, taskExecutorLaunchContext); requestResourceFuture.complete(yarnWorkerNode); } catch (Throwable t) { requestResourceFuture.completeExceptionally(t); } }
Source:
public Void call() throws Exception { try { this.trigger.initialize(this.getJobContext().getWorkingMemory().getKnowledgeRuntime()); this.trigger.nextFireTime(); if ( handle.isCancel() ) { return null; } this.job.execute( this.ctx ); if ( handle.isCancel() ) { return null; } Date date = this.trigger.hasNextFireTime(); if ( date != null ) { scheduler.internalSchedule( this ); } } catch(Exception e) { logger.warn("Unable to execute timer job!", e); throw e; } return null; }

Target:
public Void call() throws Exception { try { this.trigger.initialize(this.getJobContext().getInternalKnowledgeRuntime().orElse(null)); this.trigger.nextFireTime(); if ( handle.isCancel() ) { return null; } this.job.execute( this.ctx ); if ( handle.isCancel() ) { return null; } Date date = this.trigger.hasNextFireTime(); if ( date != null ) { scheduler.internalSchedule( this ); } } catch(Exception e) { logger.warn("Unable to execute timer job!", e); throw e; } return null; }
Source:
public Set<Diff> getDirectResultingMerges(Diff target, boolean mergeRightToLeft) { final Set<Diff> resulting = new LinkedHashSet<Diff>(); if (mergeRightToLeft) { if (DifferenceSource.LEFT == target.getSource()) { resulting.addAll(target.getImpliedBy()); } else { resulting.addAll(target.getImplies()); } } else { if (DifferenceSource.LEFT == target.getSource()) { resulting.addAll(target.getImplies()); } else { resulting.addAll(target.getImpliedBy()); } } if (target.getEquivalence() != null) { resulting.addAll(target.getEquivalence().getDifferences()); resulting.remove(target); } if (target.getConflict() != null && target.getConflict().getKind() == ConflictKind.PSEUDO) { resulting.addAll(target.getConflict().getDifferences()); resulting.remove(target); } for (Diff refine : target.getRefines()) { Set<Diff> tmp = Sets.newHashSet(resulting); tmp.add(target); Collection<Diff> notUnresolvedRefinedBy = Collections2.filter(refine.getRefinedBy(), EMFComparePredicates.hasState(DifferenceState.UNRESOLVED)); if (tmp.containsAll(notUnresolvedRefinedBy)) { resulting.add(refine); } } if (target instanceof ReferenceChange) { final ReferenceChange refTarget = (ReferenceChange)target; if (isOneToOneAndChange(refTarget)) { resulting.addAll(findInterlockedOneToOneDiffs(refTarget, mergeRightToLeft)); } } return resulting; }

Target:
public Set<Diff> getDirectResultingMerges(Diff target, boolean mergeRightToLeft) { final Set<Diff> resulting = new LinkedHashSet<Diff>(); if (mergeRightToLeft) { if (DifferenceSource.LEFT == target.getSource()) { resulting.addAll(target.getImpliedBy()); } else { resulting.addAll(target.getImplies()); } } else { if (DifferenceSource.LEFT == target.getSource()) { resulting.addAll(target.getImplies()); } else { resulting.addAll(target.getImpliedBy()); } } if (target.getEquivalence() != null) { resulting.addAll(target.getEquivalence().getDifferences()); resulting.remove(target); } if (target.getConflict() != null && target.getConflict().getKind() == ConflictKind.PSEUDO) { resulting.addAll(target.getConflict().getDifferences()); resulting.remove(target); } for (Diff refine : target.getRefines()) { Set<Diff> tmp = Sets.newHashSet(resulting); tmp.add(target); Collection<Diff> unresolvedRefinedDiffs = Collections2.filter(refine.getRefinedBy(), EMFComparePredicates.hasState(DifferenceState.UNRESOLVED)); if (tmp.containsAll(unresolvedRefinedDiffs)) { resulting.add(refine); } } if (target instanceof ReferenceChange) { final ReferenceChange refTarget = (ReferenceChange)target; if (isOneToOneAndChange(refTarget)) { resulting.addAll(findInterlockedOneToOneDiffs(refTarget, mergeRightToLeft)); } } return resulting; }
Source:
private String normalizeWindowGlobals(String name) { if (name.startsWith("window.") || name.startsWith("this.")) { return name.replaceAll("^(window|this)\\.", ""); } return name; }

Target:
private String normalizeWindowGlobals(String name) { return name.replaceAll("^(window|this)\\.", ""); }
Source:
public void removeAssignment(String providerId, String dataSetId, String recordId, String schema, String versionId) throws DataSetNotExistsException { isDataSetExists(providerId, dataSetId); dataSetDAO.removeAssignment(providerId, dataSetId, recordId, schema, versionId); DataProvider dataProvider = uis.getProvider(providerId); if (!dataSetDAO.hasMoreRepresentations(providerId, dataSetId, schema)) { dataSetDAO.removeRepresentationNameForDataSet(schema, providerId, dataSetId); } Representation representation = recordDAO.getRepresentation(recordId, schema, versionId); representationIndexer.removeAssignment(recordId, schema, new CompoundDataSetId(providerId, dataSetId), dataProvider.getPartitionKey()); Set<String> deletedRevisions = new HashSet<>(); if (representation != null) { for (Revision revision : representation.getRevisions()) { String revisionName = revision.getRevisionName(); String revisionProvider = revision.getRevisionProviderId(); String revisionId = revisionName + "_" + revisionProvider; if (!deletedRevisions.contains(revisionId)) { dataSetDAO.deleteLatestProviderDatasetRepresentationInfo(dataSetId, providerId, recordId, schema, revisionName, revisionProvider); deletedRevisions.add(revisionId); } dataSetDAO.removeDataSetsRevision(providerId, dataSetId, RevisionUtils.getRevisionKey(revision), schema, recordId); dataSetDAO.deleteProviderDatasetRepresentationInfo(dataSetId, providerId, recordId, schema, revision.getUpdateTimeStamp()); } } if (!deletedRevisions.isEmpty()) { } }

Target:
public void removeAssignment(String providerId, String dataSetId, String recordId, String schema, String versionId) throws DataSetNotExistsException { isDataSetExists(providerId, dataSetId); dataSetDAO.removeAssignment(providerId, dataSetId, recordId, schema, versionId); DataProvider dataProvider = uis.getProvider(providerId); if (!dataSetDAO.hasMoreRepresentations(providerId, dataSetId, schema)) { dataSetDAO.removeRepresentationNameForDataSet(schema, providerId, dataSetId); } Representation representation = recordDAO.getRepresentation(recordId, schema, versionId); representationIndexer.removeAssignment(recordId, schema, new CompoundDataSetId(providerId, dataSetId), dataProvider.getPartitionKey()); Set<String> deletedRevisions = new HashSet<>(); if (representation != null) { for (Revision revision : representation.getRevisions()) { String revisionName = revision.getRevisionName(); String revisionProvider = revision.getRevisionProviderId(); String revisionId = revisionName + "_" + revisionProvider; if (!deletedRevisions.contains(revisionId)) { dataSetDAO.deleteLatestProviderDatasetRepresentationInfo(dataSetId, providerId, recordId, schema, revisionName, revisionProvider); deletedRevisions.add(revisionId); } dataSetDAO.removeDataSetsRevision(providerId, dataSetId, RevisionUtils.getRevisionKey(revision), schema, recordId); dataSetDAO.deleteProviderDatasetRepresentationInfo(dataSetId, providerId, recordId, schema, revision.getUpdateTimeStamp()); DataSet ds = dataSetDAO.getDataSet(providerId, dataSetId); dataSetDAO.removeLatestRevisionForDatasetAssignment(ds, representation, revision); } } if (!deletedRevisions.isEmpty()) { } }
Source:
public static float seededRandomFloat(float min, float max) { float result = max; if (min == max) { Gdx.app.log("SolMath", "rnd was called with bad parameters! Min " + min + " matches max " + max + ", accepting max."); Gdx.app.log("SolMath", "Please review appropriate code in the stack dump:"); for (StackTraceElement ste : Thread.currentThread().getStackTrace()) { Gdx.app.log("SolMath", ste.toString()); } return result; } return seededRandom.nextFloat() * (max - min) + min; }

Target:
public static float seededRandomFloat(float min, float max) { if (min >= max) { Gdx.app.log("SolMath", "seededRandomFloat was called with bad parameters! Min " + min + " >= max " + max + "."); Gdx.app.log("SolMath", "Please review appropriate code in the stack dump:"); for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace()) { Gdx.app.log("SolMath", stackTraceElement.toString()); } return max; } return seededRandom.nextFloat() * (max - min) + min; }
Source:
public void execute() throws Exception { if (!CassandraMonitor.hasCassadraStarted()) { logger.debug("Cassandra has not started, hence SnapshotMetaService will not run"); return; } if (!lock.tryLock()) { logger.error("SnapshotMetaService is already running! Try again later."); throw new Exception("SnapshotMetaService already running"); } try { Instant snapshotInstant = DateUtil.getInstant(); snapshotName = generateSnapshotName(snapshotInstant); logger.info("Initializing SnapshotMetaService for taking a snapshot {}", snapshotName); metaFileManager.cleanupOldMetaFiles(); cassandraOperations.takeSnapshot(snapshotName); processSnapshot(snapshotInstant).uploadMetaFile(true); logger.info("Finished processing snapshot meta service"); } catch (Exception e) { logger.error("Error while executing SnapshotMetaService", e); } finally { lock.unlock(); } }

Target:
public void execute() throws Exception { if (!CassandraMonitor.hasCassadraStarted()) { logger.debug("Cassandra has not started, hence SnapshotMetaService will not run"); return; } if (!lock.tryLock()) { logger.warn("SnapshotMetaService is already running! Try again later."); throw new Exception("SnapshotMetaService already running"); } try { Instant snapshotInstant = DateUtil.getInstant(); snapshotName = generateSnapshotName(snapshotInstant); logger.info("Initializing SnapshotMetaService for taking a snapshot {}", snapshotName); metaFileManager.cleanupOldMetaFiles(); cassandraOperations.takeSnapshot(snapshotName); processSnapshot(snapshotInstant).uploadMetaFile(true); logger.info("Finished processing snapshot meta service"); } catch (Exception e) { logger.error("Error while executing SnapshotMetaService", e); } finally { lock.unlock(); } }
Source:
void onStart(ConfigurationPropertySource propertySource) { if ( clientImplementor == null ) { clientImplementor = clientFactoryHolder.get().create( propertySource, threadPoolProvider, defaultGsonProvider ); clientFactoryHolder.close(); if ( versionCheckEnabled ) { elasticsearchVersion = ElasticsearchClientUtils.getElasticsearchVersion( clientImplementor ); if ( configuredVersionOptional.isPresent() ) { ElasticsearchVersion configuredVersion = configuredVersionOptional.get(); if ( !configuredVersion.matches( elasticsearchVersion ) ) { throw log.unexpectedElasticsearchVersion( configuredVersion, elasticsearchVersion ); } } } else if ( configuredVersionOptional.isPresent() ) { ElasticsearchVersion configuredVersion = configuredVersionOptional.get(); if ( configuredVersion.getMinor().isPresent() && configuredVersion.getMicro().isPresent() ) { elasticsearchVersion = configuredVersion; } else { throw log.invalidElasticsearchVersionCheckConfiguration( configuredVersion.toString() ); } } else { throw log.invalidElasticsearchVersionCheckConfiguration( null ); } ElasticsearchProtocolDialect protocolDialect = dialectFactory.createProtocolDialect( elasticsearchVersion ); gsonProvider = GsonProvider.create( GsonBuilder::new, logPrettyPrinting ); indexMetadataSyntax = protocolDialect.createIndexMetadataSyntax(); searchSyntax = protocolDialect.createSearchSyntax(); workBuilderFactory = protocolDialect.createWorkBuilderFactory( gsonProvider ); searchResultExtractorFactory = protocolDialect.createSearchResultExtractorFactory(); } }

Target:
void onStart(ConfigurationPropertySource propertySource) { if ( clientImplementor == null ) { clientImplementor = clientFactoryHolder.get().create( propertySource, threadPoolProvider, defaultGsonProvider ); clientFactoryHolder.close(); if ( versionCheckEnabled ) { elasticsearchVersion = ElasticsearchClientUtils.getElasticsearchVersion( clientImplementor ); if ( configuredVersionOptional.isPresent() ) { ElasticsearchVersion configuredVersion = configuredVersionOptional.get(); if ( !configuredVersion.matches( elasticsearchVersion ) ) { throw log.unexpectedElasticsearchVersion( configuredVersion, elasticsearchVersion ); } } } else { configuredVersionOptional.ifPresent( version -> elasticsearchVersion = version ); } ElasticsearchProtocolDialect protocolDialect = dialectFactory.createProtocolDialect( elasticsearchVersion ); gsonProvider = GsonProvider.create( GsonBuilder::new, logPrettyPrinting ); indexMetadataSyntax = protocolDialect.createIndexMetadataSyntax(); searchSyntax = protocolDialect.createSearchSyntax(); workBuilderFactory = protocolDialect.createWorkBuilderFactory( gsonProvider ); searchResultExtractorFactory = protocolDialect.createSearchResultExtractorFactory(); } }
Source:
public AEColor[] toColors( short frequency ) { final AEColor[] colours = new AEColor[4]; for( int i = 0; i < 4; i++ ) { int nibble = ( frequency >> 4 * ( 3 - i ) ) & 0xF; colours[i] = AEColor.values()[nibble]; } return colours; }

Target:
public AEColor[] toColors( short frequency ) { final AEColor[] colors = new AEColor[4]; for( int i = 0; i < 4; i++ ) { int nibble = ( frequency >> 4 * ( 3 - i ) ) & 0xF; colors[i] = AEColor.values()[nibble]; } return colors; }
Source:
public void saveOrUpdateShouldThrowIAEWhenUserCannotBeFoundById() { given(this.userRepository.findOne(USER_ID)).willReturn(NULL_USER_ENTITY); given(this.passwordHistoryRepository.findByUserEntity(NULL_USER_ENTITY)).willThrow(IllegalArgumentException.class); this.passwordChangeService.saveOrUpdate(passwordHistoryDtoWithUserId); }

Target:
public void saveOrUpdateShouldThrowIAEWhenUserCannotBeFoundById() { given(this.userRepository.findOne(USER_ID)).willReturn(NULL_USER_ENTITY); this.passwordChangeService.saveOrUpdate(passwordHistoryDtoWithUserId); }
Source:
public Page getNextPage() { PrestoSparkSerializedPage prestoSparkSerializedPage = null; synchronized (this) { while (prestoSparkSerializedPage == null) { if (currentIteratorIndex >= serializedPageIterators.size()) { return null; } Iterator<PrestoSparkSerializedPage> currentIterator = serializedPageIterators.get(currentIteratorIndex); if (!currentIterator.hasNext()) { currentIteratorIndex++; continue; } prestoSparkSerializedPage = currentIterator.next(); } } return pagesSerde.deserialize(toSerializedPage(prestoSparkSerializedPage)); }

Target:
public Page getNextPage() { PrestoSparkSerializedPage prestoSparkSerializedPage = null; synchronized (this) { while (prestoSparkSerializedPage == null) { if (currentIteratorIndex >= serializedPageIterators.size()) { return null; } Iterator<PrestoSparkSerializedPage> currentIterator = serializedPageIterators.get(currentIteratorIndex); if (currentIterator.hasNext()) { prestoSparkSerializedPage = currentIterator.next(); } else { currentIteratorIndex++; } } } return pagesSerde.deserialize(toSerializedPage(prestoSparkSerializedPage)); }
Source:
protected Set<Value.Immutable<?>> api$getVanillaValues() { Set<Value.Immutable<?>> vanillaValues = super.api$getVanillaValues(); if (this.caughtEntity != null) { this.targetEntity().map(Value::asImmutable).ifPresent(vanillaValues::add); } return vanillaValues; }

Target:
protected Set<Value.Immutable<?>> api$getVanillaValues() { final Set<Value.Immutable<?>> values = super.api$getVanillaValues(); values.add(this.shooter().asImmutable()); this.targetEntity().map(Value::asImmutable).ifPresent(values::add); return values; }
Source:
public void requestItems() { if (requestCount > 0) { Iterator<LoadedItem> iter = this.loadedItems.iterator(); while (iter.hasNext()) { LoadedItem item = iter.next(); if (item.isSelected() && item.isDisplayed()) { MainProxy.sendPacketToServer(PacketHandler.getPacket(SubmitFluidRequestPacket.class).setDimension(dimension).setStack(item.getStack().getItem().makeStack(requestCount)).setPosX(xCoord).setPosY(yCoord).setPosZ(zCoord)); } } } }

Target:
public void requestItems() { if (requestCount > 0) { ArrayList<ItemIdentifierStack> stacks = new ArrayList<ItemIdentifierStack>(); for (LoadedItem item : loadedItems){ if (item.isSelected() && item.isDisplayed()) { stacks.add(item.getStack().getItem().makeStack(requestCount)); } } if (stacks.size() > 0){ MainProxy.sendPacketToServer(PacketHandler.getPacket(SubmitFluidRequestPacket.class).setDimension(dimension) .setStacks(stacks.toArray(new ItemIdentifierStack[stacks.size()])).setPosX(xCoord).setPosY(yCoord).setPosZ(zCoord)); } } }
Source:
private static void convert(String e, Properties p) { String[] kv = e.split(">"); String key; String value = null; if(kv.length == 0) { key = e; } else { key = kv[0]; } if(kv.length > 1) { value = kv[1]; } p.put(urlDecode(key), urlDecode(value)); }

Target:
private static void convert(String e, Properties p) { String[] kv = e.split(PROPERTIES_KV_SEPARATOR); String key = kv[0]; String value = null; if(kv.length == 2) { value = kv[1]; } p.put(urlDecode(key), urlDecode(value)); }
Source:
public Preview.PreviewSurfaceProvider getPreviewSurfaceProvider() { return (resolution, surfaceReleaseFuture) -> { mResolution = resolution; initInternal(); mSurfaceReleaseFuture = surfaceReleaseFuture; return CallbackToFutureAdapter.getFuture( (CallbackToFutureAdapter.Resolver<Surface>) completer -> { cancelSurfaceCompleters(); mCompleterMap.put(completer, surfaceReleaseFuture); completer.addCancellationListener(() -> onCompleterCancelled(completer), ContextCompat.getMainExecutor(mTextureView.getContext())); mSurfaceCompleter = completer; tryToProvidePreviewSurface(); return "provide preview surface"; }); }; }

Target:
public Preview.PreviewSurfaceProvider getPreviewSurfaceProvider() { Threads.checkMainThread(); return (resolution, surfaceReleaseFuture) -> { mResolution = resolution; initInternal(); mSurfaceReleaseFuture = surfaceReleaseFuture; return CallbackToFutureAdapter.getFuture( (CallbackToFutureAdapter.Resolver<Surface>) completer -> { cancelSurfaceCompleters(); mCompleterMap.put(completer, surfaceReleaseFuture); completer.addCancellationListener(() -> onCompleterCancelled(completer), ContextCompat.getMainExecutor(mTextureView.getContext())); mSurfaceCompleter = completer; tryToProvidePreviewSurface(); return "provide preview surface"; }); }; }
Source:
public void testTokenForDisabledUser() { UserDetails userDetails = mock(UserDetails.class); runAsUserTokenFactory.create("test", userDetails, null); verify(userDetailsChecker).check(userDetails); }

Target:
public void testTokenForDisabledUser() { UserDetails userDetails = mock(UserDetails.class); doThrow(new DisabledException("User is disabled.")).when(userDetailsChecker).check(userDetails); runAsUserTokenFactory.create("test", userDetails, null); }
Source:
private Option<String> serializeValue(Object value) { if (value == null) { return Option.empty(); } String rawValue; try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (serializer == null) { if (DEFAULT_SERIALIZER == null) { synchronized (SERIALIZER_INSTANTIATION_SYNCHRONIZER) { if (DEFAULT_SERIALIZER == null) { DEFAULT_SERIALIZER = JsonSerializerProviders.createInstance(); } } } DEFAULT_SERIALIZER.serialize(outputStream, value); } else { serializer.serialize(outputStream, value); } rawValue = outputStream.toString("UTF-8"); } catch (IOException ex) { throw logger.logExceptionAsError(new UncheckedIOException(ex)); } return Option.of(rawValue); }

Target:
private Option<String> serializeValue(Object value) { if (value == null) { return Option.empty(); } String rawValue; try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (serializer == null) { if (defaultSerializer == null) { synchronized (SERIALIZER_INSTANTIATION_SYNCHRONIZER) { if (defaultSerializer == null) { defaultSerializer = JsonSerializerProviders.createInstance(); } } } defaultSerializer.serialize(outputStream, value); } else { serializer.serialize(outputStream, value); } rawValue = outputStream.toString("UTF-8"); } catch (IOException ex) { throw logger.logExceptionAsError(new UncheckedIOException(ex)); } return Option.of(rawValue); }
Source:
public void transform(ColumnVector outputColVector, ColumnVector inputVector, int idx) { boolean isBooleanType = this.getInputTypeInfos()[0].getTypeName().equals(serdeConstants.BOOLEAN_TYPE_NAME); if(inputVector.isNull[idx] || isBooleanType) { outputColVector.isNull[idx] = true; outputColVector.noNulls = false; return; } outputColVector.isNull[idx] = false; long[] inputCol = ((LongColumnVector)inputVector).vector; long[] outputCol = ((LongColumnVector)outputColVector).vector; long value = inputCol[idx]; long val = value; if(value < 0) { val *= -1; } long ret = 0; long pos = 1; for(int i = 0; val != 0; i++) { ret += maskedNumber * pos; val /= 10; pos *= 10; } if(value < 0) { ret *= -1; } outputCol[idx] = ret; }

Target:
public void transform(ColumnVector outputColVector, ColumnVector inputVector, int idx) { boolean isBooleanType = this.getInputTypeInfos()[0].getTypeName().equals(serdeConstants.BOOLEAN_TYPE_NAME); if(isBooleanType) { outputColVector.isNull[idx] = true; outputColVector.noNulls = false; return; } outputColVector.isNull[idx] = false; long[] inputCol = ((LongColumnVector)inputVector).vector; long[] outputCol = ((LongColumnVector)outputColVector).vector; long value = inputCol[idx]; long val = value; if(value < 0) { val *= -1; } long ret = 0; long pos = 1; for(int i = 0; val != 0; i++) { ret += maskedNumber * pos; val /= 10; pos *= 10; } if(value < 0) { ret *= -1; } outputCol[idx] = ret; }
Source:
public void removeProject(DiffProject project) { DiffProject[] temp = new DiffProject[fDiffProjects.length - 1]; int counter = 0; for (DiffProject fDiffProject : fDiffProjects) { if (fDiffProject != project) { temp[counter++] = fDiffProject; } } fDiffProjects = temp; }

Target:
public void removeProject(DiffProject project) { DiffProject[] temp = new DiffProject[fDiffProjects.length - 1]; int counter = 0; for (DiffProject diffProject : fDiffProjects) { if (diffProject != project) { temp[counter++] = diffProject; } } fDiffProjects = temp; }
Source:
public Data getCore() { IPv4 ipv4 = (IPv4) getPayload(); UDP udp = (UDP) ipv4.getPayload(); return (Data) udp.getPayload(); }

Target:
public ElasticData getCore() { IPv4 ipv4 = (IPv4) getPayload(); UDP udp = (UDP) ipv4.getPayload(); return (ElasticData) udp.getPayload(); }
Source:
private Response evalVelocity(final HttpServletRequest request, final HttpServletResponse response, final Reader velocityReader, final Map<String, Object> contextParams, final User user, final DotJSONCache cache) throws Exception { final org.apache.velocity.context.Context context = VelocityUtil.getInstance().getContext(request, response); contextParams.forEach(context::put); context.put("dotJSON", new DotJSON()); final StringWriter evalResult = new StringWriter(); try { VelocityUtil.getEngine().evaluate(context, evalResult, "", velocityReader); } catch(MethodInvocationException e) { if(e.getCause() instanceof DotToolException) { throw (Exception) (e.getCause()).getCause(); } } final DotJSON dotJSON = (DotJSON) context.get("dotJSON"); if(dotJSON.size()==0) { return Response.ok(evalResult.toString()).build(); } else { if(UtilMethods.isSet(dotJSON.get("errors"))) { return Response.status(Response.Status.BAD_REQUEST).entity(dotJSON.get("errors")).build(); } cache.add(request, user, dotJSON); return Response.ok(dotJSON.getMap()).build(); } }

Target:
private Response evalVelocity(final HttpServletRequest request, final HttpServletResponse response, final Reader velocityReader, final Map<String, Object> contextParams, final User user, final DotJSONCache cache) throws Exception { final org.apache.velocity.context.Context context = VelocityUtil.getInstance().getContext(request, response); contextParams.forEach(context::put); context.put("dotJSON", new DotJSON()); final StringWriter evalResult = new StringWriter(); try { VelocityUtil.getEngine().evaluate(context, evalResult, "", velocityReader); } catch(MethodInvocationException e) { if(e.getCause() instanceof DotToolException) { Logger.error(this,"Error evaluating velocity: " + (e.getCause()).getCause().getMessage()); throw (Exception) (e.getCause()).getCause(); } } final DotJSON dotJSON = (DotJSON) context.get("dotJSON"); if(dotJSON.size()==0) { return Response.ok(evalResult.toString()).build(); } else { if(UtilMethods.isSet(dotJSON.get("errors"))) { return Response.status(Response.Status.BAD_REQUEST).entity(dotJSON.get("errors")).build(); } cache.add(request, user, dotJSON); return Response.ok(dotJSON.getMap()).build(); } }
Source:
public PropertyHandle<T> getHandle() { if ( handle == null ) { try { handle = introspector.createPropertyHandle( name, member ); } catch (IllegalAccessException | RuntimeException e) { throw log.errorRetrievingPropertyTypeModel( getName(), holderTypeModel, e ); } } return handle; }

Target:
public PropertyHandle<T> getHandle() { if ( handle == null ) { try { handle = (PropertyHandle<T>) introspector.createPropertyHandle( name, member ); } catch (IllegalAccessException | RuntimeException e) { throw log.errorRetrievingPropertyTypeModel( getName(), holderTypeModel, e ); } } return handle; }
Source:
public void canDoActionFailsOnNullCluster() { cmd = spy(new EnableGlusterHookCommand(new GlusterHookParameters(null, HOOK_ID))); setupMocks(); assertFalse(cmd.canDoAction()); }

Target:
public void canDoActionFailsOnNullCluster() { cmd = spy(new EnableGlusterHookCommand(new GlusterHookParameters(null, HOOK_ID))); setupMocks(); assertFalse(cmd.canDoAction()); assertTrue(cmd.getReturnValue().getCanDoActionMessages().contains(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_IS_NOT_VALID.toString())); }
Source:
public List<Destination> getDestinations(FilterType filterType) { Predicate<Destination> filter; switch (filterType) { case PROJECT_CREATION : filter = FOR_CREATION; break; case PROJECT_DELETION : filter = FOR_DELETION; break; case ALL : return destinations; default : filter = null; break; } return FluentIterable.from(destinations).filter(filter).toList(); }

Target:
public List<Destination> getDestinations(FilterType filterType) { Predicate<Destination> filter; switch (filterType) { case PROJECT_CREATION : filter = new Predicate<Destination>() { @Override public boolean apply(Destination dest) { if (dest == null || !dest.isCreateMissingRepos()) { return false; } return true; } }; break; case PROJECT_DELETION : filter = new Predicate<Destination>() { @Override public boolean apply(Destination dest) { if (dest == null || !dest.isReplicateProjectDeletions()) { return false; } return true; } }; break; case ALL : return destinations; default : return destinations; } return FluentIterable.from(destinations).filter(filter).toList(); }
Source:
synchronized void recordScanStop() { if (!isScanning) return; this.scansStopped++; isScanning = false; stopTime = System.currentTimeMillis(); long scanDuration = stopTime - startTime; minScanTime = Math.min(scanDuration, minScanTime); maxScanTime = Math.max(scanDuration, maxScanTime); totalScanTime += scanDuration; LastScan curr = lastScans.get(lastScans.size() - 1); curr.duration = scanDuration; if (lastScans.size() > NUM_SCAN_DURATIONS_KEPT) { lastScans.remove(0); } BluetoothProto.ScanEvent scanEvent = new BluetoothProto.ScanEvent(); scanEvent.setScanEventType(BluetoothProto.ScanEvent.SCAN_EVENT_STOP); scanEvent.setScanTechnologyType(BluetoothProto.ScanEvent.SCAN_TECH_TYPE_LE); scanEvent.setEventTimeMillis(System.currentTimeMillis()); String initiator = appName; String[] nameSplit = initiator.split("\\."); if (nameSplit.length > 3) { initiator = nameSplit[0] + "." + nameSplit[1] + "." + nameSplit[2]; } scanEvent.setInitiator(initiator); gattService.addScanEvent(scanEvent); }

Target:
synchronized void recordScanStop() { if (!isScanning) return; this.scansStopped++; isScanning = false; stopTime = System.currentTimeMillis(); long scanDuration = stopTime - startTime; minScanTime = Math.min(scanDuration, minScanTime); maxScanTime = Math.max(scanDuration, maxScanTime); totalScanTime += scanDuration; LastScan curr = lastScans.get(lastScans.size() - 1); curr.duration = scanDuration; if (lastScans.size() > NUM_SCAN_DURATIONS_KEPT) { lastScans.remove(0); } BluetoothProto.ScanEvent scanEvent = new BluetoothProto.ScanEvent(); scanEvent.setScanEventType(BluetoothProto.ScanEvent.SCAN_EVENT_STOP); scanEvent.setScanTechnologyType(BluetoothProto.ScanEvent.SCAN_TECH_TYPE_LE); scanEvent.setEventTimeMillis(System.currentTimeMillis()); scanEvent.setInitiator(fixAppName(appName)); gattService.addScanEvent(scanEvent); }
Source:
public void visitFileInput(PyFileInputTree pyFileInputTree) { scopesByRootTree = new HashMap<>(); pyFileInputTree.accept(new FirstPhaseVisitor()); pyFileInputTree.accept(new SecondPhaseVisitor()); scopesByRootTree.values().stream() .filter(scope -> scope.rootTree.is(Kind.FUNCDEF)) .forEach(scope -> { PyFunctionDefTree funcDef = (PyFunctionDefTree) scope.rootTree; for (TreeSymbol symbol : scope.symbols()) { ((PyFunctionDefTreeImpl) funcDef).addLocalVariableSymbol(symbol); } }); }

Target:
public void visitFileInput(PyFileInputTree pyFileInputTree) { scopesByRootTree = new HashMap<>(); pyFileInputTree.accept(new FirstPhaseVisitor()); pyFileInputTree.accept(new SecondPhaseVisitor()); scopesByRootTree.values().stream() .filter(scope -> scope.rootTree instanceof PyFunctionLikeTree) .forEach(scope -> { PyFunctionLikeTree funcDef = (PyFunctionLikeTree) scope.rootTree; for (TreeSymbol symbol : scope.symbols()) { if (funcDef.is(Kind.LAMBDA)) { ((PyLambdaExpressionTreeImpl) funcDef).addLocalVariableSymbol(symbol); } else { ((PyFunctionDefTreeImpl) funcDef).addLocalVariableSymbol(symbol); } } }); }
Source:
public void run() { File configFile = new File(fileName); if (!configFile.exists()) { LOGGER.debug("No config file located, cannot load from it."); return; } try (InputStream is = new FileInputStream(configFile)) { Properties props = new Properties(); props.load(is); if (props.isEmpty()) { LOGGER.debug("No applications were found in the configuration file."); return; } LOGGER.debug("Found applications to install from config."); for (Entry<Object, Object> curApp : props.entrySet()) { String appName = curApp.getKey().toString(); String appLocation = curApp.getValue().toString(); LOGGER.debug("Starting app at location: {}", appName, appLocation); startApp(appName, appLocation); } LOGGER.debug("Finished installing applications, uninstalling installer module..."); installAndUninstallFeatures(); } catch (FileNotFoundException fnfe) { LOGGER.warn("Could not file the configuration file at " + configFile.getAbsolutePath(), fnfe); } catch (IOException ioe) { LOGGER.warn("Could not load file as property list.", ioe); } }

Target:
public void run() { Properties props = PropertiesLoader.getInstance().loadProperties(fileName, null); if (props.isEmpty()) { LOGGER.debug("No applications were found in the configuration file."); return; } LOGGER.trace("Found applications to install from config."); for (Entry<Object, Object> curApp : props.entrySet()) { String appName = (String) curApp.getKey(); String appLocation = (String) curApp.getValue(); LOGGER.debug("Starting app at location: {}", appName, appLocation); startApp(appName, appLocation); } LOGGER.trace("Finished installing applications, uninstalling installer module..."); installAndUninstallFeatures(); }
Source:
public static boolean isFeatureEnabled(@NonNull Context context, @NonNull String namespace, @NonNull String name) { final int propertyVersion = getDeviceConfigPropertyInt(namespace, name, 0 ); return isFeatureVersionEnabled(context, propertyVersion); }

Target:
public static boolean isFeatureEnabled(@NonNull Context context, @NonNull String namespace, @NonNull String name) { final int propertyVersion = getDeviceConfigPropertyInt(namespace, name, 0 ); return isFeatureEnabled(context, namespace, name, false); }
Source:
protected void setup(Binder binder) { configBinder(binder).bindConfig(FileSystemConfig.class); String provider = buildConfigObject(FileSystemConfig.class).getProvider(); Module module = providers.get(provider); if (module == null) { binder.addError("Unknown filesystem provider: %s", provider); } else if (module instanceof ConfigurationAwareModule) { install(module); } else { binder.install(module); } }

Target:
protected void setup(Binder binder) { configBinder(binder).bindConfig(StorageManagerConfig.class); String fileSystemProvider = buildConfigObject(StorageManagerConfig.class).getFileSystemProvider(); Module module = providers.get(fileSystemProvider); if (module == null) { binder.addError("Unsupported file system: %s", fileSystemProvider); } else if (module instanceof ConfigurationAwareModule) { install(module); } else { binder.install(module); } }
Source:
public Iterable<User> getUsersByRole(String role, String... roles) { final StringBuilder uriBuilder = new StringBuilder("/users.json"); if (roles.length == 0) { uriBuilder.append("?role=").append(role); } else { uriBuilder.append("?role[]=").append(role); } for (final String curRole : roles) { uriBuilder.append("&role[]=").append(curRole); } logger.info(uriBuilder.toString()); return new PagedIterable<User>(cnst(uriBuilder.toString()), handleList(User.class, "users")); }

Target:
public Iterable<User> getUsersByRole(String role, String... roles) { final StringBuilder uriBuilder = new StringBuilder("/users.json"); if (roles.length == 0) { uriBuilder.append("?role=").append(encodeUrl(role)); } else { uriBuilder.append("?role[]=").append(encodeUrl(role)); } for (final String curRole : roles) { uriBuilder.append("&role[]=").append(encodeUrl(curRole)); } return new PagedIterable<User>(cnst(uriBuilder.toString()), handleList(User.class, "users")); }
Source:
public void parseJsonResults_Timestamp() { initWithJson(CUCUMBER_TIMESTAMPED_JSON); ReportParser reportParser = new ReportParser(configuration); List<Feature> features = reportParser.parseJsonFiles(jsonReports); assertThat(features).hasSize(3); SoftAssertions.assertSoftly(a -> { for (Feature f : features) { for (Element elm : f.getElements()) { if (elm.isScenario()) { a.assertThat(elm.getStartTime()).isNotNull(); } } } }); }

Target:
public void parseJsonResults_Timestamp() { initWithJson(CUCUMBER_TIMESTAMPED_JSON); ReportParser reportParser = new ReportParser(configuration); List<Feature> features = reportParser.parseJsonFiles(jsonReports); assertThat(features).hasSize(2); SoftAssertions.assertSoftly(a -> { for (Feature f : features) { for (Element elm : f.getElements()) { if (elm.isScenario()) { a.assertThat(elm.getStartTime()).isNotNull(); } } } }); }
Source:
public void testasync3() throws Exception { Client client = ResteasyClientBuilder.newClient(); Response response = null; getDispatcher(server).setMaxCacheSize(10); latch = new CountDownLatch(1); Builder builder = client.target("http://localhost:" + TestPortProvider.getPort() + "?asynch=true").request(); response = builder.post(Entity.entity("content", "text/plain")); Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus()); String jobUrl2 = response.getHeaderString(HttpHeaders.LOCATION); Assert.assertTrue(latch.await(3, TimeUnit.SECONDS)); response.close(); Thread.sleep(1000); builder = client.target(jobUrl2).request(); response = builder.post(Entity.entity("content", "text/plain")); Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus()); Assert.assertEquals("content", response.readEntity(String.class)); builder = client.target(jobUrl2).request(); response = builder.get(); Assert.assertEquals(HttpServletResponse.SC_GONE, response.getStatus()); response.close(); }

Target:
public void testasync3() throws Exception { Response response = null; getDispatcher(server).setMaxCacheSize(10); latch = new CountDownLatch(1); Builder builder = client.target("http://localhost:" + TestPortProvider.getPort() + "?asynch=true").request(); response = builder.post(Entity.entity("content", "text/plain")); Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus()); String jobUrl2 = response.getHeaderString(HttpHeaders.LOCATION); Assert.assertTrue(latch.await(3, TimeUnit.SECONDS)); response.close(); Thread.sleep(1000); builder = client.target(jobUrl2).request(); response = builder.post(Entity.entity("content", "text/plain")); Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus()); Assert.assertEquals("content", response.readEntity(String.class)); builder = client.target(jobUrl2).request(); response = builder.get(); Assert.assertEquals(HttpServletResponse.SC_GONE, response.getStatus()); response.close(); }