auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static boolean hasMatrixParam(List<PathSegment> pathSegments, String param) { if (pathSegments != null) for (PathSegment segement : pathSegments) { MultivaluedMap<String, String> matrixParams = segement.getMatrixParameters(); if (matrixParams != null && !matrixParams.isEmpty()) for (String key : matrixParams.keySet()) { if (key.equals(param)) return true; } } return false; }

Target:
private static boolean hasMatrixParam(List<PathSegment> pathSegments, String param) { if (pathSegments != null) for (PathSegment segement : pathSegments) { MultivaluedMap<String, String> matrixParams = segement.getMatrixParameters(); if (matrixParams != null && !matrixParams.isEmpty() && matrixParams.containsKey(param)) return true; } return false; }
Source:
protected synchronized void injectSizzle() { if (sizzleSource == null) { try { sizzleSource = IOUtils.toString(currentThread().getContextClassLoader().getResource("sizzle.js"), Charset.defaultCharset()); } catch (IOException e) { throw new RuntimeException("Cannot load sizzle.js from classpath", e); } } executeJavaScript(sizzleSource); }

Target:
protected synchronized void injectSizzle() { if (sizzleSource == null) { try { sizzleSource = IOUtils.toString(currentThread().getContextClassLoader().getResource("sizzle.js"), StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException("Cannot load sizzle.js from classpath", e); } } executeJavaScript(sizzleSource); }
Source:
public void loadLocations(final String url) { loginView.showLocationLoadingAnimation(); if (NetworkUtils.hasNetwork()) { String locationEndPoint = url + ApplicationConstants.API.REST_ENDPOINT + "location"; RestApi restApi = RestServiceBuilder.createService(RestApi.class); Call<Results<Location>> call = restApi.getLocations(locationEndPoint, "Login Location", "full"); call.enqueue(new Callback<Results<Location>>() { @Override public void onResponse(Call<Results<Location>> call, Response<Results<Location>> response) { if (response.isSuccessful()) { RestServiceBuilder.changeBaseUrl(url.trim()); mOpenMRS.setServerUrl(url); mOpenMRS.setLocations(response.body().getResults()); loginView.initLoginForm(response.body().getResults(), url); loginView.startFormListService(); loginView.setLocationErrorOccurred(false); } else { loginView.showInvalidURLSnackbar("Failed to fetch server's locations"); loginView.setLocationErrorOccurred(true); } loginView.hideUrlLoadingAnimation(); } @Override public void onFailure(Call<Results<Location>> call, Throwable t) { loginView.hideUrlLoadingAnimation(); loginView.showInvalidURLSnackbar(t.getMessage()); loginView.setLocationErrorOccurred(true); } }); } else { List<Location> locations = mOpenMRS.getLocations(); if (locations != null) { loginView.initLoginForm(locations, url); loginView.setLocationErrorOccurred(false); } else { ToastUtil.error("Network not available."); loginView.setLocationErrorOccurred(true); } loginView.hideLoadingAnimation(); } }

Target:
public void loadLocations(final String url) { loginView.showLocationLoadingAnimation(); if (NetworkUtils.hasNetwork()) { String locationEndPoint = url + ApplicationConstants.API.REST_ENDPOINT + "location"; RestApi restApi = RestServiceBuilder.createService(RestApi.class); Call<Results<Location>> call = restApi.getLocations(locationEndPoint, "Login Location", "full"); call.enqueue(new Callback<Results<Location>>() { @Override public void onResponse(Call<Results<Location>> call, Response<Results<Location>> response) { if (response.isSuccessful()) { RestServiceBuilder.changeBaseUrl(url.trim()); mOpenMRS.setServerUrl(url); loginView.initLoginForm(response.body().getResults(), url); loginView.startFormListService(); loginView.setLocationErrorOccurred(false); } else { loginView.showInvalidURLSnackbar("Failed to fetch server's locations"); loginView.setLocationErrorOccurred(true); loginView.initLoginForm(new ArrayList<Location>(), url); } loginView.hideUrlLoadingAnimation(); } @Override public void onFailure(Call<Results<Location>> call, Throwable t) { loginView.hideUrlLoadingAnimation(); loginView.showInvalidURLSnackbar(t.getMessage()); loginView.setLocationErrorOccurred(true); } }); } else { List<Location> locations = LocationDAO.getLocations(); if (locations.size() > 0) { loginView.initLoginForm(locations, url); loginView.setLocationErrorOccurred(false); } else { loginView.showToast("Network not available.", ToastUtil.ToastType.ERROR); loginView.setLocationErrorOccurred(true); } loginView.hideLoadingAnimation(); } }
Source:
public void testNonexistentLocalCommandExitStatus() throws Exception { ThreadProperty.set("class", this.getClass().getCanonicalName()); CommonG commong = new CommonG(); String command = "shur"; commong.runLocalCommand(command); int exitstatus = commong.getCommandExitStatus(); assertThat(exitstatus).as("Running command echo locally").isEqualTo(1); }

Target:
public void testNonexistentLocalCommandExitStatus() throws Exception { ThreadProperty.set("class", this.getClass().getCanonicalName()); CommonG commong = new CommonG(); String command = "shur"; commong.runLocalCommand(command); int exitstatus = commong.getCommandExitStatus(); assertThat(exitstatus).as("Running nonexistent command 'shur' locally").isEqualTo(1); }
Source:
public static boolean isEmbedded(String driverClass, String url) { return (driverClass != null && (matches(HSQL, driverClass) || ( matches(H2, driverClass) && !StringUtils.hasText("mem")) || matches(DERBY, driverClass) || matches(HSQLDB, driverClass))); }

Target:
public static boolean isEmbedded(String driverClass, String url) { return (driverClass != null && (matches(HSQL, driverClass) || (matches(H2, driverClass) && url.contains(":h2:mem")) || matches(DERBY, driverClass) || matches(HSQLDB, driverClass))); }
Source:
public void tccReceived(RTCPTCCPacket pkt) { PacketDetail retrievedPacketDetail; for (int receivedSequenceNo: pkt.getPackets().keySet()) { retrievedPacketDetail = outgoingPacketFields .get(receivedSequenceNo); if (retrievedPacketDetail != null) { long _bitrate = bitrateEstimator .rtcpTCCRemoteBitrateEstimator((int) pkt.getSourceSSRC(), retrievedPacketDetail.pktTime, pkt.getPackets().get(receivedSequenceNo), retrievedPacketDetail.pktLength); pkt.getPackets().remove(receivedSequenceNo); } } }

Target:
public void tccReceived(RTCPTCCPacket pkt) { PacketDetail retrievedPacketDetail; for (int receivedSequenceNo: pkt.getPackets().keySet()) { if (outgoingPacketFields.containsKey(receivedSequenceNo)){ retrievedPacketDetail = outgoingPacketFields .get(receivedSequenceNo); if (retrievedPacketDetail != null) { long _bitrate = bitrateEstimator .rtcpTCCRemoteBitrateEstimator( (int) pkt.getSourceSSRC(), retrievedPacketDetail.pktTime, pkt.getPackets().get(receivedSequenceNo), retrievedPacketDetail.pktLength); outgoingPacketFields.remove(receivedSequenceNo); } } } }
Source:
public synchronized void putAll(List<Entry<K, V>> entries) { Preconditions.checkNotNull(rwTable, "Cannot write to a read-only table: " + rdTable); entries.forEach(e -> { this.rwTable.put(e.getKey(), e.getValue()); this.cache.put(e.getKey(), e.getValue()); }); }

Target:
public void putAll(List<Entry<K, V>> entries) { Preconditions.checkNotNull(rwTable, "Cannot write to a read-only table: " + rdTable); entries.forEach(e -> put(e.getKey(), e.getValue())); }
Source:
public MockBoundedByteBufferReceive send(Send send) throws IOException { RequestOrResponseType type = ((RequestOrResponse) send).getRequestType(); switch (type) { case PutRequest: PutRequest putRequest = (PutRequest) send; final ServerErrorCode putError = hardError != null ? hardError : putErrors.size() > 0 ? putErrors.poll() : ServerErrorCode.No_Error; if (putError == ServerErrorCode.No_Error) { updateBlobMap(putRequest); } return new MockBoundedByteBufferReceive( new PutResponse(putRequest.getCorrelationId(), putRequest.getClientId(), putError) { ByteBuffer getPayload() { ByteBuffer buf; buf = ByteBuffer.allocate(2 + 2 + 4 + 4 + 2); buf.putShort((short) RequestOrResponseType.PutResponse.ordinal()); buf.putShort(versionId); buf.putInt(correlationId); buf.putInt(0); buf.putShort((short) putError.ordinal()); buf.flip(); return buf; } }.getPayload()); default: throw new IOException("Unknown request type received"); } }

Target:
public MockBoundedByteBufferReceive send(Send send) throws IOException { RequestOrResponseType type = ((RequestOrResponse) send).getRequestType(); switch (type) { case PutRequest: PutRequest putRequest = (PutRequest) send; final ServerErrorCode putError = hardError != null ? hardError : putErrors.size() > 0 ? putErrors.poll() : ServerErrorCode.No_Error; if (putError == ServerErrorCode.No_Error) { updateBlobMap(putRequest); } return new MockBoundedByteBufferReceive( new PutResponse(putRequest.getCorrelationId(), putRequest.getClientId(), putError) { ByteBuffer getPayload() throws IOException { ByteArrayOutputStream bStream = new ByteArrayOutputStream(); DataOutputStream dStream = new DataOutputStream(bStream); dStream.writeShort((short) RequestOrResponseType.PutResponse.ordinal()); dStream.writeShort(versionId); dStream.writeInt(correlationId); dStream.writeInt(0); dStream.writeShort((short) putError.ordinal()); return ByteBuffer.wrap(bStream.toByteArray()); } }.getPayload()); default: throw new IOException("Unknown request type received"); } }
Source:
public static Tuple testTuple(List<Object> values, MkTupleParam param) { String stream = param.getStream(); if (stream == null) { stream = Utils.DEFAULT_STREAM_ID; } String component = param.getComponent(); if (component == null) { component = "component"; } int task = 1; List<String> fields = param.getFields(); if (fields == null) { fields = new ArrayList<>(values.size()); for (int i = 1; i <= values.size(); i++) { fields.add("field"+i); } } Map<Integer, String> taskToComp = new HashMap<>(); taskToComp.put(task, component); Map<String, Map<String, Fields>> compToStreamToFields = new HashMap<>(); Map<String, Fields> streamToFields = new HashMap<>(); streamToFields.put(stream, new Fields(fields)); compToStreamToFields.put(component, streamToFields); TopologyContext context= new TopologyContext(null, ConfigUtils.readStormConfig(), taskToComp, null, compToStreamToFields, null, "test-storm-id", null, null, 1, null, null, new HashMap<>(), new HashMap<>(), new HashMap<>(), new HashMap<>(), new AtomicBoolean(false)); return new TupleImpl(context, values, "component", 1, stream); }

Target:
public static Tuple testTuple(List<Object> values, MkTupleParam param) { String stream = param.getStream(); if (stream == null) { stream = Utils.DEFAULT_STREAM_ID; } String component = param.getComponent(); if (component == null) { component = "component"; } int task = 1; List<String> fields = param.getFields(); if (fields == null) { fields = new ArrayList<>(values.size()); for (int i = 1; i <= values.size(); i++) { fields.add("field"+i); } } Map<Integer, String> taskToComp = new HashMap<>(); taskToComp.put(task, component); Map<String, Map<String, Fields>> compToStreamToFields = new HashMap<>(); Map<String, Fields> streamToFields = new HashMap<>(); streamToFields.put(stream, new Fields(fields)); compToStreamToFields.put(component, streamToFields); TopologyContext context= new TopologyContext(null, ConfigUtils.readStormConfig(), taskToComp, null, compToStreamToFields, null, "test-storm-id", null, null, 1, null, null, new HashMap<>(), new HashMap<>(), new HashMap<>(), new HashMap<>(), new AtomicBoolean(false)); return new TupleImpl(context, values, component, 1, stream); }
Source:
public String getServerAddressByPort(String workspaceId, int port) throws Exception { Workspace workspace = getById(workspaceId); ensureRunningStatus(workspace); return getById(workspaceId) .getRuntime() .getMachines() .get(0) .getServers() .get(valueOf(port) + "/tcp") .getUrl(); .getRuntime() .getServers() .get(valueOf(port) + "/tcp") .getAddress(); }

Target:
public String getServerAddressByPort(String workspaceId, int port) throws Exception { Workspace workspace = getById(workspaceId); ensureRunningStatus(workspace); Map<String, ? extends Machine> machines = workspace.getRuntime().getMachines(); for (Machine machine : machines.values()) { if (containsWsAgentServer(machine)) { return machine.getServers().get(valueOf(port) + "/tcp").getUrl(); } } return null; }
Source:
private static void setDosingType(DrugOrder drugOrder, MedicationRequest fhirMedicationRequest) { List<Extension> extensions = fhirMedicationRequest.getExtensionsByUrl(ExtensionURL.DOSING_TYPE); if (extensions.size() > 0) { ContextUtil.getDrugOrderHelper().setDosingType(drugOrder, ExtensionsUtil.getStringFromExtension(extensions.get(FIRST))); } }

Target:
private static void setDosingType(DrugOrder drugOrder, MedicationRequest fhirMedicationRequest) { List<Extension> extensions = fhirMedicationRequest.getExtensionsByUrl(ExtensionURL.DOSING_TYPE); if (!CollectionUtils.isEmpty(extensions)) { ContextUtil.getDrugOrderHelper().setDosingType(drugOrder, ExtensionsUtil.getStringFromExtension(extensions.get(FIRST))); } }
Source:
Map getNetworkStatsMap(VM vm) { List<Device> nicDevices = vm.getDevicesByType(Device.DeviceType.NIC); String macAddress = vm.getMacAddress(); if( macAddress.equals(VM.NONE_STRING) ) { log.debug("no mac address for vm {}", vm.getId()); return map(); } Map resultMap = map(); int count = 0; for(Device device : nicDevices) { Map netStats = map(); String dName = "vnet" + count; netStats.put("txErrors", "0"); netStats.put("state", "unknown"); netStats.put("macAddr", device.getMacAddr()); netStats.put("name", dName); netStats.put("txDropped", "0"); netStats.put("txRate", Utils.rangeParser(AppConfig.getInstance().getNetworkLoad())); netStats.put("rxErrors", "0"); netStats.put("rxRate", Utils.rangeParser(AppConfig.getInstance().getNetworkLoad())); netStats.put("tx", Utils.rangeParser(AppConfig.getInstance().getNetworkLoad())); netStats.put("rx", Utils.rangeParser(AppConfig.getInstance().getNetworkLoad())); netStats.put("rxDropped", "0"); netStats.put("speed", "1000"); netStats.put("sampleTime", "4318787.08"); resultMap.put(dName, netStats); ++count; } return resultMap; }

Target:
Map getNetworkStatsMap(VM vm) { List<Device> nicDevices = vm.getDevicesByType(Device.DeviceType.NIC); String macAddress = vm.getMacAddress(); if( macAddress.equals(VM.NONE_STRING) ) { log.debug("no mac address for vm {}", vm.getId()); return map(); } List<String> networkLoad = AppConfig.getInstance().getNetworkLoad(); Map resultMap = map(); int count = 0; for(Device device : nicDevices) { Map netStats = map(); String dName = "vnet" + count; netStats.put("txErrors", "0"); netStats.put("state", "unknown"); netStats.put("macAddr", device.getMacAddr()); netStats.put("name", dName); netStats.put("txDropped", "0"); netStats.put("txRate", Utils.rangeParser(networkLoad)); netStats.put("rxErrors", "0"); netStats.put("rxRate", Utils.rangeParser(networkLoad)); netStats.put("tx", Utils.rangeParser(networkLoad)); netStats.put("rx", Utils.rangeParser(networkLoad)); netStats.put("rxDropped", "0"); netStats.put("speed", "1000"); netStats.put("sampleTime", "4318787.08"); resultMap.put(dName, netStats); ++count; } return resultMap; }
Source:
public static CourseUnitAndroidVideoPlayerFragment newInstance(VideoBlockModel unit, boolean hasNextUnit, boolean hasPreviousUnit) { CourseUnitAndroidVideoPlayerFragment f = new CourseUnitAndroidVideoPlayerFragment(); Bundle args = new Bundle(); args.putSerializable(Router.EXTRA_COURSE_UNIT, unit); args.putBoolean(HAS_NEXT_UNIT_ID, hasNextUnit); args.putBoolean(HAS_PREV_UNIT_ID, hasPreviousUnit); f.setArguments(args); return f; }

Target:
public static CourseUnitAndroidVideoPlayerFragment newInstance(VideoBlockModel unit, boolean hasNextUnit, boolean hasPreviousUnit) { CourseUnitAndroidVideoPlayerFragment fragment = new CourseUnitAndroidVideoPlayerFragment(); fragment.setArguments(getCourseUnitBundle(unit, hasNextUnit, hasPreviousUnit)); return fragment; }
Source:
public OAuth2ServiceProvider updateProvider(String serviceName, OAuth2ServiceProvider provider) { DirectoryService ds = Framework.getService(DirectoryService.class); try (Session session = ds.open(DIRECTORY_NAME)) { DocumentModel entry = getProviderDocModel(serviceName); entry.setProperty(SCHEMA, "serviceName", provider.getServiceName()); entry.setProperty(SCHEMA, "description", provider.getDescription()); entry.setProperty(SCHEMA, "authorizationServerURL", provider.getAuthorizationServerURL()); entry.setProperty(SCHEMA, "tokenServerURL", provider.getTokenServerURL()); entry.setProperty(SCHEMA, "userAuthorizationURL", provider.getUserAuthorizationURL()); entry.setProperty(SCHEMA, "clientId", provider.getClientId()); entry.setProperty(SCHEMA, "clientSecret", provider.getClientSecret()); entry.setProperty(SCHEMA, "scopes", StringUtils.join(provider.getScopes(), ",")); boolean enabled = (provider.getClientId() != null && provider.getClientSecret() != null); entry.setProperty(SCHEMA, "enabled", enabled && provider.isEnabled()); if (!enabled) { log.info("OAuth2 provider for " + serviceName + " is disabled because clientId and/or clientSecret are empty"); } session.updateEntry(entry); return getProvider(serviceName); } }

Target:
public OAuth2ServiceProvider updateProvider(String serviceName, OAuth2ServiceProvider provider) { DirectoryService ds = Framework.getService(DirectoryService.class); try (Session session = ds.open(DIRECTORY_NAME)) { DocumentModel entry = getProviderDocModel(serviceName); entry.setProperty(SCHEMA, "serviceName", provider.getServiceName()); entry.setProperty(SCHEMA, "description", provider.getDescription()); entry.setProperty(SCHEMA, "authorizationServerURL", provider.getAuthorizationServerURL()); entry.setProperty(SCHEMA, "tokenServerURL", provider.getTokenServerURL()); entry.setProperty(SCHEMA, "userAuthorizationURL", provider.getUserAuthorizationURL()); entry.setProperty(SCHEMA, "clientId", provider.getClientId()); entry.setProperty(SCHEMA, "clientSecret", provider.getClientSecret()); entry.setProperty(SCHEMA, "scopes", String.join(",", provider.getScopes())); boolean enabled = provider.getClientId() != null && provider.getClientSecret() != null; entry.setProperty(SCHEMA, "enabled", enabled && provider.isEnabled()); if (!enabled) { log.info("OAuth2 provider for " + serviceName + " is disabled because clientId and/or clientSecret are empty"); } session.updateEntry(entry); return getProvider(serviceName); } }
Source:
private void scheduleWriteLastModified(String daoTypeName) { long modifiedTime = getLastModifiedOfTypeName(daoTypeName); Date when = new Date(); synchronized (daoTypeNameReferenceTime) { boolean schedule = daoTypeNameReferenceTime.get(daoTypeName) == null; daoTypeNameReferenceTime.put(daoTypeName, modifiedTime); GcsStorageService service = this; if (schedule) { Runnable task = new Runnable() { public void run() { log.info("RUNNING {}", daoTypeName); Long storedTime; synchronized (service.daoTypeNameReferenceTime) { storedTime = service.daoTypeNameReferenceTime.remove(daoTypeName); if (storedTime == null) { log.info("Defered writeLastModified was canceled."); return; } } long modifiedTime = service.getLastModifiedOfTypeName(daoTypeName); if (modifiedTime <= storedTime) { log.info("Retrying defered writeLastModified for {}", daoTypeName); service.writeLastModified(daoTypeName); } else { log.info("Canceling defered writeLastModified because timestamp already updated."); } } }; when.setSeconds(when.getSeconds() + 1); log.info("Scheduling defered update timestamp.", daoTypeName); taskScheduler.schedule(task, when); } else { log.info("Already scheduled update timestamp.", daoTypeName); } } }

Target:
public void scheduleWriteLastModified(String daoTypeName) { long modifiedTime = getLastModifiedOfTypeName(daoTypeName); Date when = new Date(); synchronized (daoTypeNameReferenceTime) { boolean schedule = daoTypeNameReferenceTime.get(daoTypeName) == null; daoTypeNameReferenceTime.put(daoTypeName, modifiedTime); GcsStorageService service = this; if (schedule) { Runnable task = new Runnable() { public void run() { log.info("RUNNING {}", daoTypeName); Long storedTime; synchronized (service.daoTypeNameReferenceTime) { storedTime = service.daoTypeNameReferenceTime.remove(daoTypeName); } long modifiedTime = service.getLastModifiedOfTypeName(daoTypeName); if (modifiedTime <= storedTime) { log.info("Retrying defered writeLastModified for {}", daoTypeName); service.writeLastModified(daoTypeName); } else { log.info("Canceling defered writeLastModified because timestamp already updated."); } } }; when.setSeconds(when.getSeconds() + 1); log.info("Scheduling defered update timestamp.", daoTypeName); taskScheduler.schedule(task, when); } else { log.info("Already scheduled update timestamp.", daoTypeName); } } }
Source:
public void testDynamicAddressReinitializedCorrectly() { ClientConfiguration ccfg = new ClientConfiguration() .setAddressesFinder(new TestAddressFinder("127.0.0.1:8000", "127.0.0.1:8003")); ReliableChannel rc = new ReliableChannel(chFactory, ccfg, null); rc.initConnection(); List<ReliableChannel.ClientChannelHolder> originChannels = Collections.unmodifiableList(rc.getChannelHolders()); rc.initChannelHolders(true); List<ReliableChannel.ClientChannelHolder> closedChannels = originChannels.stream() .filter(r -> r.isClosed()) .collect(Collectors.toList()); assertEquals(2, closedChannels.size()); List<ReliableChannel.ClientChannelHolder> reuseChannel = originChannels.stream() .filter(c -> !c.isClosed()) .collect(Collectors.toList()); assertEquals(1, reuseChannel.size()); List<ReliableChannel.ClientChannelHolder> newChannels = rc.getChannelHolders(); assertEquals(2, newChannels.size()); assertTrue(newChannels.get(0) == reuseChannel.get(0) || newChannels.get(1) == reuseChannel.get(0)); newChannels.forEach(c -> assertFalse(c.isClosed())); }

Target:
public void testDynamicAddressReinitializedCorrectly() { TestAddressFinder finder = new TestAddressFinder() .nextAddresesResponse(dfltAddrs) .nextAddresesResponse("127.0.0.1:10800", "127.0.0.1:10803"); ClientConfiguration ccfg = new ClientConfiguration().setAddressesFinder(finder); ReliableChannel rc = new ReliableChannel(chFactory, ccfg, null); rc.channelsInit(); List<ReliableChannel.ClientChannelHolder> originChannels = Collections.unmodifiableList(rc.getChannelHolders()); rc.initChannelHolders(); assertEquals(2, F.size(originChannels, ReliableChannel.ClientChannelHolder::isClosed)); List<ReliableChannel.ClientChannelHolder> reuseChannel = originChannels.stream() .filter(c -> !c.isClosed()) .collect(Collectors.toList()); assertEquals(1, reuseChannel.size()); List<ReliableChannel.ClientChannelHolder> newChannels = rc.getChannelHolders(); assertEquals(2, newChannels.size()); assertTrue(newChannels.get(0) == reuseChannel.get(0) || newChannels.get(1) == reuseChannel.get(0)); newChannels.forEach(c -> assertFalse(c.isClosed())); }
Source:
private OutputContext outputContext(QueryContext queryContext) { String channelGroupParam = queryContext.getRequest() .getParameter(SherlockAttributes.SCHEDULE_CHANNEL_GROUP_PARAM); OutputContext.Builder builder = OutputContext.builder(queryContext); List<String> channelGroups; if (!Strings.isNullOrEmpty(channelGroupParam)) { channelGroups = Arrays.asList(channelGroupParam.split("\\s*,\\s*")); } else { channelGroups = new ArrayList<>(); } List<Region> regions = new ArrayList<>(); List<Platform> platforms = new ArrayList<>(); for (ChannelGroup<?> channelGroup : resolveChannelGroups(channelGroups)) { if (channelGroup instanceof Region) { regions.add((Region) channelGroup); } else if (channelGroup instanceof Platform) { platforms.add((Platform) channelGroup); } else { throw new RuntimeException(new NotAcceptableException( String.format( "%s is not a region or platform.", channelGroup.getId() ) )); } } if (!regions.isEmpty()) { builder.withRegions(regions); } if (!platforms.isEmpty()) { builder.withPlatforms(platforms); } return builder.build(); }

Target:
private OutputContext outputContext(QueryContext queryContext) { String channelGroupParam = queryContext.getRequest() .getParameter(SherlockParameter.SCHEDULE_CHANNEL_GROUP.getName()); OutputContext.Builder builder = OutputContext.builder(queryContext); if (channelGroupParam != null) { List<String> channelGroupsParams = SPLITTER.splitToList(channelGroupParam); List<ChannelGroup<?>> channelGroups = resolveChannelGroups(channelGroupsParams); List<Region> regions = channelGroups.stream() .filter(cg -> cg instanceof Region) .map(cg -> (Region) cg) .collect(Collectors.toList()); if (!regions.isEmpty()) { builder.withRegions(regions); } List<Platform> platforms = channelGroups.stream() .filter(cg -> cg instanceof Platform) .map(cg -> (Platform) cg) .collect(Collectors.toList()); if (!platforms.isEmpty()) { builder.withPlatforms(platforms); } } return builder.build(); }
Source:
public void testResponseFilters() throws Exception { TestReplicationListener listener = new TestReplicationListener(); PullReplication pullReplication = createPullReplication(); pullReplication.responseFilters.add(new ResponseStreamReaderFilter()); Replicator replicator = ReplicatorFactory.oneway(pullReplication); replicator.getEventBus().register(listener); replicator.start(); while(replicator.getState() != Replicator.State.COMPLETE && replicator.getState() != Replicator.State.ERROR) { Thread.sleep(1000); } Assert.assertEquals(Replicator.State.ERROR, replicator.getState()); Assert.assertFalse(listener.finishCalled); Assert.assertTrue(listener.errorCalled); Assert.assertTrue(listener.exception instanceof RuntimeException); RuntimeException exception = (RuntimeException)listener.exception; Assert.assertTrue(exception.getCause() instanceof IOException); }

Target:
public void testResponseFilters() throws Exception { FilterCallCounter filterCallCounter = new FilterCallCounter(); PullReplication pullReplication = createPullReplication(); pullReplication.responseFilters.add(filterCallCounter); runReplicationUntilComplete(pullReplication); Assert.assertTrue(filterCallCounter.filterResponseTimesCalled >= 1); }
Source:
Map<String, Object> getExtraInformation() { return extraInformation; }

Target:
public Map<String, Object> getExtraInformation() { return extraInformation; }
Source:
private static String computeDefaultResolution(Context context, int key, int value) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); String resolution = preferences != null ? preferences.getString(context.getString(key), context.getString(value)) : context.getString(R.string.best_resolution_key); String maxResolution = getResolutionLimit(context); if (maxResolution != null && (resolution.equals("best_resolution") || compareVideoStreamResolution(maxResolution, resolution) < 1)) { resolution = maxResolution; } return resolution; }

Target:
private static String computeDefaultResolution(Context context, int key, int value) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); String resolution = preferences != null ? preferences.getString(context.getString(key), context.getString(value)) : context.getString(R.string.best_resolution_key); String maxResolution = getResolutionLimit(context); if (maxResolution != null && (resolution.equals(context.getString(R.string.best_resolution_key)) || compareVideoStreamResolution(maxResolution, resolution) < 1)) { resolution = maxResolution; } return resolution; }
Source:
private void addCertificate() { fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.addChoosableFileFilter(certFilter); fileChooser.setFileFilter(certFilter); int retVal = fileChooser.showOpenDialog(this); if (retVal == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try { idControll.addEntryToKeyStore(file); } catch (IOException e) { Log.error("Cannot upload certificate file", e); } catch (IllegalArgumentException e) { Log.warning("Certificate or it's alias cannot be null", e); } catch (HeadlessException e) { Log.error("Error at setting certificate alias", e); } } }

Target:
private void addCertificate() { fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.addChoosableFileFilter(certFilter); fileChooser.setFileFilter(certFilter); int retVal = fileChooser.showOpenDialog(this); if (retVal == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try { idControll.addEntryToKeyStore(file); } catch (CertificateException e) { JOptionPane.showMessageDialog(null, Res.getString("dialog.cannot.upload.certificate.might.be.ill.formated")); Log.error("Cannot upload certificate file", e); } catch (InvalidKeySpecException | NoSuchAlgorithmException | KeyStoreException | InvalidNameException | IOException e) { JOptionPane.showMessageDialog(null, "dialog.cannot.upload.certificate"); Log.error("Cannot upload certificate file", e); } } }
Source:
public void containersChanged(Set<TaskContainerDelta> containers) { for (TaskContainerDelta delta : containers) { IRepositoryElement reviewRepoElement = delta.getElement(); if (!(reviewRepoElement instanceof ITask)) { return; } ITask review = (ITask) reviewRepoElement; AbstractRepositoryConnector connector = repositoryManager.getRepositoryConnector(review.getConnectorKind()); if (review != null && connector instanceof ReviewsConnector) { switch (delta.getKind()) { case REMOVED: break; case DELETED: deleteMappingsTo(review); break; case CONTENT: String taskUrl = getTaskUrl(review); updateMapping(review, taskUrl); } } } }

Target:
public void containersChanged(Set<TaskContainerDelta> containers) { for (TaskContainerDelta delta : containers) { IRepositoryElement reviewRepoElement = delta.getElement(); if (!(reviewRepoElement instanceof ITask)) { return; } ITask review = (ITask) reviewRepoElement; AbstractRepositoryConnector connector = repositoryManager.getRepositoryConnector(review.getConnectorKind()); if (review != null && connector instanceof ReviewsConnector) { if (delta.getKind() == Kind.DELETED) { deleteMappingsTo(review); } } } }
Source:
public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater.inflate(R.layout.theme_grid_item, parent, false); ThemeViewHolder themeViewHolder = new ThemeViewHolder(view); view.setTag(themeViewHolder); mViewWidth = parent.getWidth(); return view; }

Target:
public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater.inflate(R.layout.theme_grid_item, parent, false); configureThemeImageSize(parent); ThemeViewHolder themeViewHolder = new ThemeViewHolder(view); view.setTag(themeViewHolder); return view; }
Source:
private List<DiskImage> getImagesToPreview() { if (imagesToPreview == null) { List<DiskImage> imagesByGuid = new ArrayList<>(); if (getParameters().getDisks() != null) { for (Guid guid : getParameters().getDisks()) { DiskImage image = diskImageDao.getSnapshotById(guid); imagesByGuid.add(image); } imagesToPreview = imagesByGuid; } else { imagesToPreview = diskImageDao.getAllSnapshotsForVmSnapshot(getDstSnapshot().getId()); } List<CinderDisk> CinderImagesToPreview = DisksFilter.filterCinderDisks(imagesToPreview); imagesToPreview = DisksFilter.filterImageDisks(imagesToPreview, ONLY_NOT_SHAREABLE, ONLY_SNAPABLE); imagesToPreview.addAll(CinderImagesToPreview); } return imagesToPreview; }

Target:
private List<DiskImage> getImagesToPreview() { if (imagesToPreview == null) { if (getParameters().getDisks() != null) { imagesToPreview = getParameters().getDisks().stream() .map(diskImageDao::getSnapshotById) .collect(Collectors.toList()); } else { imagesToPreview = diskImageDao.getAllSnapshotsForVmSnapshot(getDstSnapshot().getId()); } List<CinderDisk> CinderImagesToPreview = DisksFilter.filterCinderDisks(imagesToPreview); imagesToPreview = DisksFilter.filterImageDisks(imagesToPreview, ONLY_NOT_SHAREABLE, ONLY_SNAPABLE); imagesToPreview.addAll(CinderImagesToPreview); } return imagesToPreview; }
Source:
private static HttpURLConnection createConnection(Connection.Request req) throws IOException { HttpURLConnection conn = (HttpURLConnection) req.url().openConnection(); conn.setRequestMethod(req.method().name()); conn.setInstanceFollowRedirects(false); conn.setConnectTimeout(req.timeout()); conn.setReadTimeout(req.timeout()); if (!req.isSecure()) { initUnSecureSSL(); if (conn instanceof HttpsURLConnection) { ((HttpsURLConnection)conn).setSSLSocketFactory(sslSocketFactory); } } if (req.method() == Method.POST) conn.setDoOutput(true); if (req.cookies().size() > 0) conn.addRequestProperty("Cookie", getRequestCookieString(req)); for (Map.Entry<String, String> header : req.headers().entrySet()) { conn.addRequestProperty(header.getKey(), header.getValue()); } return conn; }

Target:
private static HttpURLConnection createConnection(Connection.Request req) throws IOException { HttpURLConnection conn = (HttpURLConnection) req.url().openConnection(); conn.setRequestMethod(req.method().name()); conn.setInstanceFollowRedirects(false); conn.setConnectTimeout(req.timeout()); conn.setReadTimeout(req.timeout()); if (conn instanceof HttpsURLConnection) { if (!req.isValidateSSLCertificates()) { initUnSecureSSL(); ((HttpsURLConnection)conn).setSSLSocketFactory(sslSocketFactory); ((HttpsURLConnection)conn).setHostnameVerifier(getInsecureVerifier()); } } if (req.method().hasBody()) conn.setDoOutput(true); if (req.cookies().size() > 0) conn.addRequestProperty("Cookie", getRequestCookieString(req)); for (Map.Entry<String, String> header : req.headers().entrySet()) { conn.addRequestProperty(header.getKey(), header.getValue()); } return conn; }
Source:
public void attempToRestoreVmConfigurationFromSnapshot(VM vm, Snapshot snapshot, Guid activeSnapshotId, CompensationContext compensationContext) { boolean vmUpdatedFromConfiguration = updateVmFromConfiguration(vm, snapshot.getVmConfiguration()); if (snapshot.getVmConfiguration() == null || !vmUpdatedFromConfiguration) { vm.setImages(new ArrayList<DiskImage>(getDiskImageDao().getAllSnapshotsForVmSnapshot(snapshot.getId()))); } vm.setapp_list(snapshot.getAppList()); getVmDynamicDao().update(vm.getDynamicData()); synchronizeDisksFromSnapshot(vm.getId(), snapshot.getId(), activeSnapshotId, vm.getImages()); if (vmUpdatedFromConfiguration) { getVmStaticDao().update(vm.getStaticData()); synchronizeNics(vm.getId(), vm.getInterfaces(), compensationContext); } }

Target:
public void attempToRestoreVmConfigurationFromSnapshot(VM vm, Snapshot snapshot, Guid activeSnapshotId, CompensationContext compensationContext) { boolean vmUpdatedFromConfiguration = false; if (snapshot.getVmConfiguration() != null) { vmUpdatedFromConfiguration = updateVmFromConfiguration(vm, snapshot.getVmConfiguration()); } if (!vmUpdatedFromConfiguration) { vm.setImages(new ArrayList<DiskImage>(getDiskImageDao().getAllSnapshotsForVmSnapshot(snapshot.getId()))); } vm.setapp_list(snapshot.getAppList()); getVmDynamicDao().update(vm.getDynamicData()); synchronizeDisksFromSnapshot(vm.getId(), snapshot.getId(), activeSnapshotId, vm.getImages(), vm.getvm_name()); if (vmUpdatedFromConfiguration) { getVmStaticDao().update(vm.getStaticData()); synchronizeNics(vm.getId(), vm.getInterfaces(), compensationContext); } }
Source:
public static List<Sample> convert(final List<Sample> samples) { if (samples.size() <= Math.max(DEFAULT_NOISE_LENGTH_TOLERANCE, DEFAULT_MOVING_AVERAGE_WINDOW_SIZE_FOR_HIGH_RESOLUTION)) { return samples; } final double[] values = getSampleValuesArray(samples); final double mean = new Mean().evaluate(values); final double stdDev = new StandardDeviation().evaluate(values, mean); final int movingAvgWindowSize = samples.get(1).dateTime - samples.get(0).dateTime > 60000 ? DEFAULT_MOVING_AVERAGE_WINDOW_SIZE_FOR_LOW_RESOLUTION : DEFAULT_MOVING_AVERAGE_WINDOW_SIZE_FOR_HIGH_RESOLUTION; final double[] noiseFreeValues = smudgeNoise(values, mean, stdDev, DEFAULT_NOISE_LENGTH_TOLERANCE); final double[] smoothedValues = smooth(noiseFreeValues, movingAvgWindowSize); final List<Sample> convertedSamples = Lists.newArrayList(); for (int i=0; i < samples.size(); i++) { convertedSamples.add(new Sample(samples.get(i).dateTime, (float) smoothedValues[i], samples.get(i).offsetMillis)); } return convertedSamples; }

Target:
public static List<Sample> convert(final List<Sample> samples) { if (samples.size() <= Math.max(DEFAULT_NOISE_LENGTH_TOLERANCE, DEFAULT_MOVING_AVERAGE_WINDOW_SIZE_FOR_HIGH_RESOLUTION)) { return samples; } final double[] values = getSampleValuesArray(samples); final double mean = new Mean().evaluate(values); final double stdDev = new StandardDeviation().evaluate(values, mean); final int movingAvgWindowSize = new Interval(samples.get(0).dateTime, samples.get(1).dateTime).toDuration().getStandardMinutes() > 5 ? DEFAULT_MOVING_AVERAGE_WINDOW_SIZE_FOR_LOW_RESOLUTION : DEFAULT_MOVING_AVERAGE_WINDOW_SIZE_FOR_HIGH_RESOLUTION; final double[] noiseFreeValues = smudgeNoise(values, mean, stdDev, DEFAULT_NOISE_LENGTH_TOLERANCE); final double[] smoothedValues = smooth(noiseFreeValues, movingAvgWindowSize); final List<Sample> convertedSamples = Lists.newArrayList(); for (int i=0; i < samples.size(); i++) { convertedSamples.add(new Sample(samples.get(i).dateTime, (float) smoothedValues[i], samples.get(i).offsetMillis)); } return convertedSamples; }
Source:
public void shouldSetRemovalTime_HistoricProcessInstanceAuthorization() { testRule.getProcessEngineConfiguration() .setEnableHistoricInstancePermissions(true); String processInstanceId = testRule.process().userTask().deploy().start(); Authorization authorization = authorizationService.createNewAuthorization(Authorization.AUTH_TYPE_GRANT); authorization.setResource(Resources.HISTORIC_PROCESS_INSTANCE); authorization.setResourceId(processInstanceId); authorization.setUserId("foo"); authorizationService.saveAuthorization(authorization); HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery(); testRule.syncExec( historyService.setRemovalTimeToHistoricProcessInstances() .absoluteRemovalTime(REMOVAL_TIME) .byQuery(query) .executeAsync() ); authorization = authorizationService.createAuthorizationQuery() .resourceType(Resources.HISTORIC_PROCESS_INSTANCE) .singleResult(); assertThat(authorization.getRemovalTime()).isEqualTo(REMOVAL_TIME); testRule.clearAuthorization(); }

Target:
public void shouldSetRemovalTime_HistoricProcessInstanceAuthorization() { testRule.getProcessEngineConfiguration() .setEnableHistoricInstancePermissions(true); String processInstanceId = testRule.process().userTask().deploy().start(); Authorization authorization = authorizationService.createNewAuthorization(Authorization.AUTH_TYPE_GRANT); authorization.setResource(Resources.HISTORIC_PROCESS_INSTANCE); authorization.setResourceId(processInstanceId); authorization.setUserId("foo"); authorizationService.saveAuthorization(authorization); HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery(); testRule.syncExec( historyService.setRemovalTimeToHistoricProcessInstances() .absoluteRemovalTime(REMOVAL_TIME) .byQuery(query) .executeAsync() ); authorization = authorizationService.createAuthorizationQuery() .resourceType(Resources.HISTORIC_PROCESS_INSTANCE) .singleResult(); assertThat(authorization.getRemovalTime()).isEqualTo(REMOVAL_TIME); }
Source:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Exec {\n"); sb.append(" command: ").append(toIndentedString(command)).append("\n"); sb.append("}"); return sb.toString(); }

Target:
public String toString() { return "Exec{" + "command=" + command + '}'; }
Source:
public Path getFileName() { if (this.withoutRoot().isEmpty()) { return null; } else { return this.parentFileSystem.getPath(Flux.fromArray(this.splitToElements()).last().block()); } }

Target:
public Path getFileName() { if (this.withoutRoot().isEmpty()) { return null; } else { List<String> elements = Arrays.asList(this.splitToElements()); return this.parentFileSystem.getPath(elements.get(elements.size() - 1)); } }
Source:
private boolean classesDeclareOverridingNativeMethod(IType[] classes) throws CoreException { for (IType classe : classes) { for (IMethod method : classe.getMethods()) { if ((!method.equals(getMethod())) && (JdtFlags.isNative(method)) && (null != Checks.findSimilarMethod(getMethod(), new IMethod[]{method}))) { return true; } } } return false; }

Target:
private boolean classesDeclareOverridingNativeMethod(IType[] classes) throws CoreException { for (IType type : classes) { for (IMethod method : type.getMethods()) { if ((!method.equals(getMethod())) && (JdtFlags.isNative(method)) && (null != Checks.findSimilarMethod(getMethod(), new IMethod[]{method}))) { return true; } } } return false; }
Source:
public boolean evaluate(IEvaluationContext context) { if (activeWhen == null) { active = true; } else { try { active = false; active = activeWhen.evaluate(context) != EvaluationResult.FALSE; } catch (CoreException e) { if (Policy.DEBUG_CMDS) { Activator.trace(Policy.DEBUG_CMDS_FLAG, "Failed to calculate active", e); } } } if (active) { try { if (handler instanceof IHandler2) { ((IHandler2) handler).setEnabled(context); } if (!handler.isEnabled()) { active = false; } } catch (RuntimeException e) { active = false; Activator.trace(Policy.DEBUG_CMDS_FLAG, "Failed to calculate active", e); } } return active; }

Target:
public boolean evaluate(IEvaluationContext context) { if (activeWhen == null) { active = true; } else { try { active = false; active = activeWhen.evaluate(context) != EvaluationResult.FALSE; } catch (CoreException e) { if (Policy.DEBUG_CMDS) { Activator.trace(Policy.DEBUG_CMDS_FLAG, "Failed to evaluate activeWhen for HandlerActivation " + this + " in context " + context, e); } } } if (active) { try { if (handler instanceof IHandler2) { ((IHandler2) handler).setEnabled(context); } if (!handler.isEnabled()) { active = false; } } catch (RuntimeException e) { active = false; Activator.trace(Policy.DEBUG_CMDS_FLAG, "Failed to evaluate handler active state for HandlerActivation " + this + " in context " + context, e); } } return active; }
Source:
public static ContentSigner createSigner(PrivateKey privateKey) { try { AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder() .find("SHA256WithRSAEncryption"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder() .find(sigAlgId); return new BcRSAContentSignerBuilder(sigAlgId, digAlgId) .build(PrivateKeyFactory.createKey(privateKey.getEncoded())); } catch (Exception e) { throw new RuntimeException("Could not create content signer.", e); } }

Target:
private static ContentSigner createSigner(PrivateKey privateKey) { try { AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder() .find("SHA256WithRSAEncryption"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder() .find(sigAlgId); return new BcRSAContentSignerBuilder(sigAlgId, digAlgId) .build(PrivateKeyFactory.createKey(privateKey.getEncoded())); } catch (Exception e) { throw new RuntimeException("Could not create content signer.", e); } }
Source:
public Comparator<String> nameComparator() { final Map<String, Integer> positions = positions(); return new Comparator<String>() { @Override public int compare(String left, String right) { Integer lp = positions.get(left); Integer rp = positions.get(right); if (lp == rp) { return 0; } else if (lp == null) { return -1; } else if (rp == null) { return 1; } else { return lp - rp; } } }; }

Target:
public Comparator<String> nameComparator() { final Map<String, Integer> positions = positions(); return new Comparator<String>() { @Override public int compare(String left, String right) { Integer lp = positions.get(left); Integer rp = positions.get(right); if (lp == null) { return rp != null ? 1 : left.compareTo(right); } else if (rp == null) { return lp != null ? -1 : left.compareTo(right); } else if (lp == rp) { return left.compareTo(right); } else { return lp - rp; } } }; }
Source:
private static void setLightConditions(AtBDynamicScenario scenario) { int roll = Compute.randomInt(10) + 1; int light = PlanetaryConditions.L_DAY; if ((6 <= roll) && (roll < 8)){ light = PlanetaryConditions.L_DUSK; } else if (roll == 8){ light = PlanetaryConditions.L_FULL_MOON; } else if (roll == 9) { light = PlanetaryConditions.L_MOONLESS; } else { light = PlanetaryConditions.L_PITCH_BLACK; } scenario.setLight(light); }

Target:
private static void setLightConditions(AtBDynamicScenario scenario) { int roll = Compute.randomInt(10) + 1; int light; if (roll < 6) { light = PlanetaryConditions.L_DAY; } else if (roll < 8) { light = PlanetaryConditions.L_DUSK; } else if (roll == 8) { light = PlanetaryConditions.L_FULL_MOON; } else if (roll == 9) { light = PlanetaryConditions.L_MOONLESS; } else { light = PlanetaryConditions.L_PITCH_BLACK; } scenario.setLight(light); }
Source:
public void onNext(final TaskMessage taskMessage) { final String taskId = taskMessage.getId(); final byte[] retBytes = taskMessage.get(); final String retStr = retBytes == null ? "No RetVal" : new String(retBytes, StandardCharsets.UTF_8); LOG.log(Level.FINE, "Line count from {0} : {1}", new String[]{taskId, retStr}); if (retBytes == null) { return; } lineCnt.addAndGet(Integer.parseInt(retStr)); if (completedTasks.incrementAndGet() >= numEvals) { LOG.log(Level.INFO, "FilePath: {0}, Total line count: {1}", new Object[]{inputPathList.get(fileCounter.get() - 1), lineCnt.get()}); lineCnt.set(0); completedTasks.set(0); if (!loadNextFileInEvals()) { runningTaskList.forEach(RunningTask::close); } } }

Target:
public void onNext(final TaskMessage taskMessage) { final String taskId = taskMessage.getId(); final byte[] retBytes = taskMessage.get(); if (retBytes == null) { LOG.log(Level.FINE, "No line was read by {0}", taskId); return; } final String retStr = new String(retBytes, StandardCharsets.UTF_8); LOG.log(Level.FINE, "Line count from {0} : {1}", new String[]{taskId, retStr}); lineCnt.addAndGet(Integer.parseInt(retStr)); if (completedTasks.incrementAndGet() >= numEvals) { LOG.log(Level.INFO, "FilePath: {0}, Total line count: {1}", new Object[]{inputPathList.get(fileCounter.get() - 1), lineCnt.get()}); lineCnt.set(0); completedTasks.set(0); if (!loadNextFileInEvals()) { runningTaskList.forEach(RunningTask::close); } } }
Source:
public void forPage_fails_with_IAE_if_page_is_less_than_0() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("page index must be >= 1"); forPage(-Math.abs(new Random().nextInt() + 1)); }

Target:
public void forPage_fails_with_IAE_if_page_is_less_than_0() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("page index must be >= 1"); forPage(-Math.abs(new Random().nextInt()) - 1); }