auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<EndpointRegistryInfo> getEndpointRegistries(String tenantDomain) throws EndpointRegistryException { int tenantId; try { tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() .getTenantId(tenantDomain); if (!registryDAO.isEndpointRegistryTypeExists(EndpointRegistryConstants.REGISTRY_TYPE_WSO2, tenantId) && !registryDAO.isEndpointRegistryNameExists(EndpointRegistryConstants.DEFAULT_REGISTRY_NAME, tenantId)) { EndpointRegistryInfo defaultRegistry = new EndpointRegistryInfo(); defaultRegistry.setName(EndpointRegistryConstants.DEFAULT_REGISTRY_NAME); defaultRegistry.setType(EndpointRegistryConstants.REGISTRY_TYPE_WSO2); defaultRegistry.setOwner(EndpointRegistryConstants.SYSTEM_USER_NAME); String regId = registryDAO.addEndpointRegistry(defaultRegistry, tenantId); log.info("Successfully created the default endpoint registry " + defaultRegistry.getName() + " of type :" + defaultRegistry.getType() + " with id :" + regId + " by :" + EndpointRegistryConstants.SYSTEM_USER_NAME); } List<EndpointRegistryInfo> endpointRegistryInfoList = new ArrayList<>(); EndpointRegistryInfo endpointRegistryInfo = registryDAO.getEndpointRegistry(tenantId); if (endpointRegistryInfo != null) { endpointRegistryInfoList.add(endpointRegistryInfo); } return endpointRegistryInfoList; } catch (UserStoreException e) { String msg = "Error while retrieving tenant information"; log.error(msg, e); throw new EndpointRegistryException("Error in retrieving Tenant Information while retrieving details of " + "endpoint registries", e); } }

Target:
public List<EndpointRegistryInfo> getEndpointRegistries(String tenantDomain) throws EndpointRegistryException { int tenantId; try { tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() .getTenantId(tenantDomain); EndpointRegistryInfo endpointRegistryInfo = registryDAO.getEndpointRegistry(tenantId); if (endpointRegistryInfo == null) { EndpointRegistryInfo defaultRegistry = new EndpointRegistryInfo(); defaultRegistry.setName(EndpointRegistryConstants.DEFAULT_REGISTRY_NAME); defaultRegistry.setType(EndpointRegistryConstants.REGISTRY_TYPE_WSO2); defaultRegistry.setOwner(EndpointRegistryConstants.SYSTEM_USER_NAME); String regId = registryDAO.addEndpointRegistry(defaultRegistry, tenantId); log.info("Successfully created the default endpoint registry " + defaultRegistry.getName() + " of type :" + defaultRegistry.getType() + " with id :" + regId + " by :" + EndpointRegistryConstants.SYSTEM_USER_NAME); endpointRegistryInfo = registryDAO.getEndpointRegistry(tenantId); } List<EndpointRegistryInfo> endpointRegistryInfoList = new ArrayList<>(); if (endpointRegistryInfo != null) { endpointRegistryInfoList.add(endpointRegistryInfo); } return endpointRegistryInfoList; } catch (UserStoreException e) { String msg = "Error while retrieving tenant information"; log.error(msg, e); throw new EndpointRegistryException("Error in retrieving Tenant Information while retrieving details of " + "endpoint registries", e); } }
Source:
private boolean isPropertyInvalid(Property property, Task task) { if ((property.getValue() == null || property.getValue().equals(""))) { List<String> parameter = new ArrayList<>(); parameter.add(property.getTitle()); parameter.add(task.getProcess().getTitle()); Helper.setFehlerMeldung(Helper.getTranslation("BatchPropertyEmpty", parameter)); return true; } return false; }

Target:
private boolean isPropertyInvalid(Property property, Task task) { if (property.getValue() == null || property.getValue().equals("")) { List<String> parameter = new ArrayList<>(); parameter.add(property.getTitle()); parameter.add(task.getProcess().getTitle()); Helper.setFehlerMeldung(Helper.getTranslation("BatchPropertyEmpty", parameter)); return true; } return false; }
Source:
public void checkPermissionsRespectUmask() throws IOException, InterruptedException { final File newFile = tmp.newFile(); boolean posixSupported = isPosixSupported(newFile); assumeThat(posixSupported, is(true)); Path filePath = newFile.toPath(); AtomicFileWriter w = new AtomicFileWriter(filePath, StandardCharsets.UTF_8); w.write("whatever"); w.commit(); assertFalse(w.getTemporaryPath().toFile().exists()); assertTrue(filePath.toFile().exists()); final Set<PosixFilePermission> posixFilePermissions = Files.getPosixFilePermissions(filePath); for (PosixFilePermission perm : DEFAULT_GIVEN_PERMISSIONS) { assertTrue("missing expected permission: " + perm, posixFilePermissions.contains(perm)); } }

Target:
public void checkPermissionsRespectUmask() throws IOException, InterruptedException { final File newFile = tmp.newFile(); boolean posixSupported = isPosixSupported(newFile); assumeThat(posixSupported, is(true)); Path filePath = newFile.toPath(); AtomicFileWriter w = new AtomicFileWriter(filePath, StandardCharsets.UTF_8); w.write("whatever"); w.commit(); assertFalse(w.getTemporaryPath().toFile().exists()); assertTrue(filePath.toFile().exists()); assertThat(Files.getPosixFilePermissions(filePath), equalTo(DEFAULT_GIVEN_PERMISSIONS)); }
Source:
public void onEventMainThread(DiscussionThreadPostedEvent event) { DiscussionThread newThread = event.getDiscussionThread(); if (discussionTopic.containsThread(newThread)) { if (postsFilter == DiscussionPostsFilter.UNANSWERED && newThread.getType() != DiscussionThread.ThreadType.QUESTION) { return; } int i = 0; for (; i < discussionPostsAdapter.getCount(); ++i) { if (!discussionPostsAdapter.getItem(i).isPinned()) { break; } } discussionPostsAdapter.insert(newThread, i); discussionPostsListView.setSelection(i); setScreenStateUponResult(null); spinnersContainerLayout.setVisibility(View.VISIBLE); } }

Target:
public void onEventMainThread(DiscussionThreadPostedEvent event) { DiscussionThread newThread = event.getDiscussionThread(); if (discussionTopic.containsThread(newThread)) { if (postsFilter == DiscussionPostsFilter.UNANSWERED && newThread.getType() != DiscussionThread.ThreadType.QUESTION) { return; } int i = 0; for (; i < discussionPostsAdapter.getCount(); ++i) { if (!discussionPostsAdapter.getItem(i).isPinned()) { break; } } discussionPostsAdapter.insert(newThread, i); discussionPostsListView.setSelection(i); setScreenStateUponResult(); } }
Source:
public Optional<Text> getShortDescription(CommandSource source) { return Optional.fromNullable(this.description); }

Target:
public Optional<Text> getShortDescription(CommandSource source) { return this.description; }
Source:
public void abortScheduling(String requestId) { if(trace) { log.tracef("Request[%s] abort scheduling", requestId); } ScheduledRequest scheduledRequest = scheduledRequests.get(requestId); if (scheduledRequest != null && scheduledRequest.request.isDone()) { scheduledRequest.scheduledFuture.cancel(false); scheduledRequests.remove(requestId); } }

Target:
public void abortScheduling(String requestId) { abortScheduling(requestId, false); }
Source:
public CompletionStage<Void> rollback(LocalTransaction localTransaction) { try { return CompletionStages.handleAndCompose(rollbackInternal(icf.running().createTxInvocationContext(localTransaction)), (ignore, t) -> { if (t != null) { return handleRollbackFailure(t, localTransaction); } return CompletableFutures.completedNull(); }); } catch (Throwable e) { return handleRollbackFailure(e, localTransaction); } }

Target:
public CompletionStage<Void> rollback(LocalTransaction localTransaction) { return CompletionStages.handleAndCompose(rollbackInternal(icf.running().createTxInvocationContext(localTransaction)), (ignore, t) -> { if (t != null) { return handleRollbackFailure(t, localTransaction); } return CompletableFutures.completedNull(); }); }
Source:
public void testDomainLifecycleMethods() throws Throwable { DomainClient client = domainMasterLifecycleUtil.getDomainClient(); executeLifecycleOperation(client, null, START_SERVERS, true); waitUntilState(client, "master", "main-one", "STARTED"); waitUntilState(client, "master", "main-two", "STARTED"); waitUntilState(client, "master", "other-one", "STARTED"); waitUntilState(client, "slave", "main-three", "STARTED"); waitUntilState(client, "slave", "failure-one", "STARTED"); waitUntilState(client, "slave", "failure-two", "DISABLED"); waitUntilState(client, "slave", "failure-three", "DISABLED"); executeLifecycleOperation(client, null, STOP_SERVERS, false); waitUntilState(client, "master", "main-one", "STOPPED"); waitUntilState(client, "master", "main-two", "DISABLED"); waitUntilState(client, "master", "other-one", "DISABLED"); waitUntilState(client, "slave", "main-three", "STOPPED"); waitUntilState(client, "slave", "failure-two", "DISABLED"); waitUntilState(client, "slave", "failure-three", "DISABLED"); validateResponse(startServer(client, "master", "main-one")); ModelNode result = validateFailedResponse(startServer(client, "slave", "failure-two")); String failureDescription = result.asString(); Assert.assertTrue(failureDescription.contains("IllegalStateException")); Assert.assertTrue(failureDescription.contains("Java home")); Assert.assertTrue(failureDescription.contains("does not exist")); result = validateFailedResponse(startServer(client, "slave", "failure-three")); failureDescription = result.asString(); Assert.assertTrue(failureDescription.contains("IllegalStateException")); Assert.assertTrue(failureDescription.contains("Java home")); Assert.assertTrue(failureDescription.contains("does not exist")); }

Target:
public void testDomainLifecycleMethods() throws Throwable { DomainClient client = domainMasterLifecycleUtil.getDomainClient(); executeLifecycleOperation(client, null, START_SERVERS); waitUntilState(client, "master", "main-one", "STARTED"); waitUntilState(client, "master", "main-two", "STARTED"); waitUntilState(client, "master", "other-one", "STARTED"); waitUntilState(client, "slave", "main-three", "STARTED"); waitUntilState(client, "slave", "failure-one", "STARTED"); waitUntilState(client, "slave", "failure-two", "FAILED"); waitUntilState(client, "slave", "failure-three", "FAILED"); executeLifecycleOperation(client, null, STOP_SERVERS); waitUntilState(client, "master", "main-one", "STOPPED"); waitUntilState(client, "master", "main-two", "DISABLED"); waitUntilState(client, "master", "other-one", "DISABLED"); waitUntilState(client, "slave", "main-three", "STOPPED"); waitUntilState(client, "slave", "failure-two", "DISABLED"); waitUntilState(client, "slave", "failure-three", "DISABLED"); validateResponse(startServer(client, "master", "main-one")); ModelNode result = validateResponse(startServer(client, "slave", "failure-two")); Assert.assertThat(result.asString(), is("FAILED")); result = validateResponse(startServer(client, "slave", "failure-three")); Assert.assertThat(result.asString(), is("FAILED")); }
Source:
public void publishJobModel(JobModel prevJM, JobModel currJM, String prevJMV, String currJMV, String leaseId) { try { JobModelBundle bundle = new JobModelBundle(prevJM, currJM, prevJMV, currJMV); byte[] data = SamzaObjectMapper.getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsBytes(bundle); byte[] pageData = Arrays.copyOf(data, (int) JOB_MODEL_BLOCK_SIZE); InputStream is = new ByteArrayInputStream(pageData); blob.uploadPages(is, 0, JOB_MODEL_BLOCK_SIZE, AccessCondition.generateLeaseCondition(leaseId), null, null); LOG.info("Uploaded jobModel to blob", bundle.getCurrJobModel()); } catch (Exception e) { LOG.error("JobModel publish failed for version = " + currJMV, new SamzaException(e)); } }

Target:
public boolean publishJobModel(JobModel prevJM, JobModel currJM, String prevJMV, String currJMV, String leaseId) { try { if (leaseId == null) { return false; } JobModelBundle bundle = new JobModelBundle(prevJM, currJM, prevJMV, currJMV); byte[] data = SamzaObjectMapper.getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsBytes(bundle); byte[] pageData = Arrays.copyOf(data, (int) JOB_MODEL_BLOCK_SIZE); InputStream is = new ByteArrayInputStream(pageData); blob.uploadPages(is, 0, JOB_MODEL_BLOCK_SIZE, AccessCondition.generateLeaseCondition(leaseId), null, null); LOG.info("Uploaded jobModel to blob", bundle.getCurrJobModel()); return true; } catch (StorageException | IOException e) { LOG.error("JobModel publish failed for version = " + currJMV, e); return false; } }
Source:
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.register_email_layout, container, false); mPasswordFieldValidator = new PasswordFieldValidator( (TextInputLayout) v.findViewById(R.id.password_layout), getResources().getInteger(R.integer.min_password_length)); mNameValidator = new RequiredFieldValidator( (TextInputLayout) v.findViewById(R.id.name_layout)); mEmailFieldValidator = new EmailFieldValidator( (TextInputLayout) v.findViewById(R.id.email_layout)); mEmailEditText = (EditText) v.findViewById(R.id.email); mNameEditText = (EditText) v.findViewById(R.id.name); mPasswordEditText = (EditText) v.findViewById(R.id.password); mAgreementText = (TextView) v.findViewById(R.id.create_account_text); mEmailInput = (TextInputLayout) v.findViewById(R.id.email_layout); mPasswordInput = (TextInputLayout) v.findViewById(R.id.password_layout); mEmailEditText.setOnFocusChangeListener(this); mNameEditText.setOnFocusChangeListener(this); mPasswordEditText.setOnFocusChangeListener(this); v.findViewById(R.id.button_create).setOnClickListener(this); String email = getArguments().getString(ExtraConstants.EXTRA_EMAIL); if (!TextUtils.isEmpty(email)) { mEmailEditText.setText(email); mNameEditText.requestFocus(); } String name = getArguments().getString(ExtraConstants.EXTRA_NAME); if (!TextUtils.isEmpty(name)) { mNameEditText.setText(name); mPasswordEditText.requestFocus(); } return v; }

Target:
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.register_email_layout, container, false); mPasswordFieldValidator = new PasswordFieldValidator( (TextInputLayout) v.findViewById(R.id.password_layout), getResources().getInteger(R.integer.min_password_length)); mNameValidator = new RequiredFieldValidator( (TextInputLayout) v.findViewById(R.id.name_layout)); mEmailFieldValidator = new EmailFieldValidator( (TextInputLayout) v.findViewById(R.id.email_layout)); mEmailEditText = (EditText) v.findViewById(R.id.email); mNameEditText = (EditText) v.findViewById(R.id.name); mPasswordEditText = (EditText) v.findViewById(R.id.password); mAgreementText = (TextView) v.findViewById(R.id.create_account_text); mEmailInput = (TextInputLayout) v.findViewById(R.id.email_layout); mPasswordInput = (TextInputLayout) v.findViewById(R.id.password_layout); mEmailEditText.setOnFocusChangeListener(this); mNameEditText.setOnFocusChangeListener(this); mPasswordEditText.setOnFocusChangeListener(this); v.findViewById(R.id.button_create).setOnClickListener(this); if (savedInstanceState != null) { return v; } String email = mUser.getEmail(); if (!TextUtils.isEmpty(email)) { mEmailEditText.setText(email); } String name = mUser.getName(); if (!TextUtils.isEmpty(name)) { mNameEditText.setText(name); } if (!TextUtils.isEmpty(mNameEditText.getText())) { safeRequestFocus(mPasswordEditText); } else if (!TextUtils.isEmpty(mEmailEditText.getText())) { safeRequestFocus(mNameEditText); } else { safeRequestFocus(mEmailEditText); } return v; }
Source:
protected void runWithPartitionScanForNative() { EntryOperator operator = operator(this, backupProcessor, getPredicate()); Queue<Object> outComes = new LinkedList<>(); recordStore.forEach((key, record) -> { Data dataKey = toHeapData(key); operator.operateOnKey(dataKey); EntryEventType eventType = operator.getEventType(); if (eventType != null) { outComes.add(dataKey); outComes.add(operator.getOldValue()); outComes.add(operator.getByPreferringDataNewValue()); outComes.add(eventType); } }, true); if (!isEmpty(outComes)) { do { Data dataKey = (Data) outComes.poll(); Object oldValue = outComes.poll(); Object newValue = outComes.poll(); EntryEventType eventType = (EntryEventType) outComes.poll(); operator.init(dataKey, oldValue, newValue, null, eventType, null) .doPostOperateOps(); } while (!outComes.isEmpty()); } }

Target:
protected void runWithPartitionScanForNative() { EntryOperator operator = operator(this, backupProcessor, getPredicate()); Queue<Object> outComes = new LinkedList<>(); recordStore.forEach((key, record) -> { Data dataKey = toHeapData(key); operator.operateOnKey(dataKey); EntryEventType eventType = operator.getEventType(); if (eventType != null) { outComes.add(dataKey); outComes.add(operator.getOldValue()); outComes.add(operator.getByPreferringDataNewValue()); outComes.add(eventType); } }, true); while (!outComes.isEmpty()) { Data dataKey = (Data) outComes.poll(); Object oldValue = outComes.poll(); Object newValue = outComes.poll(); EntryEventType eventType = (EntryEventType) outComes.poll(); operator.init(dataKey, oldValue, newValue, null, eventType, null) .doPostOperateOps(); } }
Source:
public static void asyncDeleteFullPathOptimistic(final ZooKeeper zk, final String originalPath, int znodeVersion, final AsyncCallback.VoidCallback callback, final String leafNodePath) { zk.delete(originalPath, znodeVersion, new VoidCallback() { @Override public void processResult(int rc, String path, Object ctx) { if (rc == Code.OK.intValue()) { String parent = new File(originalPath).getParent().replace("\\", "/"); zk.getData(parent, false, (dRc, dPath, dCtx, data, stat) -> { if (Code.OK.intValue() == dRc && (stat != null && stat.getNumChildren() == 0)) { asyncDeleteFullPathOptimistic(zk, parent, -1, callback, leafNodePath); } else { if (path.equals(leafNodePath)) { callback.processResult(rc, path, leafNodePath); } else { callback.processResult(Code.OK.intValue(), path, leafNodePath); } } }, null); } else { if (path.equals(leafNodePath)) { callback.processResult(rc, path, leafNodePath); } else { callback.processResult(Code.OK.intValue(), path, leafNodePath); } } } }, leafNodePath); }

Target:
public static void asyncDeleteFullPathOptimistic(final ZooKeeper zk, final String originalPath, int znodeVersion, final AsyncCallback.VoidCallback callback, final String leafNodePath) { zk.delete(originalPath, znodeVersion, new VoidCallback() { @Override public void processResult(int rc, String path, Object ctx) { if (rc == Code.OK.intValue()) { String parent = new File(originalPath).getParent().replace("\\", "/"); zk.getData(parent, false, (dRc, dPath, dCtx, data, stat) -> { if (Code.OK.intValue() == dRc && (stat != null && stat.getNumChildren() == 0)) { asyncDeleteFullPathOptimistic(zk, parent, -1, callback, leafNodePath); } else { callback.processResult(Code.OK.intValue(), path, leafNodePath); } }, null); } else { if (path.equals(leafNodePath)) { callback.processResult(rc, path, leafNodePath); } else { callback.processResult(Code.OK.intValue(), path, leafNodePath); } } } }, leafNodePath); }
Source:
public void generateValidMoves() { validMoves = new String[operations]; for (int i = 0; i < operations; i++) { validMoves[i] = "v_" + i; } print("Valid moves ready"); }

Target:
private String[] generateValidMoves() { String[] validMoves = new String[operations]; for (int i = 0; i < operations; i++) { validMoves[i] = "v_" + i; } print("Valid moves ready"); return validMoves; }
Source:
public void addQueueListener(QueueListener queueListener) { if (!queueListeners.contains(queueListener)) { queueListeners.add(queueListener); } }

Target:
public void addQueueListener(QueueListener queueListener) { queueListeners.add(queueListener); }
Source:
private static String readTarContents(String archiveFile) throws FileNotFoundException, IOException { StringBuffer sb = new StringBuffer(); TarArchiveInputStream archive = new TarArchiveInputStream( new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(archiveFile)))); TarArchiveEntry entry; while ((entry = archive.getNextTarEntry()) != null) { sb.append(entry.getName()); } return sb.toString(); }

Target:
public static String readTarContents(String archiveFile) throws FileNotFoundException, IOException { StringBuffer sb = new StringBuffer(); BufferedReader br = null; TarArchiveInputStream archiveInputStream = null; try { archiveInputStream = new TarArchiveInputStream( new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(archiveFile)))); TarArchiveEntry entry = archiveInputStream.getNextTarEntry(); while (entry != null) { br = new BufferedReader(new InputStreamReader(archiveInputStream)); String line; while ((line = br.readLine()) != null) { sb.append(line); } entry = archiveInputStream.getNextTarEntry(); } } finally { archiveInputStream.close(); br.close(); } return sb.toString(); }
Source:
public void stop(BundleContext context) throws Exception { shutdownActiveLaunches(); plugin = null; super.stop(context); fgBundleContext = null; if (fMemoryRetrievalFactory != null) { Platform.getAdapterManager().unregisterAdapters(fMemoryRetrievalFactory, IDMContext.class); } }

Target:
public void stop(BundleContext context) throws Exception { shutdownActiveLaunches(); plugin = null; if (fMemoryRetrievalFactory != null) { Platform.getAdapterManager().unregisterAdapters(fMemoryRetrievalFactory, IDMContext.class); } super.stop(context); fgBundleContext = null; }
Source:
public void accept(Observer<? super T> observer) { switch (kind) { case OnNext: observer.onNext(getValue()); break; case OnError: observer.onError(getThrowable()); break; case OnCompleted: observer.onCompleted(); break; default: break; } }

Target:
public void accept(Observer<? super T> observer) { switch (kind) { case OnNext: observer.onNext(getValue()); break; case OnError: observer.onError(getThrowable()); break; case OnCompleted: observer.onCompleted(); break; default: throw new AssertionError("Uncovered case: " + kind); } }
Source:
public HttpRequest setUri(String uri) { ObjectUtil.checkNotNull(uri, "uri"); this.uri = uri; return this; }

Target:
public HttpRequest setUri(String uri) { this.uri = ObjectUtil.checkNotNull(uri, "uri"); return this; }
Source:
NavDeepLink(@NonNull String uri) { StringBuilder uriRegex = new StringBuilder("^"); if (!SCHEME_PATTERN.matcher(uri).find()) { uriRegex.append("http[s]?://"); } Pattern fillInPattern = Pattern.compile("\\{(.+?)\\}"); Matcher matcher = fillInPattern.matcher(uri); int appendPos = 0; while (matcher.find()) { String argName = matcher.group(1); mArguments.add(argName); uriRegex.append(Pattern.quote(uri.substring(appendPos, matcher.start())) .replace(".*", "\\E.*\\Q")); uriRegex.append("(.+?)"); appendPos = matcher.end(); } if (appendPos < uri.length()) { uriRegex.append(Pattern.quote(uri.substring(appendPos)) .replace(".*", "\\E.*\\Q")); } mPattern = Pattern.compile(uriRegex.toString()); }

Target:
NavDeepLink(@NonNull String uri) { StringBuilder uriRegex = new StringBuilder("^"); if (!SCHEME_PATTERN.matcher(uri).find()) { uriRegex.append("http[s]?://"); } Pattern fillInPattern = Pattern.compile("\\{(.+?)\\}"); Matcher matcher = fillInPattern.matcher(uri); int appendPos = 0; while (matcher.find()) { String argName = matcher.group(1); mArguments.add(argName); uriRegex.append(Pattern.quote(uri.substring(appendPos, matcher.start()))); uriRegex.append("(.+?)"); appendPos = matcher.end(); } if (appendPos < uri.length()) { uriRegex.append(Pattern.quote(uri.substring(appendPos))); } String finalRegex = uriRegex.toString().replace(".*", "\\E.*\\Q"); mPattern = Pattern.compile(finalRegex); }
Source:
private static WsMeasures.Component.Builder toWsComponent(ComponentDto component, Map<MetricDto, ComponentTreeData.Measure> measures, Map<String, ComponentDto> referenceComponentsByUuid) { WsMeasures.Component.Builder wsComponent = componentDtoToWsComponent(component); ComponentDto referenceComponent = referenceComponentsByUuid.get(component.getCopyResourceUuid()); if (referenceComponent != null) { wsComponent.setRefId(referenceComponent.uuid()); wsComponent.setRefKey(referenceComponent.key()); } for (Map.Entry<MetricDto, ComponentTreeData.Measure> entry : measures.entrySet()) { ComponentTreeData.Measure measure = entry.getValue(); Double value = measure.isValueSet() ? measure.getValue() : null; Double variation = measure.isVariationSet() ? measure.getVariation() : null; WsMeasures.Measure.Builder wsMeasureBuilder = createWsMeasureBuilder(entry.getKey(), value, measure.getData(), variation); wsComponent.addMeasures(wsMeasureBuilder); } return wsComponent; }

Target:
private static WsMeasures.Component.Builder toWsComponent(ComponentDto component, Map<MetricDto, ComponentTreeData.Measure> measures, Map<String, ComponentDto> referenceComponentsByUuid) { WsMeasures.Component.Builder wsComponent = componentDtoToWsComponent(component); ComponentDto referenceComponent = referenceComponentsByUuid.get(component.getCopyResourceUuid()); if (referenceComponent != null) { wsComponent.setRefId(referenceComponent.uuid()); wsComponent.setRefKey(referenceComponent.key()); } WsMeasures.Measure.Builder measureBuilder = WsMeasures.Measure.newBuilder(); for (Map.Entry<MetricDto, ComponentTreeData.Measure> entry : measures.entrySet()) { ComponentTreeData.Measure measure = entry.getValue(); updateMeasureBuilder(measureBuilder, entry.getKey(), measure.getValue(), measure.getData(), measure.getVariation()); wsComponent.addMeasures(measureBuilder); measureBuilder.clear(); } return wsComponent; }
Source:
public boolean isTablet(){ int size = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK; boolean large = Configuration.SCREENLAYOUT_SIZE_LARGE == size; boolean xlarge = Configuration.SCREENLAYOUT_SIZE_XLARGE == size; return (xlarge || large); }

Target:
private boolean isTablet() { return isTablet(this); }
Source:
public void actionPerformed(ActionEvent evt) { Node[] selected = ExplorerTopComponent.findInstance().getExplorerManager().getSelectedNodes(); if (selected.length != 1 || !(selected[0] instanceof MarkersNode)) { return; } MarkersNode markersNode = (MarkersNode) selected[0]; Model model = markersNode.getModelForNode(); Vec3 offset = new Vec3(0.11, 0.22, 0.33); MarkerSet markerset = model.getMarkerSet(); PhysicalFrame frameToUse; if ( model.getBodySet().getSize()==0) frameToUse = model.get_ground(); else frameToUse = model.getBodyList().begin().__deref__(); String newMarkerName = makeUniqueMarkerName(markerset); Marker newMarker = new Marker(); newMarker.setName(newMarkerName); newMarker.set_location(offset); newMarker.setParentFrame(frameToUse); OpenSimContext context = OpenSimDB.getInstance().getContext(model); context.cacheModelAndState(); model.addMarker(newMarker); try { context.restoreStateFromCachedModel(); } catch (IOException ex) { ErrorDialog.displayExceptionDialog(ex); } Vector<OpenSimObject> markers = new Vector<OpenSimObject>(); markers.add(newMarker); addMarkers(markers, true); }

Target:
public void actionPerformed(ActionEvent evt) { Node[] selected = ExplorerTopComponent.findInstance().getExplorerManager().getSelectedNodes(); if (selected.length != 1 || !(selected[0] instanceof MarkersNode)) { return; } MarkersNode markersNode = (MarkersNode) selected[0]; Model model = markersNode.getModelForNode(); Vec3 offset = new Vec3(0.11, 0.22, 0.33); MarkerSet markerset = model.getMarkerSet(); PhysicalFrame frameToUse = model.get_ground(); String newMarkerName = makeUniqueMarkerName(markerset); Marker newMarker = new Marker(); newMarker.setName(newMarkerName); newMarker.set_location(offset); newMarker.setParentFrame(frameToUse); OpenSimContext context = OpenSimDB.getInstance().getContext(model); context.cacheModelAndState(); model.addMarker(newMarker); try { context.restoreStateFromCachedModel(); } catch (IOException ex) { ErrorDialog.displayExceptionDialog(ex); } Vector<OpenSimObject> markers = new Vector<OpenSimObject>(); markers.add(newMarker); addMarkers(markers, true); }
Source:
public void onProcessFailed(ExecuteException e) { this.commandStatus.setExitStatus(new LinuxExitValue(e.getExitValue())); if (e.getExitValue() == 124) { this.commandStatus.setTimedout(true); } this.callback.accept(this.commandStatus); }

Target:
public void onProcessFailed(ExecuteException e) { this.commandStatus.setExitStatus(new LinuxExitValue(e.getExitValue())); if (e.getExitValue() == TIMEOUT_EXIT_VALUE || e.getExitValue() == SIGTERM_EXIT_VALUE) { this.commandStatus.setTimedout(true); } this.callback.accept(this.commandStatus); }
Source:
URL getURLForQuery(String query) throws URISyntaxException, MalformedURLException, FetcherException; Parser getParser(); @Override default List<BibEntry> performSearch(String query) throws FetcherException { if (StringUtil.isBlank(query)) { return Collections.emptyList(); } URL urlForQuery; try { urlForQuery = getURLForQuery(query); } catch (URISyntaxException | MalformedURLException e) { LoggerFactory.getLogger(this.getClass()).info("Search URL is malformed", query); throw new FetcherException("Search URI is malformed", e); } try (InputStream stream = getUrlDownload(urlForQuery).asInputStream()) { List<BibEntry> fetchedEntries = getParser().parseEntries(stream); fetchedEntries.forEach(this::doPostCleanup); return fetchedEntries; } catch (IOException e) { LoggerFactory.getLogger(this.getClass()).info("IOException at URL {}", urlForQuery.toString()); throw new FetcherException("A network error occurred", e); } catch (ParseException e) { throw new FetcherException("An internal parser error occurred", e); } }

Target:
URL getURLForQuery(String query) throws URISyntaxException, MalformedURLException, FetcherException; Parser getParser(); @Override default List<BibEntry> performSearch(String query) throws FetcherException { if (StringUtil.isBlank(query)) { return Collections.emptyList(); } URL urlForQuery; try { urlForQuery = getURLForQuery(query); } catch (URISyntaxException | MalformedURLException | FetcherException e) { throw new FetcherException(String.format("Search URI crafted from query %s is malformed", query), e); } return getBibEntries(urlForQuery); }
Source:
public boolean cancelOrder(CancelOrderParams orderParams) throws IOException { if (orderParams instanceof CancelOrderByIdParams) { return cancelOrder(((CancelOrderByIdParams) orderParams).getOrderId()); } return false; }

Target:
public boolean cancelOrder(CancelOrderParams orderParams) throws IOException { if (!(orderParams instanceof CancelOrderByIdParams)) { return false; } CancelOrderByIdParams cancelParams = (CancelOrderByIdParams) orderParams; return cancelOrder(cancelParams.getOrderId()); }
Source:
public TextBlock getJavadocBefore(int lineNoBefore) { int lineNo = lineNoBefore - 2; while (lineNo > 0 && shouldSkip(lineNo)) { lineNo--; } return javadocComments.get(lineNo); }

Target:
public TextBlock getJavadocBefore(int lineNoBefore) { int lineNo = lineNoBefore - 2; while (lineNo > 0 && (lineIsBlank(lineNo) || lineIsComment(lineNo))) { lineNo--; } return javadocComments.get(lineNo); }
Source:
public boolean testSourceType(CommandSource source) { Class<? extends CommandSource> clazz = source.getClass(); return sourceTypeDeep ? sourceType.isAssignableFrom(clazz) : sourceType.equals(clazz); }

Target:
public boolean testSourceType(CommandSource source) { Class<? extends CommandSource> clazz = source.getClass(); return this.sourceTypeDeep ? this.sourceType.isAssignableFrom(clazz) : this.sourceType.equals(clazz); }
Source:
public LocalFirehoseFactory( @JsonProperty("baseDir") File baseDir, @JsonProperty("filter") String filter, @JsonProperty("parser") StringInputRowParser parser ) { super( FileUtils.listFiles( Preconditions.checkNotNull(baseDir).getAbsoluteFile(), new WildcardFileFilter(filter), TrueFileFilter.INSTANCE ) ); this.baseDir = baseDir; this.filter = filter; this.parser = parser; log.info("Initialized with " + getObjects() + " files"); }

Target:
public LocalFirehoseFactory( @JsonProperty("baseDir") File baseDir, @JsonProperty("filter") String filter, @JsonProperty("parser") StringInputRowParser parser ) { this.baseDir = baseDir; this.filter = filter; this.parser = parser; }
Source:
private void handlePushNotificationResponsePerToken(final PushNotificationResponse<AeroGearApnsPushNotification> pushNotificationResponse ) { final String deviceToken = pushNotificationResponse.getPushNotification().getToken(); if (pushNotificationResponse.isAccepted()) { logger.trace(String.format("Push notification for '%s' (payload=%s)", deviceToken, pushNotificationResponse.getPushNotification().getPayload())); } else { final String rejectReason = pushNotificationResponse.getRejectionReason(); if ((pushNotificationResponse.getTokenInvalidationTimestamp() != null) || ("BadDeviceToken".equals(rejectReason))) { logger.warn(rejectReason + ", removing token: " + deviceToken); invalidTokens.add(deviceToken); } } }

Target:
private void handlePushNotificationResponsePerToken(final PushNotificationResponse<AeroGearApnsPushNotification> pushNotificationResponse ) { final String deviceToken = pushNotificationResponse.getPushNotification().getToken(); if (pushNotificationResponse.isAccepted()) { logger.trace(String.format("Push notification for '%s' (payload=%s)", deviceToken, pushNotificationResponse.getPushNotification().getPayload())); } else { final String rejectReason = pushNotificationResponse.getRejectionReason(); if ((pushNotificationResponse.getTokenInvalidationTimestamp() != null) || ("BadDeviceToken".equals(rejectReason))) { logger.info(rejectReason + ", removing token: " + deviceToken); invalidTokens.add(deviceToken); } } }
Source:
private static AsyncRequestResponseHandler getInstance(RestServerMetrics restServerMetrics) { if (instantiated.compareAndSet(false, true)) { AsyncRequestResponseHandlerFactory.restServerMetrics = restServerMetrics; instance = new AsyncRequestResponseHandler(restServerMetrics); } if (AsyncRequestResponseHandlerFactory.restServerMetrics != restServerMetrics) { throw new IllegalStateException("RestServerMetrics instance provided during construction of " + "AsyncRequestResponseHandler differs from the one currently received"); } return instance; }

Target:
private static AsyncRequestResponseHandler getInstance(RestServerMetrics restServerMetrics) { lock.lock(); try { if (instance == null) { AsyncRequestResponseHandlerFactory.restServerMetrics = restServerMetrics; instance = new AsyncRequestResponseHandler(restServerMetrics); } if (AsyncRequestResponseHandlerFactory.restServerMetrics != restServerMetrics) { throw new IllegalStateException("RestServerMetrics instance provided during construction of " + "AsyncRequestResponseHandler differs from the one currently received"); } } finally { lock.unlock(); } return instance; }
Source:
public void run() { try { while (true) { long currentTime = System.currentTimeMillis(); long remainingTime = _lastInvokeTime + _periodicTriggerInterval - currentTime; if (remainingTime <= 0) { if (_batchCallbackProcessor == null || _batchCallbackProcessor.queueIsEmpty()) { NotificationContext changeContext = new NotificationContext(_manager); changeContext.setType(Type.CALLBACK); changeContext.setChangeType(_changeType); enqueueTask(changeContext); } break; } else { wait(remainingTime); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception e1) { logger.warn("Exception during execute refresh task. Error: ", e1); } }

Target:
public void run() { if (!isReady()) { return; } long currentTime = System.currentTimeMillis(); long remainingTime = _lastInvokeTime + _triggerInterval - currentTime; if (remainingTime <= 0) { if (_batchCallbackProcessor == null || _batchCallbackProcessor.queueIsEmpty()) { NotificationContext changeContext = new NotificationContext(_manager); changeContext.setType(Type.CALLBACK); changeContext.setChangeType(_changeType); try { enqueueTask(changeContext); } catch (Exception e) { logger.warn("An exception was thrown during periodic triggered task.", e); } } scheduleNewTask(_triggerInterval); } else { scheduleNewTask(remainingTime); } }
Source:
public void setUp() { bout = new ByteArrayOutputStream(); System.setOut(new PrintStream(bout)); standardOutOrig = System.out; }

Target:
public void setUp() { bout = new ByteArrayOutputStream(); System.setOut(new PrintStream(bout)); }
Source:
public static List<OpenMode> getOperationSupportedFileSystem() { ArrayList<OpenMode> arrayList = new ArrayList<>(); arrayList.add(OpenMode.SMB); arrayList.add(OpenMode.FILE); arrayList.add(OpenMode.DROPBOX); arrayList.add(OpenMode.BOX); arrayList.add(OpenMode.GDRIVE); arrayList.add(OpenMode.ONEDRIVE); return arrayList; }

Target:
public static HashSet<OpenMode> getOperationSupportedFileSystem() { HashSet<OpenMode> hashSet = new HashSet<>(); hashSet.add(OpenMode.SMB); hashSet.add(OpenMode.FILE); hashSet.add(OpenMode.DROPBOX); hashSet.add(OpenMode.BOX); hashSet.add(OpenMode.GDRIVE); hashSet.add(OpenMode.ONEDRIVE); return hashSet; }
Source:
@Override public void onAuthenticationFailed() { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getBaseContext(), "Wrong password.", Toast.LENGTH_LONG).show(); } }); }

Target:
@Override public void onAuthenticationFailed() { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getBaseContext(), getString(R.string.notification_wrong_password), Toast.LENGTH_LONG).show(); } }); }
Source:
private PhoneAccountHandle getAccountHandleFromNumber(String dialNumber) { Cursor cursor = mContentResolver.query(Calls.CONTENT_URI, new String[] {Calls.PHONE_ACCOUNT_ID, Calls.PHONE_ACCOUNT_COMPONENT_NAME}, Calls.TYPE + "=" + Calls.OUTGOING_TYPE + " AND " + Calls.NUMBER + "=\"" + PhoneNumberUtils.normalizeNumber(dialNumber) + "\"", null, Calls.DEFAULT_SORT_ORDER + " LIMIT 1"); if (cursor == null) { return null; } if (cursor.getCount() > 0) { cursor.moveToNext(); String componentName = cursor.getString( cursor.getColumnIndex(Calls.PHONE_ACCOUNT_COMPONENT_NAME)); String accountId = cursor.getString(cursor.getColumnIndex(Calls.PHONE_ACCOUNT_ID)); cursor.close(); if (!TextUtils.isEmpty(componentName) && !TextUtils.isEmpty(accountId)) { return new PhoneAccountHandle( ComponentName.unflattenFromString(componentName), accountId); } } return null; }

Target:
private PhoneAccountHandle getAccountHandleFromNumber(String dialNumber) { Cursor cursor = mContentResolver.query(Calls.CONTENT_URI, PHONE_ACCOUNT_STRING, Calls.TYPE + "=" + Calls.OUTGOING_TYPE + " AND " + Calls.NUMBER + "=\"" + PhoneNumberUtils.normalizeNumber(dialNumber) + "\"", null, Calls.DEFAULT_SORT_ORDER + " LIMIT 1"); if (cursor == null) { return null; } if (cursor.getCount() < 1) { cursor.close(); retrun null; } cursor.moveToNext(); String componentName = cursor.getString( cursor.getColumnIndex(Calls.PHONE_ACCOUNT_COMPONENT_NAME)); String accountId = cursor.getString(cursor.getColumnIndex(Calls.PHONE_ACCOUNT_ID)); cursor.close(); if (TextUtils.isEmpty(componentName) || TextUtils.isEmpty(accountId)) { return null; } return new PhoneAccountHandle( ComponentName.unflattenFromString(componentName), accountId); }
Source:
public void testGetKwh() { final String result = DlmsUnitTypeDto.getUnit(30); Assert.assertTrue("KWH".equals(result)); }

Target:
public void testGetKwh() { final String result = DlmsUnitTypeDto.getUnit(30); assertEquals("KWH", result); }
Source:
public Builder setRating(int rating) { if (rating <= 10 && rating >= 0) { this.rating = rating; } else { throw new IllegalArgumentException("Rating tried to set was out of bounds"); } return this; }

Target:
public Builder setRating(int rating) { this.rating = rating; return this; }
Source:
public void topologicalSort() { ppp("================ SORTING"); m_strictlySortedNodes = Lists.newArrayList(); initializeIndependentNodes(); List<Node<T>> nodes2 = Lists.newArrayList(); for (Node<T> n : getNodes()) { if (! isIndependent(n.getObject())) { ppp("ADDING FOR SORT: " + n.getObject()); nodes2.add(n.clone()); } else { ppp("SKIPPING INDEPENDENT NODE " + n); } } Comparator<Node> comparator = Systematiser.getComparator(); if (comparator != null) { Collections.sort(nodes2, comparator); } while (! nodes2.isEmpty()) { Node<T> node = findNodeWithNoPredecessors(nodes2); if (null == node) { List<T> cycle = new Tarjan<>(this, nodes2.get(0).getObject()).getCycle(); StringBuilder sb = new StringBuilder(); sb.append("The following methods have cyclic dependencies:\n"); for (T m : cycle) { sb.append(m).append("\n"); } throw new TestNGException(sb.toString()); } else { m_strictlySortedNodes.add(node.getObject()); removeFromNodes(nodes2, node); } } ppp("=============== DONE SORTING"); if (m_verbose) { dumpSortedNodes(); } }

Target:
public void topologicalSort() { ppp("================ SORTING"); m_strictlySortedNodes = Lists.newArrayList(); initializeIndependentNodes(); List<Node<T>> nodes2 = Lists.newArrayList(); for (Node<T> n : getNodes()) { if (! isIndependent(n.getObject())) { ppp("ADDING FOR SORT: " + n.getObject()); nodes2.add(n.clone()); } else { ppp("SKIPPING INDEPENDENT NODE " + n); } } Collections.sort(nodes2, comparator); while (! nodes2.isEmpty()) { Node<T> node = findNodeWithNoPredecessors(nodes2); if (null == node) { List<T> cycle = new Tarjan<>(this, nodes2.get(0).getObject()).getCycle(); StringBuilder sb = new StringBuilder(); sb.append("The following methods have cyclic dependencies:\n"); for (T m : cycle) { sb.append(m).append("\n"); } throw new TestNGException(sb.toString()); } else { m_strictlySortedNodes.add(node.getObject()); removeFromNodes(nodes2, node); } } ppp("=============== DONE SORTING"); if (m_verbose) { dumpSortedNodes(); } }
Source:
public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); final String type = request.param(PARAM_TYPE); final String value = request.param(PARAM_VALUE); if (PROJECT.toString().equals(type) && isBlank(value)) { throw new IllegalArgumentException("type PROJECT requires a mandatory project key"); } if (ORGANIZATION.toString().equals(type) && isBlank(value)) { throw new IllegalArgumentException("type ORGANIZATION requires a mandatory project key"); } String userLogin = userSession.getLogin(); String uuid = ""; try (DbSession dbSession = dbClient.openSession(false)) { if (PROJECT.toString().equals(type)) { com.google.common.base.Optional<ComponentDto> dto = dbClient.componentDao().selectByKey(dbSession, value); if (dto.isPresent()) { uuid = dto.get().uuid(); } else { throw new IllegalStateException("No Project found for homepage key " + uuid); } } if (ORGANIZATION.toString().equals(type)) { Optional<OrganizationDto> dto = dbClient.organizationDao().selectByKey(dbSession, value); if (dto.isPresent()) { uuid = dto.get().getUuid(); } else { throw new IllegalStateException("No Organization found for homepage key " + uuid); } } UserDto userDto = dbClient.userDao().selectActiveUserByLogin(dbSession, userLogin); checkState(userDto != null, "User login '%s' cannot be found", userLogin); userDto.setHomepageType(type); userDto.setHomepageValue(uuid); dbClient.userDao().update(dbSession, userDto); dbSession.commit(); } response.noContent(); }

Target:
public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); String type = request.mandatoryParam(PARAM_TYPE); String value = request.param(PARAM_PARAMETER); checkRequest(type, value); String login = userSession.getLogin(); try (DbSession dbSession = dbClient.openSession(false)) { UserDto user = dbClient.userDao().selectActiveUserByLogin(dbSession, login); checkState(user != null, "User login '%s' cannot be found", login); user.setHomepageType(type); user.setHomepageValue(findHomepageValue(dbSession, type, value)); dbClient.userDao().update(dbSession, user); dbSession.commit(); } response.noContent(); }
Source:
private PeriodicMetrics providePeriodicMetrics(final MetricsFactory metricsFactory, final ActorSystem actorSystem) { final TsdPeriodicMetrics periodicMetrics = new TsdPeriodicMetrics.Builder() .setMetricsFactory(metricsFactory) .setPollingExecutor(actorSystem.dispatcher()) .build(); final FiniteDuration delay = FiniteDuration.apply(500, TimeUnit.MILLISECONDS); actorSystem.scheduler().schedule(delay, delay, periodicMetrics, actorSystem.dispatcher()); return periodicMetrics; }

Target:
private PeriodicMetrics providePeriodicMetrics(final MetricsFactory metricsFactory, final ActorSystem actorSystem) { final TsdPeriodicMetrics periodicMetrics = new TsdPeriodicMetrics.Builder() .setMetricsFactory(metricsFactory) .setPollingExecutor(actorSystem.dispatcher()) .build(); final FiniteDuration delay = FiniteDuration.apply(1, TimeUnit.SECONDS); actorSystem.scheduler().schedule(delay, delay, periodicMetrics, actorSystem.dispatcher()); return periodicMetrics; }
Source:
public AssetRequestHandler(Context context) { this.context = context; assetManager = context.getAssets(); }

Target:
public AssetRequestHandler(Context context) { this.context = context.getApplicationContext(); assetManager = context.getAssets(); }
Source:
public static String argTypeList(final ImmutableList<Arguments> arguments) { if (arguments.isEmpty()) { return ""; } final StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < arguments.size(); i++) { stringBuilder.append(arguments.get(i).getType()); if (i < arguments.size() - 1) { stringBuilder.append(", "); } } return stringBuilder.toString(); }

Target:
public static String argTypeList(final ImmutableList<Arguments> arguments) { return arguments.stream().map(i -> i.getType()).collect(Collectors.joining(", ")); }
Source:
private void assertNotInitializedExceptionIsThrownAndMappedCorrectly() { try { addTodo(); } catch (Exception e) { assertTrue(exceptionIsRetryableAndContainsMessage(e, "CassandraKeyValueService is not initialized yet")); } }

Target:
private void assertNotInitializedExceptionIsThrownAndMappedCorrectly() { try { addTodo(); fail("Expected to throw an exception"); } catch (Exception e) { assertTrue(exceptionIsRetryableAndContainsMessage(e, "CassandraKeyValueService is not initialized yet")); } }
Source:
public void testDeleteBaseTableRows() throws Exception { String baseTableName = generateUniqueName(); String baseTableFullName = SchemaUtil.getTableName(SCHEMA1, baseTableName); try (Connection connection = DriverManager.getConnection(getUrl()); Connection viewConnection = isMultiTenant ? DriverManager.getConnection(TENANT_SPECIFIC_URL) : connection) { createBaseTableAndViews(connection, baseTableFullName, viewConnection, SCHEMA2, SCHEMA2, SCHEMA2); String deleteTableRows = "DELETE FROM " + SYSTEM_CATALOG_NAME + " WHERE " + TABLE_SCHEM + " = '" + SCHEMA1 + "' AND " + TABLE_NAME + " = '" + baseTableName + "' AND " + TABLE_TYPE + " = '" + PTableType.TABLE.getSerializedValue() + "'"; connection.createStatement().execute(deleteTableRows); connection.commit(); String viewQuery = "SELECT COUNT(*) FROM " + SYSTEM_CATALOG_NAME + " WHERE " + TABLE_TYPE + " = '" + PTableType.VIEW.getSerializedValue() + "'"; ResultSet rs = connection.createStatement().executeQuery(viewQuery); assertTrue(rs.next()); long count = rs.getLong(1); assertTrue(rs.getLong(1) == fanout + fanout * fanout + fanout * fanout * fanout); runOrphanViewTool(false, true, true, false); assertTrue(getLineCount() == fanout + fanout * fanout + fanout * fanout * fanout); rs = connection.createStatement().executeQuery(viewQuery); assertTrue(rs.next()); assertTrue(rs.getLong(1) == fanout + fanout * fanout + fanout * fanout * fanout); runOrphanViewTool(true, false, false, true); verifyNoViewNoLink(connection, SCHEMA2); verifyNoChildLink(connection, SCHEMA1); deleteAllRows(connection, SCHEMA1, SCHEMA2, SCHEMA3, SCHEMA4); } }

Target:
public void testDeleteBaseTableRows() throws Exception { String baseTableName = generateUniqueName(); String baseTableFullName = SchemaUtil.getTableName(SCHEMA1, baseTableName); try (Connection connection = DriverManager.getConnection(getUrl()); Connection viewConnection = isMultiTenant ? DriverManager.getConnection(TENANT_SPECIFIC_URL) : connection) { createBaseTableAndViews(connection, baseTableFullName, viewConnection, SCHEMA2, SCHEMA2, SCHEMA2); executeDeleteQuery(connection, deleteTableRows, SCHEMA1); ResultSet rs = connection.createStatement().executeQuery(countAllViewsQuery); assertTrue(rs.next()); assertTrue(rs.getLong(1) == childCount + grandChildCount + grandGrandChildCount); runOrphanViewTool(false, true, true, false); verifyOrphanFileLineCounts(childCount + grandChildCount + grandGrandChildCount, 0, childCount + grandChildCount + grandGrandChildCount, childCount); rs = connection.createStatement().executeQuery(countAllViewsQuery); assertTrue(rs.next()); assertTrue(rs.getLong(1) == childCount + grandChildCount + grandGrandChildCount); runOrphanViewTool(true, false, false, true); verifyNoViewNoLinkInSystemCatalog(connection, SCHEMA2); verifyNoChildLink(connection, SCHEMA1); deleteAllRows(connection, SCHEMA1, SCHEMA2, SCHEMA3, SCHEMA4); } }