auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public final U assertValueSequence(Iterable<? extends T> sequence) { int i = 0; Iterator<T> actualIterator = values.iterator(); Iterator<? extends T> expectedIterator = sequence.iterator(); boolean actualNext; boolean expectedNext; for (;;) { expectedNext = expectedIterator.hasNext(); actualNext = actualIterator.hasNext(); if (!actualNext || !expectedNext) { break; } T v = expectedIterator.next(); T u = actualIterator.next(); if (!ObjectHelper.equals(u, v)) { throw fail("Values at position " + i + " differ; Expected: " + valueAndClass(v) + ", Actual: " + valueAndClass(u)); } i++; } if (actualNext) { throw fail("More values received than expected (" + i + ")"); } if (expectedNext) { throw fail("Fewer values received than expected (" + i + ")"); } return (U)this; }

Target:
public final U assertValueSequence(Iterable<? extends T> sequence) { int i = 0; Iterator<T> actualIterator = values.iterator(); Iterator<? extends T> expectedIterator = sequence.iterator(); boolean actualNext; boolean expectedNext; for (;;) { expectedNext = expectedIterator.hasNext(); actualNext = actualIterator.hasNext(); if (!actualNext || !expectedNext) { break; } T u = expectedIterator.next(); T v = actualIterator.next(); if (!ObjectHelper.equals(u, v)) { throw fail("Values at position " + i + " differ; Expected: " + valueAndClass(u) + ", Actual: " + valueAndClass(v)); } i++; } if (actualNext) { throw fail("More values received than expected (" + i + ")"); } if (expectedNext) { throw fail("Fewer values received than expected (" + i + ")"); } return (U)this; }
Source:
protected void onShowPage(boolean firstShow) { try { loadConfiguration(); if (!isEnable) { disposeControl(); Label label = new Label(page, SWT.WRAP); label.setText("Schema retrieval is not enabled for selected driver."); label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1)); page.layout(true, true); setMessage(""); setPageComplete(true); return; } if (firstShow) { createComponent(); } else { disposeControl(); schemas.clear(); createComponent(); } getSchemas(); schemaTable.setInput(schemas); if (multipleSelection) { schemaTable.setAllChecked(true); setPageComplete(true); setMessage("Please select one or multiple schemas."); } else { setMessage("Please select one schema."); } } catch (SQLException e) { log.error(e.getMessage(), e); } }

Target:
protected void onShowPage(boolean firstShow) { try { loadConfiguration(); if (!isEnable) { disposeControl(); Label label = new Label(page, SWT.WRAP); label.setText( "Restricting the tables to load from specific database schemas, is not " + "supported for this database driver. All database tables will be loaded."); label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1)); page.layout(true, true); setMessage(""); setPageComplete(true); return; } if (firstShow) { createComponent(); } else { disposeControl(); schemas.clear(); createComponent(); } getSchemas(); schemaTable.setInput(schemas); if (multipleSelection) { schemaTable.setAllChecked(true); setPageComplete(true); setMessage("Please select one or multiple schemas."); } else { setMessage("Please select one schema."); } } catch (SQLException e) { log.error(e.getMessage(), e); } }
Source:
public void clickCloseShareScreenButton() { waitForElementByElement(closeShareScreenButton); closeShareScreenButton.click(); }

Target:
public void clickCloseShareScreenButton() { waitForElementByElement(closeShareScreenButton); closeShareScreenButton.click(); PageObjectLogging.log("clickCloseShareScreenButton", "close share screen button was clicked", true); }
Source:
public AppPage clickNoOnModal() { waitForTwoConfirmationModalAndClickOnNo(); waitForPageToLoad(); return this; }

Target:
public void clickNoOnModal() { waitForModalPresence(); WebElement noButton = browser.driver.findElement(By.cssSelector("[data-bb-handler='no']")); waitForElementToBeClickable(noButton); click(noButton); waitForModalToDisappear(); }
Source:
public List<String> getApiUris() { List<String> apiUris = Lists.newArrayList(); if (config.has(NSBarcodeConfigKeys.API_CONFIG)) { JSONArray childNode = null; try { childNode = config.getJSONArray(NSBarcodeConfigKeys.API_CONFIG); } catch (JSONException e) { log.error(TAG, "Invalid json array: "+ config.toString()); return apiUris; } for (int index = 0; index < childNode.length(); index++) { try { apiUris.add(new JSONObject(childNode.getString(index)).getString(NSBarcodeConfigKeys.API_URI)); } catch (JSONException e) { log.error(TAG, "Invalid child json object: "+ config.toString()); } } } return apiUris; }

Target:
public List<String> getApiUris() { List<String> apiUris = Lists.newArrayList(); if (config.has(NSBarcodeConfigKeys.API_CONFIG)) { JSONArray childNode = null; try { childNode = config.getJSONArray(NSBarcodeConfigKeys.API_CONFIG); } catch (JSONException e) { log.error("Invalid json array: "+ config.toString()); return apiUris; } for (int index = 0; index < childNode.length(); index++) { try { apiUris.add(childNode.getJSONObject(index).getString(NSBarcodeConfigKeys.API_URI)); } catch (JSONException e) { log.error("Invalid child json object: "+ config.toString()); } } } return apiUris; }
Source:
public int getNumWaiters() { return this.connectionPool.getNumActive(); }

Target:
public int getNumWaiters() { return this.connectionPool.getNumWaiters(); }
Source:
public void getReplicasForBlobIdTest() throws ExecutionException, InterruptedException, JSONException { List<PartitionId> partitionIds = CLUSTER_MAP.getWritablePartitionIds(); PartitionId partitionId = partitionIds.get(new Random().nextInt(partitionIds.size())); String originalReplicaStr = partitionId.getReplicaIds().toString().replace(", ", ","); BlobId blobId = new BlobId(partitionId); String uri = AdminBlobStorageService.GET_REPLICAS_FOR_BLOB_ID + "?" + GetReplicasForBlobIdHandler.BLOB_ID_KEY + "=" + blobId; FullHttpRequest request = buildRequest(HttpMethod.GET, uri, null, null); Queue<HttpObject> responseParts = nettyClient.sendRequest(request, null, null).get(); HttpResponse response = (HttpResponse) responseParts.poll(); assertEquals("Unexpected status", HttpResponseStatus.OK, response.getStatus()); assertEquals("Unexpected Content-Type", "application/json", HttpHeaders.getHeader(response, HttpHeaders.Names.CONTENT_TYPE)); ByteBuffer buffer = getContent(response, responseParts); JSONObject responseObj = new JSONObject(new String(buffer.array())); String returnedReplicasStr = responseObj.getString(GetReplicasForBlobIdHandler.REPLICAS_KEY).replace("\"", ""); assertEquals("Replica IDs returned for the BlobId do no match with the replicas IDs of partition", originalReplicaStr, returnedReplicasStr); }

Target:
public void getReplicasForBlobIdTest() throws ExecutionException, InterruptedException, JSONException { List<PartitionId> partitionIds = CLUSTER_MAP.getWritablePartitionIds(); PartitionId partitionId = partitionIds.get(new Random().nextInt(partitionIds.size())); String originalReplicaStr = partitionId.getReplicaIds().toString().replace(", ", ","); BlobId blobId = new BlobId(partitionId); String uri = AdminBlobStorageService.GET_REPLICAS_FOR_BLOB_ID + "?" + GetReplicasForBlobIdHandler.BLOB_ID_KEY + "=" + blobId; FullHttpRequest httpRequest = buildRequest(HttpMethod.GET, uri, null, null); Queue<HttpObject> responseParts = nettyClient.sendRequest(httpRequest, null, null).get(); HttpResponse response = (HttpResponse) responseParts.poll(); assertEquals("Unexpected status", HttpResponseStatus.OK, response.getStatus()); assertEquals("Unexpected Content-Type", "application/json", HttpHeaders.getHeader(response, HttpHeaders.Names.CONTENT_TYPE)); ByteBuffer buffer = getContent(response, responseParts); JSONObject responseObj = new JSONObject(new String(buffer.array())); String returnedReplicasStr = responseObj.getString(GetReplicasForBlobIdHandler.REPLICAS_KEY).replace("\"", ""); assertEquals("Returned response for the BlobId do no match with the replicas IDs of partition", originalReplicaStr, returnedReplicasStr); }
Source:
public Sku toSku() { return this.sku; }

Target:
public Sku toSku() { return new Sku() .withName(sku.name()) .withTier(sku.tier()) .withFamily(sku.family()) .withCapacity(sku.capacity()) .withSize(sku.size()); }
Source:
private static ResourceModel processSimpleResource(final Class<?> resourceClass, ResourceModel parentResource) { Class<? extends RecordTemplate> valueClass = null; if (SingleObjectResource.class.isAssignableFrom(resourceClass)) { @SuppressWarnings("unchecked") Class<? extends SingleObjectResource<?>> clazz = (Class<? extends SingleObjectResource<?>>) resourceClass; List<Class<?>> kvParams = ReflectionUtils.getTypeArguments(SingleObjectResource.class, clazz); valueClass = kvParams.get(0).asSubclass(RecordTemplate.class); } else { for (Method method : resourceClass.getDeclaredMethods()) { if (method.isSynthetic()) { continue; } Finder finderAnno = method.getAnnotation(Finder.class); if (finderAnno == null) { continue; } throw new ResourceConfigException("Class '" + resourceClass.getName() + "' of a SingleUnstructuredDataResource " + "class does not support for @Finder methods"); } } ResourceType resourceType = getResourceType(resourceClass); RestLiAnnotationData annotationData = getRestLiAnnotationData(resourceClass); String name = annotationData.name(); String namespace = annotationData.namespace(); Class<?> parentResourceClass = annotationData.parent().equals(RestAnnotations.ROOT.class) ? null : annotationData.parent(); ResourceModel resourceModel = new ResourceModel(valueClass, resourceClass, parentResourceClass, name, resourceType, namespace); resourceModel.setParentResourceModel(parentResource); addResourceMethods(resourceClass, resourceModel); log.debug("Processed simple resource '" + resourceClass.getName() + "'"); return resourceModel; }

Target:
private static ResourceModel processSimpleResource(final Class<?> resourceClass, ResourceModel parentResource) { Class<? extends RecordTemplate> valueClass = null; if (SingleObjectResource.class.isAssignableFrom(resourceClass)) { @SuppressWarnings("unchecked") Class<? extends SingleObjectResource<?>> clazz = (Class<? extends SingleObjectResource<?>>) resourceClass; List<Class<?>> kvParams = ReflectionUtils.getTypeArguments(SingleObjectResource.class, clazz); valueClass = kvParams.get(0).asSubclass(RecordTemplate.class); } ResourceType resourceType = getResourceType(resourceClass); RestLiAnnotationData annotationData = getRestLiAnnotationData(resourceClass); String name = annotationData.name(); String namespace = annotationData.namespace(); Class<?> parentResourceClass = annotationData.parent().equals(RestAnnotations.ROOT.class) ? null : annotationData.parent(); ResourceModel resourceModel = new ResourceModel(valueClass, resourceClass, parentResourceClass, name, resourceType, namespace); resourceModel.setParentResourceModel(parentResource); addResourceMethods(resourceClass, resourceModel); log.debug("Processed simple resource '" + resourceClass.getName() + "'"); return resourceModel; }
Source:
public void writeData(byte[] data) throws IOException { if (getOutputStream() != null) { if (isHardwareFlowControl()) { int tries = 0; while (tries < 3 && !isCTS()) { try { Thread.sleep(100); } catch (InterruptedException e) { } tries += 1; } if (isCTS()) { getOutputStream().write(data); getOutputStream().flush(); } } else { getOutputStream().write(data); getOutputStream().flush(); } } }

Target:
public void writeData(byte[] data) throws IOException { if (data == null) throw new NullPointerException("Data to be sent cannot be null."); if (getOutputStream() != null) { if (isHardwareFlowControl()) { int tries = 0; while (tries < 3 && !isCTS()) { try { Thread.sleep(100); } catch (InterruptedException e) { } tries += 1; } if (isCTS()) { getOutputStream().write(data); getOutputStream().flush(); } } else { getOutputStream().write(data); getOutputStream().flush(); } } }
Source:
public Response getPhotos(@Auth Key key, @QueryParam("username") String username) throws IOException, MalformedURLException { if (username == null) { return Response.status(Response.Status.BAD_REQUEST) .entity("'username' query parameter is required for getUser").build(); } PilotUser pilotUser = thunderClient.getUser(username); FacebookProvider facebookProvider = facebookProviderFactory.newFacebookProvider(pilotUser.getFacebookAccessToken()); List<String> urlList; try { urlList = facebookProvider.getFacebookUserPhotos(); } catch (FacebookOAuthException e) { LOG.error("Bad Facebook OAuth token for username {}", username, e); return Response.status(Response.Status.NOT_FOUND) .entity("Request rejected due to bad OAuth token").build(); } return Response.ok(urlList).build(); }

Target:
public Response getPhotos(@Auth Key key, @QueryParam("username") String username) { if (username == null) { return Response.status(Response.Status.BAD_REQUEST) .entity("'username' query parameter is required for getUser").build(); } PilotUser pilotUser = thunderClient.getUser(username); FacebookProvider facebookProvider = facebookProviderFactory.newFacebookProvider(pilotUser.getFacebookAccessToken()); List<String> urlList; try { urlList = facebookProvider.getFacebookUserPhotos(); } catch (FacebookOAuthException e) { LOG.error("Bad Facebook OAuth token for username {}", username, e); return Response.status(Response.Status.NOT_FOUND) .entity("Request rejected due to bad OAuth token").build(); } return Response.ok(urlList).build(); }
Source:
public void testEqualityOverride() { KieSession ksession = session.getStateful(); FactHandle string = ksession.insert("testString"); ksession.fireAllRules(); Assertions.assertThat(ksession.getObjects().size()).isEqualTo(2); ksession.insert(42); ksession.fireAllRules(); Assertions.assertThat(ksession.getObjects().size()).isEqualTo(4); ksession.delete(string); ksession.fireAllRules(); Assertions.assertThat(ksession.getObjects().size()).isEqualTo(2); }

Target:
public void testEqualityOverride() { KieSession ksession = session.getStateful(); FactHandle string = ksession.insert("testString"); ksession.fireAllRules(); Assertions.assertThat(ksession.getObjects().size()).isEqualTo(2); ksession.insert(ANY_NUMBER); ksession.fireAllRules(); Assertions.assertThat(ksession.getObjects().size()).isEqualTo(4); ksession.delete(string); ksession.fireAllRules(); Assertions.assertThat(ksession.getObjects().size()).isEqualTo(2); }
Source:
public void prepareRun(BatchSinkContext context) throws Exception { Job job = context.getHadoopJob(); job.setOutputFormatClass(NullOutputFormat.class); context.addOutput(Output.of(batchConfig.referenceName, new SolrSearchSink.SolrOutputFormatProvider(batchConfig))); }

Target:
public void prepareRun(BatchSinkContext context) throws Exception { context.addOutput(Output.of(batchConfig.referenceName, new SolrSearchSink.SolrOutputFormatProvider(batchConfig))); }
Source:
public void load() { for (IndexConfiguration indexConfiguration : indexesConfigurations) { if (copyConfiguration) { indexConfigurationCopier.copyIndexConfiguration(indexConfiguration, solrHomeLocationPolicy.fetchSolrHome()); } indexReloader.reloadIndex(indexConfiguration); } }

Target:
public void load() { for (IndexConfiguration indexConfiguration : indexesConfigurations) { if (copyConfiguration) { indexConfigurationCopier.copyIndexConfiguration(indexConfiguration, solrHomeLocationPolicy.getSolrHome()); } indexReloader.reloadIndex(indexConfiguration); } }
Source:
protected void packHeader (OutputObjectState os, Header hdr) throws IOException { Uid txId = ((hdr == null) ? null : hdr.getTxId()); Uid processUid = ((hdr == null) ? null : hdr.getProcessId()); try { os.packStringBytes(markerBytes); if (txId != null) { UidHelper.packInto(txId, os); UidHelper.packInto(processUid, os); } else UidHelper.packInto(Uid.nullUid(), os); long birthDate = System.currentTimeMillis(); if (tsLogger.logger.isTraceEnabled()) { tsLogger.logger.trace("StateManager.packHeader for object-id " + get_uid() + " birth-date " + birthDate); } os.packLong(birthDate); } catch (IOException ex) { throw ex; } catch (Exception e) { IOException ioException = new IOException(e.toString()); ioException.initCause(e); throw ioException; } }

Target:
protected void packHeader (OutputObjectState os, Header hdr) throws IOException { Uid txId = ((hdr == null) ? null : hdr.getTxId()); Uid processUid = ((hdr == null) ? null : hdr.getProcessId()); try { os.packStringBytes(StateManager.markerBytes); if (txId != null) { UidHelper.packInto(txId, os); UidHelper.packInto(processUid, os); } else UidHelper.packInto(Uid.nullUid(), os); long birthDate = System.currentTimeMillis(); if (tsLogger.logger.isTraceEnabled()) { tsLogger.logger.trace("StateManager.packHeader for object-id " + get_uid() + " birth-date " + birthDate); } os.packLong(birthDate); } catch (IOException ex) { throw ex; } catch (Exception e) { IOException ioException = new IOException(e.toString()); ioException.initCause(e); throw ioException; } }
Source:
@Test public void testFilterableWhere3() throws SQLException { final String sql = "select empno, gender, name from EMPS\n" + " where gender = 'F' or empno > 125"; sql("filterable-model", sql) .returns("EMPNO=120; GENDER=F; NAME=Wilma", "EMPNO=130; GENDER=F; NAME=Alice") .ok(); }

Target:
@Test public void testFilterableWhere3() throws SQLException { final String sql = "select empno, gender, name from EMPS\n" + " where gender <> 'M' and empno > 125"; sql("filterable-model", sql) .returns("EMPNO=130; GENDER=F; NAME=Alice") .ok(); }
Source:
public static String getRootURL() { String moduleURL = GWT.getModuleBaseURL(); int index = moduleURL.indexOf("://"); if (index == -1) { GWT.log("Can't extract root URL from module URL \"" + moduleURL + "\"."); } index = moduleURL.indexOf("/", index + 3); if (index == -1) { return moduleURL; } return moduleURL.substring(0, index); }

Target:
public static String getRootURL() { String moduleURL = GWT.getModuleBaseURL(); String separator = "://"; int index = moduleURL.indexOf(separator); if (index == -1) { throw new RuntimeException(); } index = moduleURL.indexOf("/", index + separator.length()); if (index == -1) { return moduleURL; } return moduleURL.substring(0, index); }
Source:
public void canWaitForLocks() { LockTokenV2 token = CLUSTER.lock(requestFor(LOCK_A, LOCK_B)); Future<?> future = executor.submit( () -> CLUSTER.timelockService().waitForLocks(waitRequestFor(LOCK_A, LOCK_B))); assertNotDone(future); CLUSTER.unlock(token); assertDone(future); }

Target:
public void canWaitForLocks() { LockTokenV2 token = CLUSTER.lock(requestFor(LOCK_A, LOCK_B)); Future<?> future = CLUSTER.waitForLocksAsync(waitRequestFor(LOCK_A, LOCK_B)); assertNotDone(future); CLUSTER.unlock(token); assertDone(future); }
Source:
public void testGetUrl() { try { String url = reservationReportPdfStamperView.getUrl(); assertThat(url, is("classpath:reports/reservationReport.pdf")); } catch (Exception e) { e.printStackTrace(); fail(); } }

Target:
public void testGetUrl() { reservationReportPdfStamperView.reservationReportPdfUrl = "classpath:reports/reservationReport.pdf"; String url = reservationReportPdfStamperView.getUrl(); assertThat(url, is("classpath:reports/reservationReport.pdf")); }
Source:
public static OutputStream makeCipherOutputForStream( final OutputStream httpOut, final SupportedCipherDetails cipherDetails, final Cipher cipher, final HMac hmac) { final CloseShieldOutputStream noCloseOut = new CloseShieldOutputStream(httpOut); final CipherOutputStream cipherOut = new CipherOutputStream(noCloseOut, cipher); final OutputStream out; Validate.notNull(cipherDetails, "Cipher details must not be null"); if (cipherDetails.isAEADCipher()) { out = cipherOut; } else { out = new HmacOutputStream(hmac, cipherOut); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Creating new OutputStream for multipart [{}]", out.getClass()); } return out; }

Target:
public static OutputStream makeCipherOutputForStream( final OutputStream httpOut, final SupportedCipherDetails cipherDetails, final Cipher cipher, final HMac hmac) { final CloseShieldOutputStream noCloseOut = new CloseShieldOutputStream(httpOut); final CipherOutputStream cipherOut = new CipherOutputStream(noCloseOut, cipher); final OutputStream out; Validate.notNull(cipherDetails, "Cipher details must not be null"); Validate.notNull(cipher, "Cipher must not be null"); if (cipherDetails.isAEADCipher()) { out = cipherOut; } else { out = new HmacOutputStream(hmac, cipherOut); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Creating new OutputStream for multipart [{}]", out.getClass()); } return out; }
Source:
public Reply<?> removeOperators(@Named("id")Object id, Request request) { OperatorIdentifiersDTO dto = request.read(OperatorIdentifiersDTO.class).as(Json.class); OperatorIdentifiers ids = adapt(dto); Optional<RoamingGroup> group = repository.findById(id); if (!group.isPresent()) { return Reply.with("Roaming group to which you want to remove operators is undefined.").status(SC_BAD_REQUEST); } repository.remove(id, ids); return Reply.saying().ok(); }

Target:
public Reply<?> removeOperators(@Named("id")Object id, Request request) { List<Object> dtos = request.read(new TypeLiteral<List<Object>>() {}).as(Json.class); List<ID> ids = adaptToID(dtos); repository.removeOperators(new ID(id), ids); return Reply.saying().ok(); }
Source:
public Iterator<Vector3ic> iterator() { Vector3i pos = new Vector3i(); final int[] level = {this.startDistance}; final int[] offset = {-this.startDistance,0,0}; return new Iterator<Vector3ic>() { @Override public boolean hasNext() { return level[0] < endDistance; } @Override public Vector3ic next() { pos.set(origin.x + offset[0], origin.y + offset[1], origin.z + offset[2]); if (offset[2] < 0) { offset[2] *= -1; } else if (offset[1] < 0) { offset[1] *= -1; offset[2] = -(level[0] - TeraMath.fastAbs(offset[0]) - TeraMath.fastAbs(offset[1])); } else { offset[1] = -offset[1] + 1; if (offset[1] > 0) { if (++offset[0] <= level[0]) { offset[1] = TeraMath.fastAbs(offset[0]) - level[0]; offset[2] = 0; } else { level[0]++; offset[0] = -level[0]; offset[1] = 0; offset[2] = 0; } } else { offset[2] = -(level[0] - TeraMath.fastAbs(offset[0]) - TeraMath.fastAbs(offset[1])); } } return pos; } }; }

Target:
public Iterator<Vector3ic> iterator() { Vector3i pos = new Vector3i(); final int[] level = {this.startDistance}; final Vector3i offset = new Vector3i(-this.startDistance,0,0); return new Iterator<Vector3ic>() { @Override public boolean hasNext() { return level[0] < endDistance; } @Override public Vector3ic next() { origin.add(offset, pos); if (offset.z < 0) { offset.z *= -1; } else if (offset.y() < 0) { offset.y *= -1; offset.z = -(level[0] - TeraMath.fastAbs(offset.x()) - TeraMath.fastAbs(offset.y())); } else { offset.y = -offset.y() + 1; if (offset.y > 0) { if (++offset.x <= level[0]) { offset.y = TeraMath.fastAbs(offset.x) - level[0]; offset.z = 0; } else { level[0]++; offset.x = -level[0]; offset.y = 0; offset.z = 0; } } else { offset.z = -(level[0] - TeraMath.fastAbs(offset.x) - TeraMath.fastAbs(offset.y)); } } return pos; } }; }
Source:
private boolean logContains(String msg) { List<LogItem> logs = ShadowLog.getLogs(); boolean found = false; for (LogItem logItem : logs) { if (logItem.msg.startsWith(msg)) found = true; } return found; }

Target:
private static boolean logContains(String msg) { List<LogItem> logs = ShadowLog.getLogs(); boolean found = false; for (LogItem logItem : logs) { if (logItem.msg.startsWith(msg)) found = true; } return found; }
Source:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mMapContainer = (FrameLayout) inflater.inflate(R.layout.map_fragment_layout, null); if (mPortalItemId != null) { loadWebMapIntoMapView(mPortalItemId, mBasemapPortalItemId, AccountManager.getInstance().getPortal()); } else { if (mBasemapPortalItemId != null) { loadWebMapIntoMapView(mBasemapPortalItemId, null, AccountManager.getInstance().getAGOLPortal()); } else { String defaultBaseMapURL = getString(R.string.default_basemap_url); mBasemap = new Basemap(defaultBaseMapURL); mMap = new ArcGISMap(mBasemap); MapFragment.mMapView = mMapContainer.findViewById(R.id.map); MapFragment.mMapView.setMap(mMap); setMapView(MapFragment.mMapView); setClickListenerForFloatingActionButton(MapFragment.mMapView); addGraphicLayers(); mMapView.addViewpointChangedListener(new ViewpointChangedListener() { @Override public void viewpointChanged(ViewpointChangedEvent visibleAreaChangedEvent) { mCompass.setRotationAngle(((MapView)visibleAreaChangedEvent.getSource()).getMapRotation()); } }); } } return mMapContainer; }

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mMapContainer = (FrameLayout) inflater.inflate(R.layout.map_fragment_layout, null); if (mPortalItemId != null) { loadWebMapIntoMapView(mPortalItemId, mBasemapPortalItemId, AccountManager.getInstance().getPortal()); } else { if (mBasemapPortalItemId != null) { loadWebMapIntoMapView(mBasemapPortalItemId, null, AccountManager.getInstance().getAGOLPortal()); } else { String defaultBaseMapURL = getString(R.string.default_basemap_url); mBasemap = new Basemap(defaultBaseMapURL); mMap = new ArcGISMap(mBasemap); mMapView = mMapContainer.findViewById(R.id.map); mMapView.setMap(mMap); setMapView(mMapView); setClickListenerForFloatingActionButton(mMapView); addGraphicLayers(); mMapView.addViewpointChangedListener(new ViewpointChangedListener() { @Override public void viewpointChanged(ViewpointChangedEvent visibleAreaChangedEvent) { mCompass.setRotationAngle(((MapView) visibleAreaChangedEvent.getSource()).getMapRotation()); } }); } } return mMapContainer; }
Source:
public abstract T performTask() throws Throwable; @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void execute() { if (ApiUtil.hasHoneyComb()) { underlyingTask.executeOnExecutor(executor); } else { underlyingTask.execute(); } }

Target:
public abstract T performTask() throws Throwable; public void execute() { underlyingTask.executeOnExecutor(executor); }
Source:
public static String getExtension(String mimetype) { String ext = null; if (mimetype.equalsIgnoreCase("audio/mpeg")) { ext = ".mp3"; } else if (mimetype.equalsIgnoreCase("audio/vnd.dlna.adts")) { ext = ".m4a"; } else if (mimetype.equalsIgnoreCase("audio/wav") ) { ext = ".wav"; } else if (mimetype.equalsIgnoreCase("audio/l16")) { ext = ".l16"; } else if (mimetype.equalsIgnoreCase("video/mpeg") || mimetype.equalsIgnoreCase("video/mp4")) { ext = ".mp4"; } if (ext != null) return ext; List<String> list = null; try { list = MimeTypes.getDefaultMimeTypes().forName(mimetype).getExtensions(); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String extension = (String) iterator.next(); if (extension.length() == 4) { ext = extension; break; } } } catch (MimeTypeException e) { LOGGER.warn("Unknown mime type: {}", mimetype); } return ext; }

Target:
public static String getExtension(String mimetype) { String ext = null; if (mimetype.equalsIgnoreCase("audio/mpeg")) { ext = ".mp3"; } else if (mimetype.equalsIgnoreCase("audio/mp4") || mimetype.equalsIgnoreCase("audio/x-mp4") || mimetype.equalsIgnoreCase("audio/x-m4a")) { ext = ".m4a"; } else if (mimetype.equalsIgnoreCase("audio/x-ogg") || mimetype.equalsIgnoreCase("audio/ogg")) { ext = ".ogg"; } else if (mimetype.equalsIgnoreCase("audio/x-flac") || mimetype.equalsIgnoreCase("audio/flac")) { ext = ".flac"; } else if (mimetype.equalsIgnoreCase("audio/wav") ) { ext = ".wav"; } else if (mimetype.equalsIgnoreCase("audio/l16")) { ext = ".l16"; } else if (mimetype.equalsIgnoreCase("video/mpeg") || mimetype.equalsIgnoreCase("video/mp4")) { ext = ".mp4"; } else if (mimetype.equalsIgnoreCase("video/x-matroska") || mimetype.equalsIgnoreCase("video/x-mkv") || mimetype.equalsIgnoreCase("video/mkv")) { ext = ".mkv"; } else if (mimetype.equalsIgnoreCase("image/webp")) { ext = ".webp"; } if (ext != null) return ext; List<String> list = null; try { list = MimeTypes.getDefaultMimeTypes().forName(mimetype).getExtensions(); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String extension = (String) iterator.next(); if (extension.length() == 4) { ext = extension; break; } } } catch (MimeTypeException e) { LOGGER.warn("Unknown mime type: {}", mimetype); } return ext; }
Source:
public void testOperators() { assertEquals( valueOf(15), valueOf(3).multiply(valueOf(5)) ); assertTrue ( SATOSHI.isPositive() ); assertFalse( SATOSHI.isNegative() ); assertFalse( SATOSHI.isZero() ); assertFalse( NEGATIVE_ONE.isPositive() ); assertTrue ( NEGATIVE_ONE.isNegative() ); assertFalse( NEGATIVE_ONE.isZero() ); assertFalse( ZERO.isPositive() ); assertFalse( ZERO.isNegative() ); assertTrue ( ZERO.isZero() ); assertFalse( Transaction.MIN_NONDUST_OUTPUT.isDust() ); assertTrue ( valueOf(Transaction.MIN_NONDUST_OUTPUT.value - 1).isDust() ); assertTrue ( valueOf(2).isGreaterThan(valueOf(1)) ); assertFalse ( valueOf(2).isGreaterThan(valueOf(2)) ); assertFalse ( valueOf(1).isGreaterThan(valueOf(2)) ); assertTrue ( valueOf(1).isLessThan(valueOf(2)) ); assertFalse ( valueOf(2).isLessThan(valueOf(2)) ); assertFalse ( valueOf(2).isLessThan(valueOf(1)) ); }

Target:
public void testOperators() { assertTrue(SATOSHI.isPositive()); assertFalse(SATOSHI.isNegative()); assertFalse(SATOSHI.isZero()); assertFalse(NEGATIVE_SATOSHI.isPositive()); assertTrue(NEGATIVE_SATOSHI.isNegative()); assertFalse(NEGATIVE_SATOSHI.isZero()); assertFalse(ZERO.isPositive()); assertFalse(ZERO.isNegative()); assertTrue(ZERO.isZero()); assertTrue(valueOf(2).isGreaterThan(valueOf(1))); assertFalse(valueOf(2).isGreaterThan(valueOf(2))); assertFalse(valueOf(1).isGreaterThan(valueOf(2))); assertTrue(valueOf(1).isLessThan(valueOf(2))); assertFalse(valueOf(2).isLessThan(valueOf(2))); assertFalse(valueOf(2).isLessThan(valueOf(1))); }
Source:
public void test() throws Exception { Configuration conf = new Configuration(false); LocalMode lma = LocalMode.newInstance(); DAG dag = lma.getDAG(); super.populateDAG(dag, conf); StreamingApplication app = new StreamingApplication() { @Override public void populateDAG(DAG dag, Configuration conf) { } }; lma.prepareDAG(app, conf); final LocalMode.Controller lc = lma.getController(); lc.run(60000); lc.shutdown(); if (SpillableTestOperator.errorTrace != null) { SpillableTestOperator.errorTrace.printStackTrace(); Assert.assertNull(SpillableTestOperator.errorTrace.getMessage(), SpillableTestOperator.errorTrace); } }

Target:
public void test() throws Exception { Configuration conf = new Configuration(false); LocalMode lma = LocalMode.newInstance(); DAG dag = lma.getDAG(); super.populateDAG(dag, conf); StreamingApplication app = new StreamingApplication() { @Override public void populateDAG(DAG dag, Configuration conf) { } }; lma.prepareDAG(app, conf); final LocalMode.Controller lc = lma.getController(); lc.run(60000); lc.shutdown(); if (SpillableTestOperator.errorTrace != null) { logger.error("Error.", SpillableTestOperator.errorTrace); Assert.assertNull(SpillableTestOperator.errorTrace.getMessage(), SpillableTestOperator.errorTrace); } }
Source:
public Optional<UsernamePasswordCredentials> extract(WebContext context) { final String username = context.getRequestParameter(this.usernameParameter); final String password = context.getRequestParameter(this.passwordParameter); if (username == null || password == null) { return Optional.empty(); } return Optional.of(new UsernamePasswordCredentials(username, password)); }

Target:
public Optional<UsernamePasswordCredentials> extract(WebContext context) { final Optional<String> username = context.getRequestParameter(this.usernameParameter); final Optional<String> password = context.getRequestParameter(this.passwordParameter); if (username.isPresent() && password.isPresent()) { return Optional.of( new UsernamePasswordCredentials(username.get(), password.get()) ); } return Optional.empty(); }
Source:
public void testSystemEnvVarRef() { String[] envvar = findEnvVar(); if (envvar[0].length() == 0) { fail("No environment variables found, can't pass test."); return; } final String envvarValue = envvar[1]; Assert.assertNotNull("Expect non-null env var: "+envvar[0], envvarValue); final String value = "${"+envvar[0]+"}"; assertEquals(envvarValue, resolver.resolve(value)); }

Target:
public void testSystemEnvVarRef() { String[] envvar = findEnvVar(); if (envvar[0].length() == 0) { FoundationTestActivator.getDefault().getLog().log( new Status(IStatus.WARNING, FoundationTestActivator.PLUGIN_ID, ("No environment variables found, can't pass test."))); return; } final String envvarValue = envvar[1]; Assert.assertNotNull("Expect non-null env var: "+envvar[0], envvarValue); final String value = "${"+envvar[0]+"}"; assertEquals(envvarValue, resolver.resolve(value)); }
Source:
public ValidationResult isInProcess() { StoragePoolIsoMap domainIsoMap = storageDomain.getStoragePoolIsoMapData(); if (domainIsoMap.getStatus() != null && domainIsoMap.getStatus().isStorageDomainInProcess()) { new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2, String.format("$status %1$s", StorageDomainStatus.Locked)); } return ValidationResult.VALID; }

Target:
public ValidationResult isInProcess() { StoragePoolIsoMap domainIsoMap = storageDomain.getStoragePoolIsoMapData(); if (domainIsoMap.getStatus() != null && domainIsoMap.getStatus().isStorageDomainInProcess()) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2, String.format("$status %1$s", domainIsoMap.getStatus())); } return ValidationResult.VALID; }
Source:
public int hashCode() { int result = super.hashCode(); result = 31 * result + (scmId != null ? scmId.hashCode() : 0); return result; }

Target:
public int hashCode() { int result = super.hashCode(); result = 31 * result + (this.getFingerprint() != null ? this.getFingerprint().hashCode() : 0); return result; }
Source:
public void testSimple() throws Exception { FileUtils.copyURLToFile( getClass().getResource("main-helloWorld."+ext), new File(app, "main."+ext)); MockHttpServletResponse resp = getAsServletResponse("/rest/apps/foo/main."+ext); assertEquals(200, resp.getStatus()); assertEquals("Hello World!", resp.getContentAsString()); }

Target:
public void testSimple() throws Exception { FileUtils.copyURLToFile( getClass().getResource("main-helloWorld."+ext), new File(app, "main."+ext)); MockHttpServletResponse resp = getAsServletResponse("/script/apps/foo/main."+ext); assertEquals(200, resp.getStatus()); assertEquals("Hello World!", resp.getContentAsString()); }
Source:
public void testRerunFailingErrorTestsWithOneRetry() throws Exception { OutputValidator outputValidator = unpack().setJUnitVersion( VERSION ).maven().addGoal( "-Dsurefire.rerunFailingTestsCount=1" ).withFailure().executeTest().assertTestSuiteResults( 5, 1, 1, 0, 0 ); verifyFailuresOneRetryAllClasses( outputValidator ); outputValidator = unpack().setJUnitVersion( VERSION ).maven().addGoal( "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-DforkCount=2" ).withFailure().executeTest().assertTestSuiteResults( 5, 1, 1, 0, 0 ); verifyFailuresOneRetryAllClasses( outputValidator ); outputValidator = unpack().setJUnitVersion( VERSION ).maven().addGoal( "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-Dparallel=methods" ).addGoal( "-DuseUnlimitedThreads=true" ).withFailure().executeTest().assertTestSuiteResults( 5, 1, 1, 0, 0 ); verifyFailuresOneRetryAllClasses( outputValidator ); outputValidator = unpack().setJUnitVersion( VERSION ).maven().addGoal( "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-Dparallel=classes" ).addGoal( "-DuseUnlimitedThreads=true" ).withFailure().executeTest().assertTestSuiteResults( 5, 1, 1, 0, 0 ); verifyFailuresOneRetryAllClasses( outputValidator ); }

Target:
public void testRerunFailingErrorTestsWithOneRetry() throws Exception { OutputValidator outputValidator = unpack().setJUnitVersion( VERSION ).maven().addGoal( "-Dsurefire.rerunFailingTestsCount=1" ).withFailure().debugLogging().executeTest() .assertTestSuiteResults( 5, 1, 1, 0, 0 ); verifyFailuresOneRetryAllClasses( outputValidator ); outputValidator = unpack().setJUnitVersion( VERSION ).maven().debugLogging().addGoal( "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-DforkCount=2" ).withFailure().executeTest().assertTestSuiteResults( 5, 1, 1, 0, 0 ); verifyFailuresOneRetryAllClasses( outputValidator ); outputValidator = unpack().setJUnitVersion( VERSION ).maven().debugLogging().addGoal( "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-Dparallel=methods" ).addGoal( "-DuseUnlimitedThreads=true" ).withFailure().executeTest().assertTestSuiteResults( 5, 1, 1, 0, 0 ); verifyFailuresOneRetryAllClasses( outputValidator ); outputValidator = unpack().setJUnitVersion( VERSION ).maven().debugLogging().addGoal( "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-Dparallel=classes" ).addGoal( "-DuseUnlimitedThreads=true" ).withFailure().executeTest().assertTestSuiteResults( 5, 1, 1, 0, 0 ); verifyFailuresOneRetryAllClasses( outputValidator ); }
Source:
protected boolean addIfNotPresent(Privilege[] privileges) { ArrayList<Privilege> list = new ArrayList(); list.addAll(Arrays.asList(this.privileges)); boolean res = combineRecursively(list, privileges); this.privileges = new Privilege[list.size()]; list.toArray(this.privileges); return res; }

Target:
protected boolean addIfNotPresent(Privilege[] privileges) { ArrayList<Privilege> list = new ArrayList(); for (Privilege privilege : privileges) { list.add(privilege); } boolean res = combineRecursively(list, privileges); this.privileges.addAll(list); return res; }
Source:
protected void postConnect(OneTimeCallback callback) throws ClientConnectionException { try { final int interestedOps = SelectionKey.OP_READ; reactor.wakeup(); final ReactorClient client = this; final FutureTask<SelectionKey> task = scheduleTask(new Retryable<SelectionKey>( new Callable<SelectionKey>() { @Override public SelectionKey call() throws ClosedChannelException { return channel.register(selector, interestedOps, client); } }, this.policy)); key = task.get(); } catch (InterruptedException | ExecutionException e) { throw new ClientConnectionException(e); } if (key == null) { throw new ClientConnectionException("Connection issue during post connect"); } }

Target:
protected void postConnect(OneTimeCallback callback) throws ClientConnectionException { try { final ReactorClient client = this; final FutureTask<SelectionKey> task = scheduleTask(new Retryable<SelectionKey>( new Callable<SelectionKey>() { @Override public SelectionKey call() throws ClosedChannelException { return channel.register(selector, SelectionKey.OP_READ, client); } }, this.policy)); key = task.get(); } catch (InterruptedException | ExecutionException e) { throw new ClientConnectionException(e); } if (key == null) { throw new ClientConnectionException("Connection issue during post connect"); } }
Source:
private void lockFileForDeletion(File f) throws IOException, InterruptedException { assert !unlockFileCallables.containsKey(f) : f + " is already locked." ; assert Functions.isWindows(); final FileChannel channel = FileChannel.open(f.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE); final FileLock lock = channel.lock(); unlockFileCallables.put(f, new Callable<Void>() { public Void call() throws IOException { lock.release(); channel.close(); return null; }; }); }

Target:
private void lockFileForDeletion(File f) throws IOException, InterruptedException { assert !unlockFileCallables.containsKey(f) : f + " is already locked." ; assert Functions.isWindows(); final InputStream s = new FileInputStream(f); unlockFileCallables.put(f, new Callable<Void>() { public Void call() throws IOException { s.close(); return null; }; }); }
Source:
public View getView(String name) { for (View v : views) { if (v.getViewName().equals(name)) return v; if (v instanceof ViewGroup) { View nestedView = ((ViewGroup) v).getView(name); if (nestedView != null) { return nestedView; } } } return null; }

Target:
public View getView(String name) { for (View v : views) { if (v.getViewName().equals(name)) { return v; } } for (View v : views) { if (v instanceof ViewGroup) { View nestedView = ((ViewGroup) v).getView(name); if (nestedView != null) { return nestedView; } } } return null; }
Source:
public void canFetchReadmeFileFromSpecifiedBranch() throws IOException { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple(HttpURLConnection.HTTP_OK, "{\"name\": \"README.md\"}") ).start(); final Contents contents = new RtContents( new ApacheRequest(container.home()), RtContentsTest.repo()); MatcherAssert.assertThat( contents.readme("somebranch"), Matchers.notNullValue() ); container.stop(); }

Target:
public void canFetchReadmeFileFromSpecifiedBranch() throws IOException { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple( HttpURLConnection.HTTP_OK, "{\"name\": \"README.md\"}" ) ).start(); final Contents contents = new RtContents( new ApacheRequest(container.home()), RtContentsTest.repo() ); try { MatcherAssert.assertThat( contents.readme("somebranch"), Matchers.notNullValue() ); } finally { container.stop(); } }
Source:
public List<KeyRange> generateSplitRanges(int maxConcurrency) { List<KeyRange> splits = Lists.newArrayListWithCapacity(estimateSplitNum); int[] position = new int[slots.size()]; byte[] lowerBoundKey = new byte[maxKeyLength]; byte[] upperBoundKey = new byte[maxKeyLength]; int step = (int) Math.ceil(((double) estimateSplitNum) / maxConcurrency) - 1; boolean terminated = false, lowerInclusive; while (true) { setKey(Bound.LOWER, position, lowerBoundKey, 0, 0, position.length); lowerInclusive = ScanUtil.isKeyInclusive(Bound.LOWER, position, slots); terminated = !ScanUtil.incrementKey(slots, position, step, Bound.UPPER); if (!terminated) { setKey(Bound.UPPER, position, upperBoundKey, 0, 0, position.length); } else { for (int i=0; i<slots.size(); i++) { position[i] = slots.get(i).size() - 1; } setKey(Bound.UPPER, position, upperBoundKey, 0, 0, position.length); } KeyRange range = KeyRange.getKeyRange( Arrays.copyOf(lowerBoundKey, lowerBoundKey.length), lowerInclusive, Arrays.copyOf(upperBoundKey, upperBoundKey.length), false); splits.add(range); terminated = terminated || !ScanUtil.incrementKey(slots, position, 1, Bound.LOWER); if (terminated) break; } return splits; }

Target:
public List<KeyRange> generateSplitRanges(int maxConcurrency) { List<KeyRange> splits = Lists.newArrayListWithCapacity(estimateSplitNum); int[] position = new int[slots.size()]; byte[] lowerBoundKey = new byte[maxKeyLength]; byte[] upperBoundKey = new byte[maxKeyLength]; int step = (int) Math.ceil(((double) estimateSplitNum) / maxConcurrency) - 1; boolean terminated = false, lowerInclusive; while (!terminated) { setKey(Bound.LOWER, position, lowerBoundKey, 0, 0, position.length); lowerInclusive = ScanUtil.isKeyInclusive(Bound.LOWER, position, slots); terminated = !ScanUtil.incrementKey(slots, position, step, Bound.UPPER); if (!terminated) { setKey(Bound.UPPER, position, upperBoundKey, 0, 0, position.length); } else { for (int i=0; i<slots.size(); i++) { position[i] = slots.get(i).size() - 1; } setKey(Bound.UPPER, position, upperBoundKey, 0, 0, position.length); } KeyRange range = KeyRange.getKeyRange( Arrays.copyOf(lowerBoundKey, lowerBoundKey.length), lowerInclusive, Arrays.copyOf(upperBoundKey, upperBoundKey.length), false); splits.add(range); terminated = terminated || !ScanUtil.incrementKey(slots, position, 1, Bound.LOWER); } return splits; }
Source:
public void contextDestroyed(ServletContextEvent sce) { LOGGER.info("(\"*****************************************************WPSJobListener - context destroyed, cancelling request tasks"); for (Runnable runnable : RequestHandler.pool.getQueue()) { ((FutureTask) runnable).cancel(true); LOGGER.info("cancelling task"); } }

Target:
public void contextDestroyed(ServletContextEvent sce) { for (Runnable runnable : RequestHandler.pool.getQueue()) { ((FutureTask) runnable).cancel(true); LOGGER.info("cancelling task"); } }
Source:
public static InetAddress getLocalLoopbackAddress() { try { final Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); while (ifaces.hasMoreElements()) { final NetworkInterface iface = ifaces.nextElement(); if (iface.isLoopback() && iface.isUp() && !iface.isVirtual()) { final Enumeration<InetAddress> addrs = iface.getInetAddresses(); while (addrs.hasMoreElements()) { final InetAddress addr = addrs.nextElement(); if (addr instanceof Inet4Address && !addr.isMulticastAddress() && (addr.isLinkLocalAddress() || addr.isLoopbackAddress() || addr.isAnyLocalAddress())) { return addr; } } } } } catch (final Exception e) { LOG.warn("getLocalLoopbackAddress: an exception occurred while attempting to determine the local loopback address.",e); } return null; }

Target:
public static Optional<InetAddress> getLocalLoopbackAddress() { try { final List<InetAddress> loopbackAddresses = new ArrayList<>(); final Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); while (ifaces.hasMoreElements()) { final NetworkInterface iface = ifaces.nextElement(); if (iface.isLoopback() && iface.isUp() && !iface.isVirtual()) { final Enumeration<InetAddress> addrs = iface.getInetAddresses(); while (addrs.hasMoreElements()) { final InetAddress addr = addrs.nextElement(); if (!addr.isMulticastAddress() && (addr.isLinkLocalAddress() || addr.isLoopbackAddress() || addr.isAnyLocalAddress())) { loopbackAddresses.add(addr); } } } } if (!loopbackAddresses.isEmpty()) { loopbackAddresses.sort(IFACE_COMPARATOR); return Optional.of(loopbackAddresses.get(0)); } } catch (final Exception e) { LOG.warn("getLocalLoopbackAddress: an exception occurred while attempting to determine the local loopback address.",e); } return Optional.empty(); }
Source:
private void filterBufferAndResetBackgroundFetch(Set<StreamPartition<String>> partitions) throws InterruptedException { checkIfClosed(); if (partitionsFetchStarted.compareAndSet(true, false)) { scheduledExec.shutdown(); try { if (!scheduledExec.awaitTermination(EXCEPTION_RETRY_DELAY_MS, TimeUnit.MILLISECONDS)) { scheduledExec.shutdownNow(); } } catch (InterruptedException e) { log.warn(e, "InterruptedException while shutting down"); throw e; } scheduledExec = Executors.newScheduledThreadPool( fetchThreads, Execs.makeThreadFactory("KinesisRecordSupplier-Worker-%d") ); } BlockingQueue<OrderedPartitionableRecord<String, String>> newQ = new LinkedBlockingQueue<>(recordBufferSize); records.stream() .filter(x -> !partitions.contains(x.getStreamPartition())) .forEachOrdered(newQ::offer); records = newQ; partitionResources.values().forEach(x -> x.stopBackgroundFetch()); }

Target:
private void filterBufferAndResetBackgroundFetch(Set<StreamPartition<String>> partitions) throws InterruptedException { checkIfClosed(); if (backgroundFetchEnabled && partitionsFetchStarted.compareAndSet(true, false)) { scheduledExec.shutdown(); try { if (!scheduledExec.awaitTermination(EXCEPTION_RETRY_DELAY_MS, TimeUnit.MILLISECONDS)) { scheduledExec.shutdownNow(); } } catch (InterruptedException e) { log.warn(e, "InterruptedException while shutting down"); throw e; } scheduledExec = Executors.newScheduledThreadPool( fetchThreads, Execs.makeThreadFactory("KinesisRecordSupplier-Worker-%d") ); } BlockingQueue<OrderedPartitionableRecord<String, String>> newQ = new LinkedBlockingQueue<>(recordBufferSize); records.stream() .filter(x -> !partitions.contains(x.getStreamPartition())) .forEachOrdered(newQ::offer); records = newQ; partitionResources.values().forEach(x -> x.stopBackgroundFetch()); }
Source:
protected Function<Filter, Predicate<DigitalExchangePageModelDto>> getPredicates() { return (filter) -> { switch (filter.getAttribute()) { case CODE: return p -> FilterUtils.filterString(filter, p::getCode); case DESCRIPTION: return p -> FilterUtils.filterString(filter, p::getDescr); case MAIN_FRAME: return p -> FilterUtils.filterInt(filter, p::getMainFrame); case PLUGIN_CODE: return p -> FilterUtils.filterString(filter, p::getPluginCode); case TEMPLATE: return p -> FilterUtils.filterString(filter, p::getTemplate); case DIGITAL_EXCHANGE: return p -> FilterUtils.filterString(filter, p::getDigitalExchange); } return null; }; }

Target:
protected Function<Filter, Predicate<DigitalExchangePageModelDto>> getPredicates() { return (filter) -> { switch (filter.getAttribute()) { case CODE: return p -> FilterUtils.filterString(filter, p::getCode); case DESCRIPTION: return p -> FilterUtils.filterString(filter, p::getDescr); case MAIN_FRAME: return p -> FilterUtils.filterInt(filter, p::getMainFrame); case PLUGIN_CODE: return p -> FilterUtils.filterString(filter, p::getPluginCode); case TEMPLATE: return p -> FilterUtils.filterString(filter, p::getTemplate); case DIGITAL_EXCHANGE: return p -> FilterUtils.filterString(filter, p::getDigitalExchange); default: return null; } }; }