auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void initProjects() { List<ProjectDTO> projectsSortedByTitle = null; try { projectsSortedByTitle = ServiceManager.getProjectService().findAllProjectsForCurrentUser(); } catch (DataException e) { Helper.setErrorMessage("Error initializing projects", logger, e); } for (ProjectDTO projectSortedByTitle : projectsSortedByTitle) { this.projects.add(projectSortedByTitle.getTitle()); } }

Target:
private void initProjects() { List<ProjectDTO> projectsSortedByTitle = Collections.emptyList(); try { projectsSortedByTitle = ServiceManager.getProjectService().findAllProjectsForCurrentUser(); } catch (DataException e) { Helper.setErrorMessage("errorInitializingProjects", logger, e); } for (ProjectDTO projectSortedByTitle : projectsSortedByTitle) { this.projects.add(projectSortedByTitle.getTitle()); } }
Source:
public Response<?> apply(RevisionResource rsrc, Input input) throws AuthException, ResourceNotFoundException, ResourceConflictException, OrmException, IOException, BadRequestException { if (!allowDrafts) { throw new BadRequestException("Draft workflow is disabled."); } PatchSet patchSet = rsrc.getPatchSet(); PatchSet.Id patchSetId = patchSet.getId(); Change change = rsrc.getChange(); if (!patchSet.isDraft()) { throw new ResourceConflictException("Patch set is not a draft."); } if (!allowDrafts) { throw new ResourceConflictException("Draft workflow is disabled."); } if (!rsrc.getControl().canDeleteDraft(dbProvider.get())) { throw new AuthException("Not permitted to delete this draft patch set"); } deleteDraftPatchSet(patchSet, change); deleteOrUpdateDraftChange(patchSetId, change); return Response.none(); }

Target:
public Response<?> apply(RevisionResource rsrc, Input input) throws AuthException, ResourceNotFoundException, ResourceConflictException, OrmException, IOException, BadRequestException { if (!allowDrafts) { throw new BadRequestException("Draft workflow is disabled."); } PatchSet patchSet = rsrc.getPatchSet(); PatchSet.Id patchSetId = patchSet.getId(); Change change = rsrc.getChange(); if (!patchSet.isDraft()) { throw new ResourceConflictException("Patch set is not a draft."); } if (!rsrc.getControl().canDeleteDraft(dbProvider.get())) { throw new AuthException("Not permitted to delete this draft patch set"); } deleteDraftPatchSet(patchSet, change); deleteOrUpdateDraftChange(patchSetId, change); return Response.none(); }
Source:
PrometheusMetricsTracker(String poolName, CollectorRegistry registry) { if (!registered.contains(registry)) { CONNECTION_TIMEOUT_COUNTER.register(registry); ELAPSED_ACQUIRED_SUMMARY.register(registry); ELAPSED_BORROWED_SUMMARY.register(registry); ELAPSED_CREATION_SUMMARY.register(registry); registered.add(registry); } this.connectionTimeoutCounterChild = CONNECTION_TIMEOUT_COUNTER.labels(poolName); this.elapsedAcquiredSummaryChild = ELAPSED_ACQUIRED_SUMMARY.labels(poolName); this.elapsedBorrowedSummaryChild = ELAPSED_BORROWED_SUMMARY.labels(poolName); this.elapsedCreationSummaryChild = ELAPSED_CREATION_SUMMARY.labels(poolName); }

Target:
PrometheusMetricsTracker(String poolName, CollectorRegistry registry) { synchronized (registered) { if (!registered.contains(registry)) { CONNECTION_TIMEOUT_COUNTER.register(registry); ELAPSED_ACQUIRED_SUMMARY.register(registry); ELAPSED_BORROWED_SUMMARY.register(registry); ELAPSED_CREATION_SUMMARY.register(registry); registered.add(registry); } } this.connectionTimeoutCounterChild = CONNECTION_TIMEOUT_COUNTER.labels(poolName); this.elapsedAcquiredSummaryChild = ELAPSED_ACQUIRED_SUMMARY.labels(poolName); this.elapsedBorrowedSummaryChild = ELAPSED_BORROWED_SUMMARY.labels(poolName); this.elapsedCreationSummaryChild = ELAPSED_CREATION_SUMMARY.labels(poolName); }
Source:
public boolean add(Properties e) { throw new UnsupportedOperationException(MESSAGE_HISTORY_IS_IMMUTABLE); }

Target:
public boolean add(Properties e) { throw UNSUPPORTED_OPERATION_EXCEPTION_IMMUTABLE; }
Source:
public static boolean artifactExists(WebDriver driver, String name, long timeout) { String url = getUrl(driver, name); String username = getField(url, 1); String password = getField(url, 2); try { return new WebDriverWait(driver, timeout).until((k) -> checkArtifactUsingHttp(url, username, password)); } catch (Exception e) { return false; } }

Target:
public static boolean artifactExists(WebDriver driver, String name, long timeout) { String url = getUrl(driver, name); String username = getField(url, 1); String password = getField(url, 2); try { return new WebDriverWait(driver, timeout).until((k) -> checkArtifactUsingHttp(url, username, password)); } catch (Exception e) { LOGGER.debug(e); return false; } }
Source:
public void testBlobRecordWithMetadataContentV2() throws IOException, MessageFormatException { List<StoreKey> keys = getKeys(60, 5); int chunkSize = ThreadLocalRandom.current().nextInt(1, Integer.MAX_VALUE); long totalSize = (long) keys.size() * chunkSize; ByteBuffer metadataContent = getSerializedMetadataContentV2(chunkSize, totalSize, keys); int metadataContentSize = MessageFormatRecord.Metadata_Content_Format_V2.getMetadataContentSize(keys.get(0).sizeInBytes(), keys.size()); long blobSize = MessageFormatRecord.Blob_Format_V2.getBlobRecordSize(metadataContentSize); ByteBuffer blob = ByteBuffer.allocate((int) blobSize); BlobData blobData = getBlobRecordV2(metadataContentSize, BlobType.MetadataBlob, metadataContent, blob); Assert.assertEquals(metadataContentSize, blobData.getSize()); byte[] verify = new byte[metadataContentSize]; blobData.getStream().read(verify); Assert.assertArrayEquals("Metadata content mismatch", metadataContent.array(), verify); metadataContent.rewind(); CompositeBlobInfo compositeBlobInfo = deserializeMetadataContentV2(metadataContent, new MockIdFactory()); Assert.assertEquals("Chunk size doesn't match", chunkSize, compositeBlobInfo.getChunkSize()); Assert.assertEquals("Total size doesn't match", totalSize, compositeBlobInfo.getTotalSize()); Assert.assertEquals("List of keys dont match", keys, compositeBlobInfo.getKeys()); testBlobCorruption(blob, blobSize, metadataContentSize); }

Target:
public void testBlobRecordWithMetadataContentV2() throws IOException, MessageFormatException { List<StoreKey> keys = getKeys(60, 5); int[] chunkSizes = {ThreadLocalRandom.current().nextInt(1, Integer.MAX_VALUE), 15}; long[] totalSizes = {(long) keys.size() * chunkSizes[0], ((long) keys.size() * chunkSizes[1]) - 11}; for (int i = 0; i < chunkSizes.length; i++) { ByteBuffer metadataContent = getSerializedMetadataContentV2(chunkSizes[i], totalSizes[i], keys); int metadataContentSize = MessageFormatRecord.Metadata_Content_Format_V2.getMetadataContentSize(keys.get(0).sizeInBytes(), keys.size()); long blobSize = MessageFormatRecord.Blob_Format_V2.getBlobRecordSize(metadataContentSize); ByteBuffer blob = ByteBuffer.allocate((int) blobSize); BlobData blobData = getBlobRecordV2(metadataContentSize, BlobType.MetadataBlob, metadataContent, blob); Assert.assertEquals(metadataContentSize, blobData.getSize()); byte[] verify = new byte[metadataContentSize]; blobData.getStream().read(verify); Assert.assertArrayEquals("Metadata content mismatch", metadataContent.array(), verify); metadataContent.rewind(); CompositeBlobInfo compositeBlobInfo = deserializeMetadataContentV2(metadataContent, new MockIdFactory()); Assert.assertEquals("Chunk size doesn't match", chunkSizes[i], compositeBlobInfo.getChunkSize()); Assert.assertEquals("Total size doesn't match", totalSizes[i], compositeBlobInfo.getTotalSize()); Assert.assertEquals("List of keys dont match", keys, compositeBlobInfo.getKeys()); testBlobCorruption(blob, blobSize, metadataContentSize); } }
Source:
public static ByteBuf encode( ByteBufAllocator allocator, int streamId, boolean fragmentFollows, long requestN, ByteBuf metadata, ByteBuf data) { int i = (int) requestN; if (requestN > Integer.MAX_VALUE) { i = Integer.MAX_VALUE; } return encode(allocator, streamId, fragmentFollows, i, metadata, data); }

Target:
public static ByteBuf encode( ByteBufAllocator allocator, int streamId, boolean fragmentFollows, long requestN, ByteBuf metadata, ByteBuf data) { int reqN = requestN > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) requestN; return encode(allocator, streamId, fragmentFollows, reqN, metadata, data); }
Source:
private void createProjectedColumn() { Column column = (Column) this.onGoingExpression.pop(); String str = column.getProperty(ParquetMetadataProcessor.COLUMN_NUMBER, false); if (str == null) { this.exceptions.add(new TranslatorException(ParquetPlugin.Event.TEIID23007, ParquetPlugin.Util.gs(ParquetPlugin.Event.TEIID23007, column.getName()))); return; } this.projectedColumns.add(Integer.valueOf(str)); }

Target:
private void createProjectedColumn() { Column column = (Column) this.onGoingExpression.pop(); this.projectedColumnNames.add(column.getSourceName()); }
Source:
public boolean removeWatchedAddress(final Address address) { return removeWatchedAddresses(Lists.newArrayList(address)); }

Target:
public boolean removeWatchedAddress(final Address address) { return removeWatchedAddresses(ImmutableList.of(address)); }
Source:
@Override public long processInLongOutLong(int type, long val) throws IgniteCheckedException { switch (type) { case OP_SIZE: { CachePeekMode[] modes = PlatformUtils.decodeCachePeekModes((int)val); return cache.size(modes); } case OP_SIZE_LOC: { CachePeekMode[] modes = PlatformUtils.decodeCachePeekModes((int)val); return cache.localSize(modes); } case OP_ENTER_LOCK: { try { lock(val).lockInterruptibly(); return TRUE; } catch (InterruptedException e) { throw new IgniteCheckedException("Failed to enter cache lock.", e); } } case OP_EXIT_LOCK: { lock(val).unlock(); return TRUE; } case OP_CLOSE_LOCK: { Lock lock = lockMap.remove(val); assert lock != null : "Failed to unregister lock: " + val; return TRUE; } case OP_REBALANCE: { PlatformFutureUtils.listen(platformCtx, cache.rebalance().chain(new C1<IgniteFuture, Object>() { @Override public Object apply(IgniteFuture fut) { return null; } }), val, PlatformFutureUtils.TYP_OBJ, this); return TRUE; } case OP_CLEAR_CACHE: cache.clear(); return TRUE; case OP_REMOVE_ALL2: cache.removeAll(); return TRUE; case OP_RESET_QUERY_METRICS: cache.resetQueryMetrics(); return TRUE; case OP_PRELOAD_PARTITION: cache.preloadPartition((int)val); return TRUE; case OP_ENABLE_STATISTICS: cache.enableStatistics(val == FALSE ? false : true); return TRUE; } return super.processInLongOutLong(type, val); }

Target:
@Override public long processInLongOutLong(int type, long val) throws IgniteCheckedException { switch (type) { case OP_SIZE: { CachePeekMode[] modes = PlatformUtils.decodeCachePeekModes((int)val); return cache.size(modes); } case OP_SIZE_LOC: { CachePeekMode[] modes = PlatformUtils.decodeCachePeekModes((int)val); return cache.localSize(modes); } case OP_ENTER_LOCK: { try { lock(val).lockInterruptibly(); return TRUE; } catch (InterruptedException e) { throw new IgniteCheckedException("Failed to enter cache lock.", e); } } case OP_EXIT_LOCK: { lock(val).unlock(); return TRUE; } case OP_CLOSE_LOCK: { Lock lock = lockMap.remove(val); assert lock != null : "Failed to unregister lock: " + val; return TRUE; } case OP_REBALANCE: { PlatformFutureUtils.listen(platformCtx, cache.rebalance().chain(new C1<IgniteFuture, Object>() { @Override public Object apply(IgniteFuture fut) { return null; } }), val, PlatformFutureUtils.TYP_OBJ, this); return TRUE; } case OP_CLEAR_CACHE: cache.clear(); return TRUE; case OP_REMOVE_ALL2: cache.removeAll(); return TRUE; case OP_RESET_QUERY_METRICS: cache.resetQueryMetrics(); return TRUE; case OP_PRELOAD_PARTITION: cache.preloadPartition((int)val); return TRUE; case OP_ENABLE_STATISTICS: cache.enableStatistics(val == TRUE); return TRUE; } return super.processInLongOutLong(type, val); }
Source:
public void log(String path, Serializable logEntry) { Preconditions.checkNotNull(logEntry, "Null is not supported"); try { buffer.put(new Log(path, logEntry)); } catch (InterruptedException e) { log.error(e.getMessage(), e); } }

Target:
public void log(String path, Serializable logEntry) { Preconditions.checkNotNull(logEntry, "Null is not supported"); try { buffer.put(new Log(path, logEntry)); } catch (InterruptedException e) { log.error("Failed to write by path: {}", new Object[]{logEntry, path}, e); Thread.currentThread().interrupt(); } }
Source:
protected byte[] execute(EmbeddedCacheManager cacheManager, Map<String, String> parameters, EnumSet<CacheContainerAdmin.AdminFlag> adminFlags) { Set<String> cacheNames = cacheManager.getCacheNames(); StringBuilder sb = new StringBuilder("["); for(String s : cacheNames) { if (sb.length() > 0) sb.append(','); sb.append('"'); sb.append(s); sb.append('"'); } sb.append(']'); return sb.toString().getBytes(StandardCharsets.UTF_8); }

Target:
protected byte[] execute(EmbeddedCacheManager cacheManager, Map<String, String> parameters, EnumSet<CacheContainerAdmin.AdminFlag> adminFlags) { Set<String> cacheNames = cacheManager.getCacheNames(); StringBuilder sb = new StringBuilder("["); for(String s : cacheNames) { if (sb.length() > 1) sb.append(','); sb.append('"'); sb.append(s); sb.append('"'); } sb.append(']'); return sb.toString().getBytes(StandardCharsets.UTF_8); }
Source:
private void checkForNoParams(Map<String, Object> params) throws NoParam{ if(params.isEmpty()){ FVLog.log(LogLevel.DEBUG, null, "No parameters are specified. Please input the parameters and the value you want them to be set"); throw new NoParam(" No parameters are specified. Please input the parameters and the value you want them to be set! "); } }

Target:
private void checkForNoParams(Map<String, Object> params) throws NoParamException{ if(params.isEmpty()){ FVLog.log(LogLevel.DEBUG, null, "No parameters are specified. Please input the parameters and the value you want them to be set"); throw new NoParamException(" No parameters are specified. Please input the parameters and the value you want them to be set."); } }
Source:
protected InputStream handleGzipStream(InputStream in) throws Exception { RecordingInputStream stream = new RecordingInputStream(in); try { return new GZIPInputStream(stream); } catch (java.util.zip.ZipException ex) { if (stream.getBytesRead()==0) { return in; } else { log.warn( "gzip response expected but failed to read gzip headers, assuming unencoded response for request " + RequestContext.getCurrentContext() .getRequest().getRequestURL() .toString()); stream.reset(); return stream; } } finally { stream.stopRecording(); } }

Target:
protected InputStream handleGzipStream(InputStream in) throws Exception { RecordingInputStream stream = new RecordingInputStream(in); try { return new GZIPInputStream(stream); } catch (java.util.zip.ZipException | java.io.EOFException ex) { if (stream.getBytesRead()==0) { return in; } else { log.warn( "gzip response expected but failed to read gzip headers, assuming unencoded response for request " + RequestContext.getCurrentContext() .getRequest().getRequestURL() .toString()); stream.reset(); return stream; } } finally { stream.stopRecording(); } }
Source:
public void configure(Object... parameters) { super.configure(parameters); int index = 4; if (parameters != null && parameters.length >= 10) { this.sshOptions = parameters[index++].toString(); this.javaPath = parameters[index++].toString(); if (this.javaPath == null || this.javaPath.equals("")) { throw new IllegalArgumentException("A valid Java path must be supplied."); } this.schedulingPath = parameters[index++].toString(); if (parameters[index] != null) { OperatingSystem configuredTargetOs = OperatingSystem.getOperatingSystem(parameters[index++].toString()); if (configuredTargetOs == null) { throw new IllegalArgumentException("Only 'Linux', 'Windows' and 'Cygwin' are valid values for Target OS Property."); } persistedInfraVariables.put(TARGET_OS_OBJ_KEY, configuredTargetOs); } else { throw new IllegalArgumentException("Target OS parameter cannot be null"); } this.javaOptions = parameters[index++].toString(); try { if (parameters[index] != null) { persistedInfraVariables.put(CREDENTIALS_KEY, Credentials.getCredentialsBase64((byte[]) parameters[index++])); } } catch (KeyException e) { throw new IllegalArgumentException("Could not retrieve base64 credentials", e); } } else { throw new IllegalArgumentException("Invalid parameters for infrastructure creation"); } }

Target:
public void configure(Object... parameters) { super.configure(parameters); int index = 4; if (parameters != null && parameters.length >= 10) { this.sshOptions = parameters[index++].toString(); this.javaPath = parameters[index++].toString(); if (this.javaPath == null || this.javaPath.equals("")) { throw new IllegalArgumentException("A valid Java path must be supplied."); } this.schedulingPath = parameters[index++].toString(); if (parameters[index] != null) { OperatingSystem configuredTargetOs = OperatingSystem.getOperatingSystem(parameters[index++].toString()); if (configuredTargetOs == null) { throw new IllegalArgumentException("Only 'Linux', 'Windows' and 'Cygwin' are valid values for Target OS Property."); } persistedInfraVariables.put(TARGET_OS_OBJ_KEY, configuredTargetOs); } else { throw new IllegalArgumentException("Target OS parameter cannot be null"); } this.javaOptions = parameters[index++].toString(); try { Object possibleCredentials = parameters[index++]; if (possibleCredentials != null) { persistedInfraVariables.put(CREDENTIALS_KEY, Credentials.getCredentialsBase64((byte[]) possibleCredentials)); } } catch (KeyException e) { throw new IllegalArgumentException("Could not retrieve base64 credentials", e); } } else { throw new IllegalArgumentException("Invalid parameters for infrastructure creation"); } }
Source:
public void testNumOfSplits(int splitsPerRegion, int expectedNumOfSplits) throws IOException, InterruptedException, ClassNotFoundException { String jobName = "TestJobForNumOfSplits"; LOG.info("Before map/reduce startup - job " + jobName); Configuration c = new Configuration(TEST_UTIL.getConfiguration()); Scan scan = new Scan(); scan.addFamily(INPUT_FAMILY); c.setInt("hbase.mapreduce.input.mappers.per.region", splitsPerRegion); c.set(KEY_STARTROW, ""); c.set(KEY_LASTROW, ""); Job job = new Job(c, jobName); TableMapReduceUtil.initTableMapperJob(TableName.valueOf(TABLE_NAME).getNameAsString(), scan, ScanMapper.class, ImmutableBytesWritable.class, ImmutableBytesWritable.class, job); TableInputFormat tif = new TableInputFormat(); tif.setConf(job.getConfiguration()); List<InputSplit> splits = tif.getSplits(job); for (InputSplit split : splits) { TableSplit tableSplit = (TableSplit) split; Assert.assertEquals(tableSplit.getScan().getStartRow(), HConstants.EMPTY_START_ROW); Assert.assertEquals(tableSplit.getScan().getStopRow(), HConstants.EMPTY_END_ROW); } Assert.assertEquals(expectedNumOfSplits, splits.size()); }

Target:
public void testNumOfSplits(int splitsPerRegion, int expectedNumOfSplits) throws IOException, InterruptedException, ClassNotFoundException { String jobName = "TestJobForNumOfSplits"; LOG.info("Before map/reduce startup - job " + jobName); Configuration c = new Configuration(TEST_UTIL.getConfiguration()); Scan scan = new Scan(); scan.addFamily(INPUT_FAMILY); c.setInt("hbase.mapreduce.input.mappers.per.region", splitsPerRegion); c.set(KEY_STARTROW, ""); c.set(KEY_LASTROW, ""); Job job = new Job(c, jobName); TableMapReduceUtil.initTableMapperJob(TableName.valueOf(TABLE_NAME).getNameAsString(), scan, ScanMapper.class, ImmutableBytesWritable.class, ImmutableBytesWritable.class, job); TableInputFormat tif = new TableInputFormat(); tif.setConf(job.getConfiguration()); List<InputSplit> splits = tif.getSplits(job); for (InputSplit split : splits) { TableSplit tableSplit = (TableSplit) split; Assert.assertTrue(tableSplit.getScanAsString().isEmpty()); } Assert.assertEquals(expectedNumOfSplits, splits.size()); }
Source:
@Override public Object fromBody(TypedInput body, Type type) throws ConversionException { String charset = "UTF-8"; if (body.mimeType() != null) charset = MimeUtil.parseCharset(body.mimeType()); InputStreamReader isr = null; try { isr = new InputStreamReader(body.in(), charset); return gson.fromJson(isr, type); } catch (IOException e) { throw new ConversionException(e); } catch (JsonParseException e) { throw new ConversionException(e); } finally { if (isr != null) { try { isr.close(); } catch (IOException ignored) { } } } }

Target:
@Override public Object fromBody(TypedInput body, Type type) throws ConversionException { String charset = "UTF-8"; if (body.mimeType() != null) { charset = MimeUtil.parseCharset(body.mimeType()); } InputStreamReader isr = null; try { isr = new InputStreamReader(body.in(), charset); return gson.fromJson(isr, type); } catch (IOException e) { throw new ConversionException(e); } catch (JsonParseException e) { throw new ConversionException(e); } finally { if (isr != null) { try { isr.close(); } catch (IOException ignored) { } } } }
Source:
private Schema resolveComposedSchema(ComposedSchema schema) { if (schema.getOneOf() != null) { return schema.getOneOf().get(0); } else if (schema.getAnyOf() != null) { return schema.getAnyOf().get(0); } return null; }

Target:
private static Schema<?> resolveComposedSchema(ComposedSchema schema) { if (schema.getOneOf() != null) { return schema.getOneOf().get(0); } else if (schema.getAnyOf() != null) { return schema.getAnyOf().get(0); } LOG.error("Unknown composed schema type: " + schema); return null; }
Source:
public void testParseAutosuggestFeed() throws IOException { ObjectMapper mapper = NpmJacksonMapperFactory.createObjectMapper(); PackageFeed feedDef = mapper.readValue(getClass().getResourceAsStream("/json/antlr4-autosuggest/feed.json"), PackageFeed.class); assertThat(feedDef.getName()).isEqualTo("antlr4-autosuggest"); }

Target:
public void testParseAutosuggestFeed() throws Exception { ObjectMapper mapper = NpmJacksonMapperFactory.createObjectMapper(); PackageFeed feedDef = mapper.readValue(getClass().getResourceAsStream("/json/antlr4-autosuggest/feed.json"), PackageFeed.class); assertThat(feedDef.getName()).isEqualTo("antlr4-autosuggest"); }
Source:
public Event complianceCreated(Consumer consumer, SystemPurposeComplianceStatus compliance) { Map<String, Object> eventData = new HashMap<>(); eventData.put("status", compliance.getStatus()); eventData.put("reasons", Collections.unmodifiableSet(compliance.getReasons())); try { String eventDataJson = mapper.writeValueAsString(eventData); return new Event(Event.Type.CREATED, Target.SYSTEM_PURPOSE_COMPLIANCE, consumer.getName(), principalProvider.get(), consumer.getOwnerId(), consumer.getUuid(), consumer.getUuid(), eventDataJson, null, null); } catch (JsonProcessingException e) { log.error("Error while building JSON for system purpose compliance.created event.", e); throw new IseException("Error while building JSON for system purpose compliance.created event."); } }

Target:
public Event complianceCreated(Consumer consumer, SystemPurposeComplianceStatus compliance) { Map<String, Object> eventData = new HashMap<>(); eventData.put("status", compliance.getStatus()); eventData.put("reasons", Collections.unmodifiableSet(compliance.getReasons())); try { String eventDataJson = mapper.writeValueAsString(eventData); return new Event(Event.Type.CREATED, Target.SYSTEM_PURPOSE_COMPLIANCE, consumer.getName(), principalProvider.get(), consumer.getOwnerId(), consumer.getUuid(), consumer.getUuid(), eventDataJson, null, null); } catch (JsonProcessingException e) { log.error("Error while building JSON for system purpose compliance.created event.", e); throw new IseException("Error while building JSON for system purpose compliance.created event.", e); } }
Source:
private boolean equals(ArrayContainer arrayContainer) { if (getCardinality() != arrayContainer.getCardinality()) { return false; } int pos = 0; for (short i = 0; i < nbrruns; ++i) { short runStart = getValue(i); short length = getLength(i); if (arrayContainer.content[pos] != runStart) { return false; } if (arrayContainer.content[pos + length] != runStart + length) { return false; } pos += length + 1; } return pos == arrayContainer.getCardinality(); }

Target:
private boolean equals(ArrayContainer arrayContainer) { int pos = 0; for (short i = 0; i < nbrruns; ++i) { short runStart = getValue(i); short length = getLength(i); if (pos + length >= arrayContainer.getCardinality()) { return false; } if (arrayContainer.content[pos] != runStart) { return false; } if (arrayContainer.content[pos + length] != runStart + length) { return false; } pos += length + 1; } return pos == arrayContainer.getCardinality(); }
Source:
private long getBestTime() { if (mNtpServer != null) { long ntpAge = SystemClock.elapsedRealtime() - cachedNtpTimestamp; if (mNtpActive) { if (ntpAge < (mMaxNtpCacheAgeSec - 3 * mPolicyPollPeriodSec) * 1000) { if (VDBG) Slog.v(TAG, "using cached time"); return cachedNtp + ntpAge; } } synchronized (mNtpRequestPendingGuard) { if (!mNtpRequestPending) { mNtpRequestPending = true; new Thread() { @Override public void run() { SntpClient client = new SntpClient(); if (client.requestTime(mNtpServer, MAX_NTP_FETCH_WAIT)) { cachedNtp = client.getNtpTime(); cachedNtpTimestamp = SystemClock.elapsedRealtime(); if (!mNtpActive) { mNtpActive = true; if (VDBG) Slog.d(TAG, "found Authoritative time - reseting alarm"); mHandler.obtainMessage(EVENT_RESET_ALARM).sendToTarget(); } } synchronized (mNtpRequestPendingGuard) { mNtpRequestPending = false; } } }.start(); } } if (mNtpActive) { if (ntpAge < mMaxNtpCacheAgeSec * 1000) { if (VDBG) Slog.v(TAG, "using cached time"); return cachedNtp + ntpAge; } } } long time = System.currentTimeMillis(); if (VDBG) Slog.v(TAG, "using User time: " + time); mNtpActive = false; return time; }

Target:
private long getBestTime() { if (mNtpServer != null) { long ntpAge = SystemClock.elapsedRealtime() - cachedNtpTimestamp; if (mNtpActive && ntpAge < (mMaxNtpCacheAgeSec - 3 * mPolicyPollPeriodSec) * 1000) { if (VDBG) Slog.v(TAG, "using cached time"); return cachedNtp + ntpAge; } mHandler.obtainMessage(EVENT_NTP_ALARM).sendToTarget(); if (mNtpActive && ntpAge < mMaxNtpCacheAgeSec * 1000) { if (VDBG) Slog.v(TAG, "using cached time"); return cachedNtp + ntpAge; } } long time = System.currentTimeMillis(); if (VDBG) Slog.v(TAG, "using User time: " + time); return time; }
Source:
protected String findContractControlAccountNumber(List<InvoiceAccountDetail> details) { for (InvoiceAccountDetail detail : details) { if (StringUtils.isNotBlank(detail.getContractControlAccountNumber())) { return detail.getContractControlAccountNumber(); } } LOG.error("findConntractControllAccountNumber, could not find contract controll account number"); return StringUtils.EMPTY; }

Target:
protected String findContractControlAccountNumber(List<InvoiceAccountDetail> details) { for (InvoiceAccountDetail detail : details) { if (StringUtils.isNotBlank(detail.getContractControlAccountNumber())) { return detail.getContractControlAccountNumber(); } } LOG.error("findContractControlAccountNumber, could not find contract control account number"); return StringUtils.EMPTY; }
Source:
public void processMessage(final ObjectMessage message) { LOGGER.debug("Processing public lighting set light measurement device request message"); String correlationUid = null; String messageType = null; String organisationIdentification = null; String deviceIdentification = null; Object dataObject = null; try { correlationUid = message.getJMSCorrelationID(); messageType = message.getJMSType(); organisationIdentification = message.getStringProperty(Constants.ORGANISATION_IDENTIFICATION); deviceIdentification = message.getStringProperty(Constants.DEVICE_IDENTIFICATION); dataObject = message.getObject(); } catch (final JMSException e) { LOGGER.error("UNRECOVERABLE ERROR, unable to read ObjectMessage instance, giving up.", e); LOGGER.debug("correlationUid: {}", correlationUid); LOGGER.debug("messageType: {}", messageType); LOGGER.debug("organisationIdentification: {}", organisationIdentification); LOGGER.debug("deviceIdentification: {}", deviceIdentification); return; } try { LOGGER.info("Calling application service function: {}", messageType); this.adHocManagementService.coulpeLightMeasurementDeviceForSsld(organisationIdentification, deviceIdentification, correlationUid, (String) dataObject, messageType); } catch (final Exception e) { this.handleError(e, correlationUid, organisationIdentification, deviceIdentification, messageType); } }

Target:
public void processMessage(final ObjectMessage message) { LOGGER.debug("Processing public lighting set light measurement device request message"); String correlationUid = null; String messageType = null; String organisationIdentification = null; String deviceIdentification = null; Object dataObject = null; try { correlationUid = message.getJMSCorrelationID(); messageType = message.getJMSType(); organisationIdentification = message.getStringProperty(Constants.ORGANISATION_IDENTIFICATION); deviceIdentification = message.getStringProperty(Constants.DEVICE_IDENTIFICATION); dataObject = message.getObject(); } catch (final JMSException e) { LOGGER.error("UNRECOVERABLE ERROR, unable to read ObjectMessage instance, giving up.", e); LOGGER.debug("correlationUid: {}", correlationUid); LOGGER.debug("messageType: {}", messageType); LOGGER.debug("organisationIdentification: {}", organisationIdentification); LOGGER.debug("deviceIdentification: {}", deviceIdentification); return; } try { LOGGER.info("Calling application service function: {}", messageType); this.adHocManagementService.coupleLightMeasurementDeviceForSsld(organisationIdentification, deviceIdentification, correlationUid, (String) dataObject, messageType); } catch (final Exception e) { this.handleError(e, correlationUid, organisationIdentification, deviceIdentification, messageType); } }
Source:
public static void main(String[] args) { MongoConnectionPropertiesLoader.load(); Injector injector = Guice.createInjector(new LotteryModule()); com.iluwatar.hexagonal.domain.LotteryService service = injector.getInstance( com.iluwatar.hexagonal.domain.LotteryService.class); WireTransfers bank = injector.getInstance(WireTransfers.class); try (final Scanner scanner = new Scanner(System.in)) { boolean exit = false; while (!exit) { printMainMenu(); String cmd = readString(scanner); LotteryService lotteryService = new LotteryServiceImpl(LOGGER); if ("1".equals(cmd)) { lotteryService.queryLotteryAccountFunds(bank, scanner); } else if ("2".equals(cmd)) { lotteryService.addFundsToLotteryAccount(bank, scanner); } else if ("3".equals(cmd)) { lotteryService.submitTicket(service, scanner); } else if ("4".equals(cmd)) { lotteryService.checkTicket(service, scanner); } else if ("5".equals(cmd)) { exit = true; } else { LOGGER.info("Unknown command"); } } } }

Target:
public static void main(String[] args) { MongoConnectionPropertiesLoader.load(); Injector injector = Guice.createInjector(new LotteryModule()); LotteryService service = injector.getInstance( LotteryService.class); WireTransfers bank = injector.getInstance(WireTransfers.class); try (final Scanner scanner = new Scanner(System.in)) { boolean exit = false; while (!exit) { printMainMenu(); String cmd = readString(scanner); LotteryConsoleService lotteryConsoleService = new LotteryConsoleServiceImpl(LOGGER); if ("1".equals(cmd)) { lotteryConsoleService.queryLotteryAccountFunds(bank, scanner); } else if ("2".equals(cmd)) { lotteryConsoleService.addFundsToLotteryAccount(bank, scanner); } else if ("3".equals(cmd)) { lotteryConsoleService.submitTicket(service, scanner); } else if ("4".equals(cmd)) { lotteryConsoleService.checkTicket(service, scanner); } else if ("5".equals(cmd)) { exit = true; } else { LOGGER.info("Unknown command"); } } } }
Source:
public void update(CruiseConfig preprocessedConfig) throws Exception { PackageRepository oldRepo = preprocessedConfig.getPackageRepositories().find(oldRepoId); this.newRepo.setPackages(oldRepo.getPackages()); this.newRepo.setPluginConfiguration(getPluginCofiguration(this.newRepo)); PackageRepositories repositories = preprocessedConfig.getPackageRepositories(); repositories.removePackageRepository(oldRepo.getId()); repositories.add(this.newRepo); preprocessedConfig.setPackageRepositories(repositories); }

Target:
public void update(CruiseConfig preprocessedConfig) throws Exception { PackageRepository oldRepo = preprocessedConfig.getPackageRepositories().find(newRepo.getRepoId()); this.newRepo.setPackages(oldRepo.getPackages()); PackageRepositories repositories = preprocessedConfig.getPackageRepositories(); repositories.removePackageRepository(oldRepo.getId()); repositories.add(this.newRepo); preprocessedConfig.setPackageRepositories(repositories); }
Source:
private void savePlaybackState(final StreamInfo info, final long progress) { if (info == null) return; Log.d(TAG, "savePlaybackState() called"); final Disposable stateSaver = recordManager.saveStreamState(info, progress) .observeOn(AndroidSchedulers.mainThread()) .onErrorComplete() .subscribe( ignored -> { }, error -> Log.e(TAG, "savePlaybackState() failure: ", error) ); databaseUpdateReactor.add(stateSaver); }

Target:
private void savePlaybackState(final StreamInfo info, final long progress) { if (info == null) return; if (DEBUG) Log.d(TAG, "savePlaybackState() called"); final Disposable stateSaver = recordManager.saveStreamState(info, progress) .observeOn(AndroidSchedulers.mainThread()) .onErrorComplete() .subscribe( ignored -> { }, error -> { if (DEBUG) Log.e(TAG, "savePlaybackState() failure: ", error); } ); databaseUpdateReactor.add(stateSaver); }
Source:
public void addCurrentCampaign(List<Campaign> objects) { hubList.add(1, "currently doing"); hubList.addAll(2, objects); notifyItemRangeInserted(hubList.size() - objects.size(), hubList.size() - 1); }

Target:
public void addCurrentCampaign(List<Campaign> objects) { int i = hubList.indexOf(BEEN_THERE_DONE_GOOD); hubList.addAll(i, objects); notifyItemRangeInserted(hubList.size() - objects.size(), hubList.size() - 1); }
Source:
public String toString() { return "DataProfile=" + mProfileId + "/" + mProtocol + "/" + mAuthType + "/" + ("user".equals(Build.TYPE) ? "*** ***": (mApn + "/" + mUserName + "/" + mPassword)) + "/" + mType + "/" + mMaxConnsTime + "/" + mMaxConns + "/" + mWaitTime + "/" + mEnabled + "/" + mSupportedApnTypesBitmap + "/" + mRoamingProtocol + "/" + mBearerBitmap + "/" + mMtu + "/" + mMvnoType + "/" + mMvnoMatchData + "/" + mModemCognitive; }

Target:
public String toString() { return "DataProfile=" + mProfileId + "/" + mProtocol + "/" + mAuthType + "/" + (Build.IS_USER? "*** ***": (mApn + "/" + mUserName + "/" + mPassword)) + "/" + mType + "/" + mMaxConnsTime + "/" + mMaxConns + "/" + mWaitTime + "/" + mEnabled + "/" + mSupportedApnTypesBitmap + "/" + mRoamingProtocol + "/" + mBearerBitmap + "/" + mMtu + "/" + mMvnoType + "/" + mMvnoMatchData + "/" + mModemCognitive; }
Source:
private CosmosClientException extractCosmosClientExceptionIfAny(Throwable t) { if (t == null) { return null; } if (t instanceof CosmosClientException) { return (CosmosClientException) t; } return extractCosmosClientExceptionIfAny(t.getCause()); }

Target:
private CosmosClientException extractCosmosClientExceptionIfAny(Throwable t) { if (t == null) { return null; } while(!(t instanceof CosmosClientException)) { t = t.getCause(); } return (CosmosClientException) t; }
Source:
public void testUpdatePreserveOwner() throws Exception { ShareableMetacardPreIngestPlugin wpip = makePlugin(ImmutableMap.of()); ShareableMetacardImpl prev = new ShareableMetacardImpl("id"); ShareableMetacardImpl next = ShareableMetacardImpl.clone(prev); prev.setOwner("prev"); assertThat(next.getOwner(), nullValue()); wpip.process(updateRequest(prev, next)); assertThat(next.getOwner(), is(prev.getOwner())); }

Target:
public void testUpdatePreserveOwner() throws Exception { ShareableMetacardPreIngestPlugin plugin = makePlugin(); ShareableMetacardImpl prev = new ShareableMetacardImpl("id"); ShareableMetacardImpl next = ShareableMetacardImpl.clone(prev); prev.setTags(Collections.singleton(WorkspaceAttributes.WORKSPACE_TAG)); next.setTags(Collections.singleton(WorkspaceAttributes.WORKSPACE_TAG)); prev.setOwner("prev"); assertThat(next.getOwner(), nullValue()); plugin.process(updateRequest(prev, next)); assertThat(next.getOwner(), is(prev.getOwner())); }
Source:
public void testWithChannel_duplicates() { ThingBuilder thingBuilder = ThingBuilder.create(THING_TYPE_UID, THING_UID); thingBuilder.withChannel(new Channel(new ChannelUID(THING_UID, "channel1"), "")); thingBuilder.withChannel(new Channel(new ChannelUID(THING_UID, "channel1"), "")); }

Target:
public void testWithChannel_duplicates() { ThingBuilder thingBuilder = ThingBuilder.create(THING_TYPE_UID, THING_UID); thingBuilder.withChannel(ChannelBuilder.create(new ChannelUID(THING_UID, "channel1"), "").build()); thingBuilder.withChannel(ChannelBuilder.create(new ChannelUID(THING_UID, "channel1"), "").build()); }
Source:
private boolean isValidProcessProperty() { if (this.processProperty.isValid()) { return true; } else { List<String> param = new ArrayList<String>(); param.add(processProperty.getName()); String value = Helper.getTranslation("propertyNotValid", param); Helper.setFehlerMeldung(value); Helper.setFehlerMeldung("Property " + this.processProperty.getName() + " is not valid"); return false; } }

Target:
private boolean isValidProcessProperty() { if (this.processProperty.isValid()) { return true; } else { String value = Helper.getTranslation("propertyNotValid", Arrays.asList(new String[] {processProperty.getName() })); Helper.setFehlerMeldung(value); Helper.setFehlerMeldung("Property " + this.processProperty.getName() + " is not valid"); return false; } }
Source:
@Override public UnderFileSystem create(String path, UnderFileSystemConfiguration conf) { Preconditions.checkNotNull(path, "path is null"); if (checkB2Credentials(conf)) { try { return B2UnderFileSystem.createInstance(new AlluxioURI(path), conf); } catch (ServiceException e) { throw new RuntimeException(e); } } String err = "B2 Credentials not available, cannot create B2 Under File System."; throw new RuntimeException(new IOException(err)); }

Target:
public UnderFileSystem create(String path, UnderFileSystemConfiguration conf) { Preconditions.checkNotNull(path, "path is null"); checkB2Credentials(conf); try { return B2UnderFileSystem.createInstance(new AlluxioURI(path), conf); } catch (ServiceException e) { throw new RuntimeException(e); } }
Source:
public void testGetSecret() throws IOException { respondWith(SECRET_JSON); Secret secret = osv3().barbican().secrets().get(secretId); assertNotNull(secret); assertNotNull(secret.getName()); assertEquals(secret.getExpiration().toString(), expiration); assertTrue(!secret.getContentTypes().isEmpty()); assertEquals(secret.getContentTypes().get("default"), content_type); }

Target:
public void testGetSecret() throws IOException { respondWith(SECRET_JSON); Secret secret = osv3().barbican().secrets().get(secretId); assertNotNull(secret); assertNotNull(secret.getName()); assertEquals(secret.getExpiration(), expiration); assertTrue(!secret.getContentTypes().isEmpty()); assertEquals(secret.getContentTypes().get("default"), content_type); }
Source:
public ComparableJsonNode(JsonNode delegate) { this.delegate = delegate; }

Target:
ComparableJsonNode(JsonNode delegate) { this.delegate = delegate; }
Source:
public byte[] toBytes() { byte[] offsetBytes = offset != null ? offset.toBytes() : ZERO_LENGTH_ARRAY; byte[] sessionIdBytes = sessionId != null ? sessionId.toString().getBytes() : ZERO_LENGTH_ARRAY; byte[] incarnationIdBytes = incarnationId != null ? incarnationId.toString().getBytes() : ZERO_LENGTH_ARRAY; byte[] storeKeyBytes = storeKey != null ? storeKey.toBytes() : ZERO_LENGTH_ARRAY; int size = VERSION_SIZE + TYPE_SIZE + INCARNATION_ID_LENGTH_SIZE + incarnationIdBytes.length + SESSION_ID_LENGTH_SIZE + sessionIdBytes.length + offsetBytes.length + storeKeyBytes.length + INCLUSIVE_BYTE_SIZE; byte[] buf = new byte[size]; ByteBuffer bufWrap = ByteBuffer.wrap(buf); bufWrap.putShort(VERSION_2); bufWrap.putShort((short) type.ordinal()); bufWrap.putInt(incarnationIdBytes.length); bufWrap.put(incarnationIdBytes); bufWrap.putInt(sessionIdBytes.length); bufWrap.put(sessionIdBytes); bufWrap.put(offsetBytes); bufWrap.put(storeKeyBytes); bufWrap.put(getInclusive() ? (byte) 1 : (byte) 0); return buf; }

Target:
public byte[] toBytes() { byte[] offsetBytes = offset != null ? offset.toBytes() : ZERO_LENGTH_ARRAY; byte[] sessionIdBytes = sessionId != null ? sessionId.toString().getBytes() : ZERO_LENGTH_ARRAY; byte[] incarnationIdBytes = incarnationId != null ? incarnationId.toString().getBytes() : ZERO_LENGTH_ARRAY; byte[] storeKeyBytes = storeKey != null ? storeKey.toBytes() : ZERO_LENGTH_ARRAY; int size = VERSION_SIZE + TYPE_SIZE; if (type != Type.Uninitialized) { size += INCARNATION_ID_LENGTH_SIZE + incarnationIdBytes.length + SESSION_ID_LENGTH_SIZE + sessionIdBytes.length + offsetBytes.length; if (type == Type.JournalBased) { size += INCLUSIVE_BYTE_SIZE; } else if (type == Type.IndexBased) { size += storeKeyBytes.length; } } byte[] buf = new byte[size]; ByteBuffer bufWrap = ByteBuffer.wrap(buf); bufWrap.putShort(VERSION_2); bufWrap.putShort((short) type.ordinal()); if (type != Type.Uninitialized) { bufWrap.putInt(incarnationIdBytes.length); bufWrap.put(incarnationIdBytes); bufWrap.putInt(sessionIdBytes.length); bufWrap.put(sessionIdBytes); bufWrap.put(offsetBytes); if (type == Type.JournalBased) { bufWrap.put(getInclusive() ? (byte) 1 : (byte) 0); } else if (type == Type.IndexBased) { bufWrap.put(storeKeyBytes); } } return buf; }
Source:
public String getPeerUserAgent() { Set<String> clientCapabilities = currentRequest == null ? null : currentRequest.getClientCapabilities(); if (currentRequest == null) { return userAgent; } return UserAgent.getAgent(clientCapabilities, userAgent); }

Target:
public String getPeerUserAgent() { if (currentRequest == null) { return userAgent; } return UserAgent.getAgent(currentRequest.getClientCapabilities(), userAgent); }
Source:
public UUID traceRequestCreate(@Nonnull TraceRequest traceRequest) throws StateAccessException, SerializationException { if (traceRequest.getId() == null) { traceRequest.setId(UUID.randomUUID()); } switch (traceRequest.getDeviceType()) { case ROUTER: if (routersGet(traceRequest.getDeviceId()) == null) { throw new StateAccessException( "Router " + traceRequest.getDeviceId() + " does not exist"); } break; case BRIDGE: if (bridgesGet(traceRequest.getDeviceId()) == null) { throw new StateAccessException( "Bridge " + traceRequest.getDeviceId() + " does not exist"); } break; case PORT: if (portsGet(traceRequest.getDeviceId()) == null) { throw new StateAccessException( "Port " + traceRequest.getDeviceId() + " does not exist"); } } UUID id = traceRequest.getId(); TraceRequestZkManager.TraceRequestConfig config = Converter.toTraceRequestConfig(traceRequest); zkManager.multi(traceReqZkManager.prepareCreate(id, config)); return id; }

Target:
public UUID traceRequestCreate(@Nonnull TraceRequest traceRequest) throws StateAccessException, SerializationException { if (traceRequest.getId() == null) { traceRequest.setId(UUID.randomUUID()); } if (!checkTraceRequestDeviceExists(traceRequest)) { throw new StateAccessException( "Device " + traceRequest.getDeviceId() + " of type " + traceRequest.getDeviceType() + " does not exist"); } UUID id = traceRequest.getId(); TraceRequestZkManager.TraceRequestConfig config = Converter.toTraceRequestConfig(traceRequest); zkManager.multi(traceReqZkManager.prepareCreate(id, config)); if (!checkTraceRequestDeviceExists(traceRequest)) { traceRequestDelete(traceRequest.getId()); throw new StateAccessException( "Device " + traceRequest.getDeviceId() + " deleted"); } return id; }
Source:
public void logoutWipe() { List<Survey> surveys = Survey.getAllSurveys(); for (Survey survey : surveys) { survey.delete(); } ICredentialsRepository credentialsLocalDataSource = new CredentialsLocalDataSource(); credentialsLocalDataSource.saveOrganisationCredentials(null); }

Target:
public void logoutWipe() { List<Survey> surveys = Survey.getAllSurveys(); for (Survey survey : surveys) { survey.delete(); } }
Source:
private String token(final String home, final String code) throws IOException { final String uri = new Href( String.format( "%s/login/oauth/access_token", this.getUrl("<LINK_0>") ) ).with("client_id", this.app) .with("redirect_uri", home) .with("client_secret", this.key) .with("code", code) .toString(); return new JdkRequest(uri) .method("POST") .header("Accept", "application/xml") .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .xml().xpath("/OAuth/access_token/text()").get(0); }

Target:
private String token(final String home, final String code) throws IOException { final String uri = new Href(this.github) .path("login/oauth/access_token") .toString(); return new JdkRequest(uri) .method("POST") .header("Accept", "application/xml") .body() .formParam("client_id", this.app) .formParam("redirect_uri", home) .formParam("client_secret", this.key) .formParam("code", code) .back() .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .xml().xpath("/OAuth/access_token/text()").get(0); }
Source:
static Stream<String> moduleDirectoryNames() throws IOException { String startOfModuleLine = "include '"; return Files.readAllLines(Paths.get("../settings.gradle")).stream() .filter(line -> line.startsWith(startOfModuleLine)) .map(line -> line.substring(startOfModuleLine.length(), line.length() - 1)) .filter(name -> !name.equals("junit-platform-console-standalone")) .filter(name -> name.startsWith("junit-")); }

Target:
static Stream<String> moduleDirectoryNames() throws IOException { String startOfModuleLine = "include '"; return Files.lines(Paths.get("../settings.gradle")) .filter(line -> line.startsWith(startOfModuleLine)) .map(line -> line.substring(startOfModuleLine.length(), line.length() - 1)) .filter(name -> !name.equals("junit-platform-console-standalone")) .filter(name -> name.startsWith("junit-")); }
Source:
public long getTLSCertFilesRefreshDurationSeconds() { return getLong(TLS_CERT_FILES_REFRESH_DURATION_SECONDS, 300); }

Target:
public long getTLSCertFilesRefreshDurationSeconds() { return getLong(TLS_CERT_FILES_REFRESH_DURATION_SECONDS, 0); }
Source:
public void testControlBulkOperationsEnabled() { ListTable extendedPagedTable = mock(ListTable.class); HasWidgets rightActionsToolbar = mock(HasWidgets.class); boolean enabled = false; final Button mockButton = GWT.create(Button.class); ArrayList a = new ArrayList(); a.add(mockButton); when(rightActionsToolbar.spliterator()) .thenReturn(Spliterators.spliteratorUnknownSize(a.iterator(), 0)); when(extendedPagedTable.getRightActionsToolbar()).thenReturn(rightActionsToolbar); when(extendedPagedTable.hasSelectedItems()).thenReturn(enabled); getView().controlBulkOperations(extendedPagedTable); verify(mockButton).setEnabled(enabled); }

Target:
public void testControlBulkOperationsEnabled() { when(extendedPagedTable.hasSelectedItems()).thenReturn(true); getView().controlBulkOperations(extendedPagedTable); verify(mockButton).setEnabled(true); }