auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public String getPath(String rootPath) { if (path == null) { return null; } boolean trailingSeparator = path.endsWith(File.separator); Path absolutePath = Paths.get(path); if (!absolutePath.isAbsolute()) { if (StringUtils.isNotBlank(rootPath)) { absolutePath = Paths.get(rootPath, path); } else { LOGGER.debug( "Root path is blank. Resolving relative path to: {}", path, LogSanitizer.cleanAndEncode(absolutePath.toAbsolutePath().toString())); } } String absolutePathStr = absolutePath.toAbsolutePath().toString(); return trailingSeparator ? absolutePathStr + File.separator : absolutePathStr; }

Target:
public String getPath(String rootPath) { if (path == null) { return null; } boolean trailingSeparator = path.endsWith(File.separator); Path absolutePath = Paths.get(path); if (!absolutePath.isAbsolute()) { if (StringUtils.isNotBlank(rootPath)) { absolutePath = Paths.get(rootPath, path); } else { LOGGER.debug( "Root path is blank. Resolving relative path to: {}", path, LogSanitizer.sanitize(absolutePath.toAbsolutePath())); } } String absolutePathStr = absolutePath.toAbsolutePath().toString(); return trailingSeparator ? absolutePathStr + File.separator : absolutePathStr; }
Source:
public void addWarning(String errorMessage, Element element) { warnings.add(new ProblemImpl(errorMessage, name, element)); }

Target:
public void addWarning(String errorMessage, Element element) { warnings.add(new ProblemImpl(errorMessage, element)); }
Source:
protected void internalReceiveCommand(String itemName, Command command) { if (!isOutBound(itemName)) { logger.warn("Received command ({}) for item which is configured as 'in-bound', ignoring", command.toString(), itemName); return; } try { String xbmcInstance = getXbmcInstance(itemName); String property = getProperty(itemName); XbmcConnector connector = getXbmcConnector(xbmcInstance); if (connector == null) { logger.warn("Received command ({}) for item but no XBMC connector found for {}, ignoring", command.toString(), itemName, xbmcInstance); return; } if (!connector.isConnected()) { logger.warn("Received command ({}) for item but the connection to the XBMC instance is down, ignoring", command.toString(), itemName, xbmcInstance); return; } if (property.equals("Player.PlayPause")) connector.playerPlayPause(); if (property.equals("Player.Open")) connector.playerOpen(command.toString()); if (property.equals("Player.Stop")) connector.playerStop(); if (property.equals("GUI.ShowNotification")) connector.showNotification("openHAB", command.toString()); if (property.equals("System.Shutdown") && command == OnOffType.OFF) connector.systemShutdown(); if (property.equals("Application.Volume")) connector.applicationSetVolume(command.toString()); } catch (Exception e) { logger.error("Error handling command", e); } }

Target:
protected void internalReceiveCommand(String itemName, Command command) { if (!isOutBound(itemName)) { logger.warn("Received command ({}) for item which is configured as 'in-bound', ignoring", command.toString(), itemName); return; } try { String xbmcInstance = getXbmcInstance(itemName); String property = getProperty(itemName); XbmcConnector connector = getXbmcConnector(xbmcInstance); if (connector == null) { logger.warn("Received command ({}) for item but no XBMC connector found for {}, ignoring", command.toString(), itemName, xbmcInstance); return; } if (!connector.isConnected()) { logger.warn("Received command ({}) for item but the connection to the XBMC instance is down, ignoring", command.toString(), itemName, xbmcInstance); return; } if (property.equals("Player.PlayPause")) connector.playerPlayPause(); else if (property.equals("Player.Open")) connector.playerOpen(command.toString()); else if (property.equals("Player.Stop")) connector.playerStop(); else if (property.equals("GUI.ShowNotification")) connector.showNotification("openHAB", command.toString()); else if (property.equals("System.Shutdown") && command == OnOffType.OFF) connector.systemShutdown(); else if (property.equals("Application.Volume")) connector.applicationSetVolume(command.toString()); } catch (Exception e) { logger.error("Error handling command", e); } }
Source:
public ReadBatch readRecords(List<Long> addresses, Optional<String> destNode, LogUnitClient client) { for (int i = 0; i < maxReadRetries; i++) { try { ReadResponse response = CFUtils .getUninterruptibly(client.readAll(ImmutableList.copyOf(addresses)), TimeoutException.class, NetworkException.class); Map<Long, ILogData> records = new HashMap<>(response.getAddresses()); ReadBatch readBatch = checkReadRecords(ImmutableList.copyOf(addresses), records, destNode); if (readBatch.getStatus() == ReadBatch.ReadStatus.FAILED) { throw new IllegalStateException("Some addresses failed to transfer: " + readBatch.getFailedAddresses()); } return readBatch; } catch (NetworkException | TimeoutException | IllegalStateException e) { log.warn("readRecords: error occurred: {}, retry times.", e, i); } catch (RuntimeException re) { log.error("readRecords: can't retry, error:", re); break; } } throw new ReadBatchException("readRecords: read retries were exhausted"); }

Target:
public ReadBatch readRecords(List<Long> addresses, Optional<String> destNode, LogUnitClient client) { for (int i = 0; i < maxReadRetries; i++) { try { ReadResponse response = CFUtils .getUninterruptibly(client.readAll(addresses)); Map<Long, ILogData> records = new HashMap<>(response.getAddresses()); ReadBatch readBatch = checkReadRecords(addresses, records, destNode); if (readBatch.getStatus() == ReadBatch.ReadStatus.FAILED) { throw new IllegalStateException("Some addresses failed to transfer: " + readBatch.getFailedAddresses()); } return readBatch; } catch (WrongEpochException e) { log.warn("readRecords: encountered a wrong epoch exception on try {}: {}.", i, e); throw e; } catch (RuntimeException e) { log.warn("readRecords: encountered an exception on try {}: {}.", i, e); Sleep.sleepUninterruptibly(readSleepDuration); } } throw new ReadBatchException("readRecords: read retries were exhausted"); }
Source:
private synchronized boolean isProtocolNameInconsistent(ApiKeys key, String protocolName) { final boolean protocolNameInconsistent = protocolName != null && generation() != Generation.NO_GENERATION && !protocolName.equals(generation().protocolName); if (protocolNameInconsistent) { log.error("{} failed due to inconsistent Protocol Name, received but expected {}", key, protocolName, generation().protocolName); } return protocolNameInconsistent; }

Target:
private boolean isProtocolNameInconsistent(ApiKeys key, String protocolName) { final Generation currentGeneration = generation(); final boolean protocolNameInconsistent = protocolName != null && currentGeneration != Generation.NO_GENERATION && !protocolName.equals(currentGeneration.protocolName); if (protocolNameInconsistent) { log.error("{} failed due to inconsistent Protocol Name, received but expected {}", key, protocolName, currentGeneration.protocolName); } return protocolNameInconsistent; }
Source:
public Optional<Enrollment> enrollUser(Enrollment enrollment, boolean isSectionEnrollment) throws InvalidOauthTokenException, IOException { String createdUrl = null; if (isSectionEnrollment) { createdUrl = buildCanvasUrl("sections/" + enrollment.getCourseSectionId() + "/enrollments", Collections.emptyMap()); } else { createdUrl = buildCanvasUrl("courses/" + enrollment.getCourseId() + "/enrollments", Collections.emptyMap()); } LOG.debug("create URl for course enrollments: "+ createdUrl); Response response = canvasMessenger.sendToCanvas(oauthToken, createdUrl, enrollment.toPostMap()); if (response.getErrorHappened() || response.getResponseCode() != 200) { LOG.debug("Failed to enroll in course, error message: " + response.toString()); return Optional.empty(); } return responseParser.parseToObject(Enrollment.class,response); }

Target:
private Optional<Enrollment> enrollUser(Enrollment enrollment, boolean isSectionEnrollment) throws InvalidOauthTokenException, IOException { String createdUrl = null; if (isSectionEnrollment) { createdUrl = buildCanvasUrl("sections/" + enrollment.getCourseSectionId() + "/enrollments", Collections.emptyMap()); } else { createdUrl = buildCanvasUrl("courses/" + enrollment.getCourseId() + "/enrollments", Collections.emptyMap()); } LOG.debug("create URl for course enrollments: "+ createdUrl); Response response = canvasMessenger.sendToCanvas(oauthToken, createdUrl, enrollment.toPostMap()); if (response.getErrorHappened() || response.getResponseCode() != 200) { LOG.debug("Failed to enroll in course, error message: " + response.toString()); return Optional.empty(); } return responseParser.parseToObject(Enrollment.class,response); }
Source:
public Map<Errors, Integer> errorCounts() { Map<Errors, Integer> errorCounts = new HashMap<>(); for (AlterReplicaLogDirTopicResult x : data.results()) { for (AlterReplicaLogDirsResponseData.AlterReplicaLogDirPartitionResult y : x.partitions()) { updateErrorCounts(errorCounts, Errors.forCode(y.errorCode())); } } return errorCounts; }

Target:
public Map<Errors, Integer> errorCounts() { Map<Errors, Integer> errorCounts = new HashMap<>(); data.results().forEach(topicResult -> topicResult.partitions().forEach(partitionResult -> updateErrorCounts(errorCounts, Errors.forCode(partitionResult.errorCode())))); return errorCounts; }
Source:
public Truthiness not() { if (this == TRUTHY) { return FALSY; } else if (this == FALSY) { return TRUTHY; } else { return UNKNOWN; } }

Target:
public Truthiness not() { switch (this) { case TRUTHY: return FALSY; case FALSY: return TRUTHY; default: return UNKNOWN; } }
Source:
protected Map<String, String> convertLabelsToKubernetesNames(Map<String, String> labels) { Map<String, String> names = new HashMap<>(); for (Map.Entry<String, String> entry : labels.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (value == null) { continue; } if (!key.startsWith(CHE_OPENSHIFT_RESOURCES_PREFIX)) { LOG.warn("Expected CreateContainerParams label key " + entry.getKey() + " to start with " + CHE_SERVER_LABEL_PREFIX); } else if (key.contains(".") || key.contains("_") || value.contains("_")) { LOG.error(String.format("Cannot convert label %s to DNS Name: contains '-' or '.'", entry.toString())); continue; } key = key.replaceAll(":", ".").replaceAll("/", "_"); value = value.replaceAll("/", "_"); names.put(String.format(CHE_SERVER_LABEL_PADDING, key), String.format(CHE_SERVER_LABEL_PADDING, value)); } return names; }

Target:
protected Map<String, String> convertLabelsToKubernetesNames(Map<String, String> labels) { Map<String, String> names = new HashMap<>(); for (Map.Entry<String, String> entry : labels.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (value == null) { continue; } if (!key.startsWith(CHE_SERVER_LABEL_PREFIX)) { LOG.warn("Expected CreateContainerParams label key " + entry.getKey() + " to start with " + CHE_SERVER_LABEL_PREFIX); } else if (key.contains(".") || key.contains("_") || value.contains("_")) { LOG.error(String.format("Cannot convert label %s to DNS Name: " + "'-' and '.' are used as escape characters", entry.toString())); continue; } key = key.replaceAll(":", ".").replaceAll("/", "_"); value = value.replaceAll("/", "_"); key = String.format(CHE_SERVER_LABEL_PADDING, key); value = String.format(CHE_SERVER_LABEL_PADDING, value); if (!key.matches(KUBERNETES_ANNOTATION_REGEX) || !value.matches(KUBERNETES_ANNOTATION_REGEX)) { LOG.error(String.format("Could not convert label %s into Kubernetes annotation: " + "labels must be alphanumeric with ':' and '/'", entry.toString())); continue; } names.put(key, value); } return names; }
Source:
private Player() { id = new SimpleIntegerProperty(); username = new SimpleStringProperty(); clan = new SimpleStringProperty(null); country = new SimpleStringProperty(); avatarUrl = new SimpleStringProperty(); avatarTooltip = new SimpleStringProperty(); moderatorForChannels = new SimpleSetProperty<>(FXCollections.observableSet()); chatOnly = new SimpleBooleanProperty(true); globalRatingDeviation = new SimpleFloatProperty(); globalRatingMean = new SimpleFloatProperty(); leaderboardRatingDeviation = new SimpleFloatProperty(); leaderboardRatingMean = new SimpleFloatProperty(); status = new SimpleObjectProperty<>(PlayerStatus.IDLE); game = new SimpleObjectProperty<>(); numberOfGames = new SimpleIntegerProperty(); socialStatus = new SimpleObjectProperty<>(OTHER); idleSince = new SimpleObjectProperty<>(Instant.now()); }

Target:
private Player() { id = new SimpleIntegerProperty(); username = new SimpleStringProperty(); clan = new SimpleStringProperty(); country = new SimpleStringProperty(); avatarUrl = new SimpleStringProperty(); avatarTooltip = new SimpleStringProperty(); moderatorForChannels = new SimpleSetProperty<>(FXCollections.observableSet()); chatOnly = new SimpleBooleanProperty(true); globalRatingDeviation = new SimpleFloatProperty(); globalRatingMean = new SimpleFloatProperty(); leaderboardRatingDeviation = new SimpleFloatProperty(); leaderboardRatingMean = new SimpleFloatProperty(); status = new SimpleObjectProperty<>(PlayerStatus.IDLE); game = new SimpleObjectProperty<>(); numberOfGames = new SimpleIntegerProperty(); socialStatus = new SimpleObjectProperty<>(OTHER); idleSince = new SimpleObjectProperty<>(Instant.now()); }
Source:
protected Result convert(Citations source) { if (CollectionUtils.isNotEmpty(source.getCitations())) { Result result = new Result(); result.setId(source.getDocumentId().toString()); ExtraInfo extraInfo = new ExtraInfo(); extraInfo.setValue(converter.serialize(normalize(source.getCitations()))); extraInfo.setName(EXTRA_INFO_NAME); extraInfo.setTypology(EXTRA_INFO_TYPOLOGY); extraInfo.setProvenance(this.getInferenceProvenance()); extraInfo.setTrust(StaticConfigurationProvider.ACTION_TRUST_0_9); result.setExtraInfo(Arrays.asList(extraInfo)); return result; } else { return null; } }

Target:
protected Result convert(Citations source) { if (CollectionUtils.isNotEmpty(source.getCitations())) { Result result = new Result(); result.setId(source.getDocumentId().toString()); ExtraInfo extraInfo = new ExtraInfo(); extraInfo.setValue(converter.serialize(normalize(source.getCitations()))); extraInfo.setName(EXTRA_INFO_NAME); extraInfo.setTypology(EXTRA_INFO_TYPOLOGY); extraInfo.setProvenance(this.getInferenceProvenance()); extraInfo.setTrust(StaticConfigurationProvider.ACTION_TRUST_0_9); result.setExtraInfo(Collections.singletonList(extraInfo)); return result; } else { return null; } }
Source:
private boolean runDelegatedTasks(boolean inUnwrap) { if (delegatedTaskExecutor == ImmediateExecutor.INSTANCE || (delegatedTaskExecutor instanceof EventExecutor && ((EventExecutor) delegatedTaskExecutor).inEventLoop())) { for (;;) { Runnable task = engine.getDelegatedTask(); if (task == null) { return true; } task.run(); } } else { final Runnable task = engine.getDelegatedTask(); assert task != null; executeDelegatingTask(task, inUnwrap); return false; } }

Target:
private boolean runDelegatedTasks(boolean inUnwrap) { if (delegatedTaskExecutor == ImmediateExecutor.INSTANCE || inEventLoop(delegatedTaskExecutor)) { for (;;) { runAllDelegatedTasks(engine); return true; } } else { executeDelegatedTasks(inUnwrap); return false; } }
Source:
public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { if (httpServletRequest.getRequestURI().toString().contains(DATA_ELEMENTS_ENDPOINT)) { writeResponse(httpServletResponse, "/dhis2/data-elements-response.json"); } else if (httpServletRequest.getRequestURI().toString().contains(DATA_SETS_ENDPOINT)) { writeResponse(httpServletResponse, "/dhis2/data-sets-response.json"); } else if (httpServletRequest.getRequestURI().toString().contains(ORGANISATION_UNITS_ENDPOINT)) { writeResponse(httpServletResponse, "/dhis2/organisation-units-response.json"); } else if (httpServletRequest.getRequestURI().toString().contains(PROGRAMS_ENDPOINT)) { writeResponse(httpServletResponse, "/dhis2/programs-response.json"); } else if (httpServletRequest.getRequestURI().toString().contains(PROGRAM_STAGES_ENDPOINT)) { writeResponse(httpServletResponse, "/dhis2/program-stages-response.json"); } else if (httpServletRequest.getRequestURI().toString().contains(PROGRAM_STAGE_DATA_ELEMENTS_ENDPOINT)) { writeResponse(httpServletResponse, "/dhis2/program-stage-data-elements-response.json"); } else if (httpServletRequest.getRequestURI().toString().contains(TRACKED_ENTITIES_ENDPOINT)) { writeResponse(httpServletResponse, "/dhis2/tracked-entities-response.json"); } else if (httpServletRequest.getRequestURI().toString().contains(TRACKED_ENTITY_ATTRIBUTES_ENDPOINT)) { writeResponse(httpServletResponse, "/dhis2/tracked-entity-attributes-response.json"); } else if (httpServletRequest.getRequestURI().toString().contains(PROGRAM_TRACKED_ENTITY_ATTRIBUTES_ENDPOINT)) { writeResponse(httpServletResponse, "/dhis2/program-tracked-entity-attributes-response.json"); } }

Target:
public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { String requestURI = httpServletRequest.getRequestURI().toString(); if (requestURI.contains(PROGRAM_ENDPOINT)) { writeResponse(httpServletResponse, PROGRAM_RESPONSE); } else if (requestURI.contains(DATA_ELEMENTS_ENDPOINT)) { writeResponse(httpServletResponse, DATA_ELEMENTS_RESPONSE); } else if (requestURI.contains(DATA_SETS_ENDPOINT)) { writeResponse(httpServletResponse, DATA_SETS_RESPONSE); } else if (requestURI.contains(ORGANISATION_UNITS_ENDPOINT)) { writeResponse(httpServletResponse, ORGANISATION_UNITS_RESPONSE); } else if (requestURI.contains(PROGRAMS_ENDPOINT)) { writeResponse(httpServletResponse, PROGRAMS_RESPONSE); } else if (requestURI.contains(TRACKED_ENTITIES_ENDPOINT)) { writeResponse(httpServletResponse, TRACKED_ENTITIES_RESPONSE); } else if (requestURI.contains(TRACKED_ENTITY_ATTRIBUTES_ENDPOINT)) { writeResponse(httpServletResponse, TRACKED_ENTITY_ATTRIBUTES_RESPONSE); } }
Source:
protected boolean isAnonymous() { return getModelObject() != null && getModelObject().getReview() != null && getModelObject().getReview().getRepository() != null && getModelObject().getReview().getRepository().getAccount() == null; }

Target:
protected boolean isAnonymous() { return ReviewUiUtil.isAnonymous(getModelObject()); }
Source:
public void tearDown() throws IOException { try { DeleteJobTemplate.deleteJobTemplate(PROJECT_ID, LOCATION, TEMPLATE_ID); } catch (GoogleJsonResponseException gjre) { } System.setOut(originalOut); bout.reset(); }

Target:
public void tearDown() throws IOException { DeleteJobTemplate.deleteJobTemplate(PROJECT_ID, LOCATION, TEMPLATE_ID); System.setOut(originalOut); bout.reset(); }
Source:
private List<IProject> findProjectsToDelete(final List<RepositoryNode> selectedNodes) { final List<IProject> projectsToDelete = new ArrayList<>(); for (RepositoryNode node : selectedNodes) { Repository repository = node.getRepository(); if (repository == null) { continue; } if (repository.isBare()) continue; File workDir = repository.getWorkTree(); final IPath wdPath = new Path(workDir.getAbsolutePath()); for (IProject prj : ResourcesPlugin.getWorkspace() .getRoot().getProjects()) { IPath location = prj.getLocation(); if (location != null && wdPath.isPrefixOf(location)) { projectsToDelete.add(prj); } } } return projectsToDelete; }

Target:
private List<IProject> findProjectsToDelete(final List<RepositoryNode> selectedNodes) { final List<IProject> projectsToDelete = new ArrayList<>(); for (RepositoryNode node : selectedNodes) { Repository repository = node.getRepository(); if (repository == null || repository.isBare()) { continue; } File workDir = repository.getWorkTree(); final IPath wdPath = new Path(workDir.getAbsolutePath()); for (IProject prj : ResourcesPlugin.getWorkspace() .getRoot().getProjects()) { IPath location = prj.getLocation(); if (location != null && wdPath.isPrefixOf(location)) { projectsToDelete.add(prj); } } } return projectsToDelete; }
Source:
public long byteSize() { return cacheEntriesBytes + size()*24; }

Target:
public long byteSize() { log.debug("the cache has entries, the object size used {}, calculated by beepSize {}", size(), CONFLICTTXSTREAM_OBJ_SIZE, cacheEntries.isEmpty() ? 0 : MetricsUtils.sizeOf.deepSizeOf(cacheEntries.peek())); return size()*(ENTRY_OVERHEAD + CONFLICTTXSTREAM_OBJ_SIZE); }
Source:
private void checkFailedAccess( HttpClient httpClient, HttpMethod method, String url, String clientDesc, Class expectedException, String expectedExceptionMsg ) { int retries = 0; while (true) { try { makeRequest(httpClient, method, url, null, -1); } catch (RuntimeException re) { Throwable rootCause = Throwables.getRootCause(re); if (rootCause instanceof IOException && ("Broken pipe".equals(rootCause.getMessage()) || "Connection reset by peer".contains(rootCause.getMessage()))) { if (retries > MAX_CONNECTION_EXCEPTION_RETRIES) { Assert.fail(StringUtils.format( "Broken pipe retries exhausted, test failed, did not get %s.", expectedException )); } else { retries += 1; continue; } } Assert.assertTrue( expectedException.isInstance(rootCause), StringUtils.format("Expected %s but found %s instead.", expectedException, rootCause) ); Assert.assertEquals( rootCause.getMessage(), expectedExceptionMsg ); LOG.info("%s client [%s] request failed as expected when accessing [%s]", clientDesc, method, url); return; } Assert.fail(StringUtils.format("Test failed, did not get %s.", expectedException)); } }

Target:
private void checkFailedAccess( HttpClient httpClient, HttpMethod method, String url, String clientDesc, Class expectedException, String expectedExceptionMsg ) { int retries = 0; while (true) { try { makeRequest(httpClient, method, url, null, -1); } catch (RuntimeException re) { Throwable rootCause = Throwables.getRootCause(re); if (rootCause instanceof IOException && ("Broken pipe".equals(rootCause.getMessage()) || "Connection reset by peer".contains(rootCause.getMessage()))) { if (retries > MAX_CONNECTION_EXCEPTION_RETRIES) { Assert.fail(StringUtils.format( "Broken pipe / connection reset retries exhausted, test failed, did not get %s.", expectedException )); } else { retries += 1; continue; } } Assert.assertTrue( expectedException.isInstance(rootCause), StringUtils.format("Expected %s but found %s instead.", expectedException, rootCause) ); Assert.assertEquals( rootCause.getMessage(), expectedExceptionMsg ); LOG.info("%s client [%s] request failed as expected when accessing [%s]", clientDesc, method, url); return; } Assert.fail(StringUtils.format("Test failed, did not get %s.", expectedException)); } }
Source:
private MetaConstraint<?> withGetterLocation(ConstraintLocation getterConstraintLocation, MetaConstraint<?> constraint) { ConstraintLocation converted = null; if ( !(constraint.getLocation() instanceof TypeArgumentConstraintLocation) ) { if ( requiresConversionToGetterLocation( getterConstraintLocation, constraint ) ) { converted = getterConstraintLocation; } else { converted = constraint.getLocation(); } } else { Deque<ConstraintLocation> locationStack = new ArrayDeque<>(); ConstraintLocation current = constraint.getLocation(); do { locationStack.addFirst( current ); if ( current instanceof TypeArgumentConstraintLocation ) { current = ( (TypeArgumentConstraintLocation) current ).getDelegate(); } else { current = null; } } while ( current != null ); for ( ConstraintLocation location : locationStack ) { if ( !(location instanceof TypeArgumentConstraintLocation) ) { converted = getterConstraintLocation; } else { converted = ConstraintLocation.forTypeArgument( converted, ( (TypeArgumentConstraintLocation) location ).getTypeParameter(), location.getTypeForValidatorResolution() ); } } } return MetaConstraints.create( typeResolutionHelper, valueExtractorManager, constraint.getDescriptor(), converted ); }

Target:
private MetaConstraint<?> withGetterLocation(ConstraintLocation getterConstraintLocation, MetaConstraint<?> constraint) { ConstraintLocation converted = null; if ( !(constraint.getLocation() instanceof TypeArgumentConstraintLocation) ) { if ( constraint.getLocation() instanceof GetterConstraintLocation ) { converted = constraint.getLocation(); } else { converted = getterConstraintLocation; } } else { Deque<ConstraintLocation> locationStack = new ArrayDeque<>(); ConstraintLocation current = constraint.getLocation(); do { locationStack.addFirst( current ); if ( current instanceof TypeArgumentConstraintLocation ) { current = ( (TypeArgumentConstraintLocation) current ).getDelegate(); } else { current = null; } } while ( current != null ); for ( ConstraintLocation location : locationStack ) { if ( !(location instanceof TypeArgumentConstraintLocation) ) { if ( location instanceof GetterConstraintLocation ) { converted = location; } else { converted = getterConstraintLocation; } } else { converted = ConstraintLocation.forTypeArgument( converted, ( (TypeArgumentConstraintLocation) location ).getTypeParameter(), location.getTypeForValidatorResolution() ); } } } return MetaConstraints.create( typeResolutionHelper, valueExtractorManager, constraint.getDescriptor(), converted ); }
Source:
public static Map<String, Object> defaultHeaders(EventMessage<?> message, SerializedObject<?> serializedObject) { Assert.notNull(message, () -> "Event message cannot be null"); Assert.notNull(serializedObject, () -> "Serialized Object cannot be null"); Assert.notNull(serializedObject.getType(), () -> "SerializedObject Type cannot be null"); return Collections.unmodifiableMap(new HashMap<String, Object>() {{ put(MESSAGE_ID, message.getIdentifier()); put(MESSAGE_TYPE, serializedObject.getType().getName()); put(MESSAGE_REVISION, serializedObject.getType().getRevision()); put(MESSAGE_TIMESTAMP, message.getTimestamp()); }}); }

Target:
public static Map<String, Object> defaultHeaders(EventMessage<?> message, SerializedObject<?> serializedObject) { Assert.notNull(message, () -> "Event message cannot be null"); Assert.notNull(serializedObject, () -> "Serialized Object cannot be null"); Assert.notNull(serializedObject.getType(), () -> "SerializedObject Type cannot be null"); HashMap<String, Object> headers = new HashMap<>(); headers.put(MESSAGE_ID, message.getIdentifier()); headers.put(MESSAGE_TYPE, serializedObject.getType().getName()); headers.put(MESSAGE_REVISION, serializedObject.getType().getRevision()); headers.put(MESSAGE_TIMESTAMP, message.getTimestamp()); if (message instanceof DomainEventMessage) { headers.put(AGGREGATE_ID, ((DomainEventMessage<?>) message).getAggregateIdentifier()); headers.put(AGGREGATE_SEQ, ((DomainEventMessage<?>) message).getSequenceNumber()); headers.put(AGGREGATE_TYPE, ((DomainEventMessage<?>) message).getType()); } return Collections.unmodifiableMap(headers); }
Source:
public void saveUserCredentials_saved_throws() throws IOException { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) .setClientSecret(CLIENT_SECRET) .setRefreshToken(REFRESH_TOKEN) .build(); String filePath = System.getProperty("user.dir") + File.separator + "GOOGLE_APPLICATION_CREDENTIALS"; userCredentials.save(filePath); }

Target:
public void saveUserCredentials_saved_throws() throws IOException { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) .setClientSecret(CLIENT_SECRET) .setRefreshToken(REFRESH_TOKEN) .build(); File file = File.createTempFile("GOOGLE_APPLICATION_CREDENTIALS", null, null); file.deleteOnExit(); String filePath = file.getAbsolutePath(); userCredentials.save(filePath); }
Source:
public boolean[] encode(String contents) { contents = convertToExtended(contents); int length = contents.length(); if (length > 80) { throw new IllegalArgumentException( "Requested contents should be less than 80 digits long after extended, but got " + length); } int codeWidth = (contents.length() + 2 + 2) * 9 + 1; boolean[] result = new boolean[codeWidth]; int pos = appendPattern(result, 0, Code93Reader.ASTERISK_ENCODING); for (int i = 0; i < length; i++) { int indexInString = Code93Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[indexInString]); } int check1 = computeChecksumIndex(contents, 20); pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[check1]); contents += Code93Reader.ALPHABET_STRING.charAt(check1); int check2 = computeChecksumIndex(contents, 15); pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[check2]); pos += appendPattern(result, pos, Code93Reader.ASTERISK_ENCODING); result[pos] = true; return result; }

Target:
public boolean[] encode(String contents) { contents = convertToExtended(contents); int length = contents.length(); if (length > 80) { throw new IllegalArgumentException( "Requested contents should be less than 80 digits long after converting to extended encoding, but got " + length); } int codeWidth = (contents.length() + 2 + 2) * 9 + 1; boolean[] result = new boolean[codeWidth]; int pos = appendPattern(result, 0, Code93Reader.ASTERISK_ENCODING); for (int i = 0; i < length; i++) { int indexInString = Code93Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[indexInString]); } int check1 = computeChecksumIndex(contents, 20); pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[check1]); contents += Code93Reader.ALPHABET_STRING.charAt(check1); int check2 = computeChecksumIndex(contents, 15); pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[check2]); pos += appendPattern(result, pos, Code93Reader.ASTERISK_ENCODING); result[pos] = true; return result; }
Source:
private TaskResult await(GcsClient gcs, String bucket, String object) { StorageObject metadata = pollingWaiter(state, "exists") .withWaitMessage("Object '%s/%s' does not yet exist", bucket, object) .await(pollState -> pollingRetryExecutor(pollState, "poll") .run(s -> gcs.stat(bucket, object))); return TaskResult.defaultBuilder(request) .resetStoreParams(ImmutableList.of(ConfigKey.of("gcs_wait", "last_object"))) .storeParams(storeParams(metadata)) .build(); }

Target:
private TaskResult await(GcsClient gcs, String bucket, String object) { StorageObject metadata = pollingWaiter(state, "exists") .withWaitMessage("Object '%s/%s' does not yet exist", bucket, object) .await(pollState -> pollingRetryExecutor(pollState, "poll") .retryUnless(GoogleJsonResponseException.class, Gcp::isDeterministicException) .run(s -> gcs.stat(bucket, object))); return TaskResult.defaultBuilder(request) .resetStoreParams(ImmutableList.of(ConfigKey.of("gcs_wait", "last_object"))) .storeParams(storeParams(metadata)) .build(); }
Source:
public static String removeVersionFromName(String text) { Pattern pattern = Pattern.compile(VERSION_PATTERN); Matcher matcher = pattern.matcher(text); if (matcher.find()) { log.info("Removed " + text.substring(matcher.start()) + " from " + text); return text.substring(0, matcher.start()); } return text; }

Target:
public static String removeVersionFromName(String text) { Matcher matcher = pattern.matcher(text); if (matcher.find()) { log.debug("Removed " + text.substring(matcher.start()) + " from " + text); return text.substring(0, matcher.start()); } return text; }
Source:
public void handleCommand(String command, String... arguments) { switch (command) { case "setFbo": if (arguments.length != 1) { throw new RuntimeException("Invalid number of arguments; expected 1, received " + arguments.length + "!"); } FBO fbo; switch (arguments[0]) { case "engine:fbo.gBuffer": case "engine:fbo.lastUpdatedGBuffer": fbo = lastUpdatedGBuffer; break; case "engine:fbo.staleGBuffer": fbo = staleGBuffer; break; default: fbo = displayResolutionDependentFBOs.get(new SimpleUri(arguments[0])); if (fbo == null) { throw new RuntimeException("Invalid fbo uri: " + arguments[0] + "!"); } break; } setFbo(fbo); break; default: throw new RuntimeException("Invalid command: " + command + "!"); } }

Target:
public void handleCommand(String command, String... arguments) { switch (command) { case "setFbo": if (arguments.length != 1) { throw new RuntimeException("Invalid number of arguments; expected 1, received " + arguments.length + "!"); } FBO fbo; switch (arguments[0]) { case "engine:fbo.gBuffer": case "engine:fbo.lastUpdatedGBuffer": fbo = lastUpdatedGBuffer; break; case "engine:fbo.staleGBuffer": fbo = staleGBuffer; break; default: fbo = displayResolutionDependentFBOs.get(new SimpleUri(arguments[0])); if (fbo == null) { throw new RuntimeException(("No FBO is associated with URI '" + arguments[0] + "'")); } break; } setFbo(fbo); break; default: throw new RuntimeException("Unrecognized command: '" + command + "'"); } }
Source:
public void spec203_mustNotCallMethodsOnSubscriptionOrPublisherInOnError() throws Throwable { subscriberTestWithoutSetup(new TestStageTestRun() { @Override public void run(WhiteboxTestStage stage) throws Throwable { final Subscription subs = new Subscription() { @Override public void request(long n) { Throwable thr = new Throwable(); for (StackTraceElement stackElem : thr.getStackTrace()) { if (stackElem.getMethodName().equals("onError")) { env.flop(String.format("Subscription::request MUST NOT be called from Subscriber::onError! (Caller: %s::%s line %d)", stackElem.getClassName(), stackElem.getMethodName(), stackElem.getLineNumber())); } } } @Override public void cancel() { Throwable thr = new Throwable(); for (StackTraceElement stackElem : thr.getStackTrace()) { if (stackElem.getMethodName().equals("onError")) { env.flop(String.format("Subscription::cancel MUST NOT be called from Subscriber::onError! (Caller: %s::%s line %d)", stackElem.getClassName(), stackElem.getMethodName(), stackElem.getLineNumber())); } } } }; stage.probe = stage.createWhiteboxSubscriberProbe(env); final Subscriber<T> sub = createSubscriber(stage.probe); sub.onSubscribe(subs); sub.onError(new Throwable("Test Exception: Boom!")); env.verifyNoAsyncErrors(); } }); }

Target:
public void spec203_mustNotCallMethodsOnSubscriptionOrPublisherInOnError() throws Throwable { subscriberTestWithoutSetup(new TestStageTestRun() { @Override public void run(WhiteboxTestStage stage) throws Throwable { final Subscription subs = new Subscription() { @Override public void request(long n) { Throwable thr = new Throwable(); for (StackTraceElement stackElem : thr.getStackTrace()) { if (stackElem.getMethodName().equals("onError")) { env.flop(String.format("Subscription::request MUST NOT be called from Subscriber::onError (Rule 2.3)! (Caller: %s::%s line %d)", stackElem.getClassName(), stackElem.getMethodName(), stackElem.getLineNumber())); } } } @Override public void cancel() { Throwable thr = new Throwable(); for (StackTraceElement stackElem : thr.getStackTrace()) { if (stackElem.getMethodName().equals("onError")) { env.flop(String.format("Subscription::cancel MUST NOT be called from Subscriber::onError (Rule 2.3)! (Caller: %s::%s line %d)", stackElem.getClassName(), stackElem.getMethodName(), stackElem.getLineNumber())); } } } }; stage.probe = stage.createWhiteboxSubscriberProbe(env); final Subscriber<T> sub = createSubscriber(stage.probe); sub.onSubscribe(subs); sub.onError(new TestException()); env.verifyNoAsyncErrors(); } }); }
Source:
public FileMode getIndexFileMode(final DirCacheIterator indexIter) { final FileMode wtMode = getEntryFileMode(); if (indexIter != null && !getOptions().isFileMode() && FileMode.REGULAR_FILE == wtMode && FileMode.EXECUTABLE_FILE == indexIter.getEntryFileMode()) return FileMode.EXECUTABLE_FILE; return wtMode; }

Target:
public FileMode getIndexFileMode(final DirCacheIterator indexIter) { final FileMode wtMode = getEntryFileMode(); if (indexIter == null) return wtMode; if (getOptions().isFileMode()) return wtMode; final FileMode iMode = indexIter.getEntryFileMode(); if (FileMode.REGULAR_FILE == wtMode && FileMode.EXECUTABLE_FILE == iMode) return iMode; if (FileMode.EXECUTABLE_FILE == wtMode && FileMode.REGULAR_FILE == iMode) return iMode; return wtMode; }
Source:
private void resetPreferences() { IPreferenceStore prefs = DiagramUIPlugin.getPlugin().getPreferenceStore(); for (String key : oldValueDiagramUIPreferences.keySet()) { prefs.setValue(key, (Boolean) oldValueDiagramUIPreferences.get(key)); } boolean currentUiPreference = prefs.getBoolean(SiriusDiagramUiPreferencesKeys.PREF_OLD_UI.name()); if (currentUiPreference) { System.out.println("This test has not reset the oldUiPreference : " + this.getClass().getName() + " (it is currently true)."); } IPreferenceStore platformPrefs = PlatformUI.getPreferenceStore(); for (String key : oldPlatformUIPreferences.keySet()) { platformPrefs.setValue(key, (Boolean) oldPlatformUIPreferences.get(key)); } IPreferenceStore viewpointUIPrefs = SiriusEditPlugin.getPlugin().getPreferenceStore(); for (String key : oldValueSiriusUIPreferences.keySet()) { viewpointUIPrefs.setValue(key, (Boolean) oldValueSiriusUIPreferences.get(key)); } IEclipsePreferences corePreferences = InstanceScope.INSTANCE.getNode(SiriusPlugin.ID); for (String key : oldValueSiriusPreferences.keySet()) { corePreferences.putBoolean(key, (Boolean) oldValueSiriusPreferences.get(key)); } }

Target:
private void resetPreferences() { IEclipsePreferences diagamCorePreferences = InstanceScope.INSTANCE.getNode(DiagramPlugin.ID); for (String key : oldValueDiagramPreferences.keySet()) { resetDiagramPreference(key, diagamCorePreferences); } IPreferenceStore diagramUIPreferences = DiagramUIPlugin.getPlugin().getPreferenceStore(); for (String key : oldValueDiagramUIPreferences.keySet()) { resetDiagramUIPreference(key, diagramUIPreferences); } boolean currentUiPreference = diagramUIPreferences.getBoolean(SiriusDiagramUiPreferencesKeys.PREF_OLD_UI.name()); if (currentUiPreference) { System.out.println("This test has not reset the oldUiPreference : " + this.getClass().getName() + " (it is currently true)."); } IPreferenceStore platformPrefs = PlatformUI.getPreferenceStore(); for (String key : oldPlatformUIPreferences.keySet()) { platformPrefs.setValue(key, (Boolean) oldPlatformUIPreferences.get(key)); } IPreferenceStore viewpointUIPrefs = SiriusEditPlugin.getPlugin().getPreferenceStore(); for (String key : oldValueSiriusUIPreferences.keySet()) { viewpointUIPrefs.setValue(key, (Boolean) oldValueSiriusUIPreferences.get(key)); } IEclipsePreferences corePreferences = InstanceScope.INSTANCE.getNode(SiriusPlugin.ID); for (String key : oldValueSiriusPreferences.keySet()) { corePreferences.putBoolean(key, (Boolean) oldValueSiriusPreferences.get(key)); } }
Source:
public void initialize(URL location, ResourceBundle resources) { setData(); ps.configProperty().addListener(pc -> cs.setSelectedDate(LocalDate.now())); }

Target:
public void initialize(URL location, ResourceBundle resources) { setData(); }
Source:
private String getClientEngineUrl(BootstrapContext context) { final boolean productionMode = context.getSession() .getConfiguration().isProductionMode(); ResourceProvider resourceProvider = context.getSession() .getService().getContext().getAttribute(Lookup.class) .lookup(ResourceProvider.class); String clientEngine = getClientEngine(resourceProvider); boolean resolveNow = !productionMode || clientEngine == null; if (resolveNow && resourceProvider.getClientResource("/META-INF/resources/" + CLIENT_ENGINE_NOCACHE_FILE) != null) { return context.getUriResolver().resolveVaadinUri( "context://" + CLIENT_ENGINE_NOCACHE_FILE); } if (clientEngine == null) { throw new BootstrapException( "Client engine file name has not been resolved during initialization"); } return context.getUriResolver() .resolveVaadinUri("context://" + clientEngine); }

Target:
private String getClientEngineUrl(BootstrapContext context) { final boolean productionMode = context.getSession() .getConfiguration().isProductionMode(); ResourceProvider resourceProvider = getResourceProvider(context); String clientEngine = getClientEngine(resourceProvider); boolean resolveNow = !productionMode || clientEngine == null; if (resolveNow && resourceProvider.getClientResource("/META-INF/resources/" + CLIENT_ENGINE_NOCACHE_FILE) != null) { return context.getUriResolver().resolveVaadinUri( "context://" + CLIENT_ENGINE_NOCACHE_FILE); } if (clientEngine == null) { throw new BootstrapException( "Client engine file name has not been resolved during initialization"); } return context.getUriResolver() .resolveVaadinUri("context://" + clientEngine); }
Source:
private static byte[] clearZeroBytesFromString(byte[] data, int maxLength) { if (data == null) return null; ByteArrayOutputStream dataOut = new ByteArrayOutputStream() ; int limit = (maxLength < data.length) ? maxLength - 4 : data.length; for (int i = 0; i < limit; i++) { if (data[i] != 0x00) dataOut.write(data[i]); } if (maxLength < data.length) { if (data[limit-1] < 0 && data[limit-1] >= (byte)0xC0) { dataOut.write(data[limit]); } if (data[limit-1] < 0 && data[limit-1] >= (byte)0xE0) { dataOut.write(data[limit+1]); } if (data[limit-1] < 0 && data[limit-1] >= (byte)0xF0) { dataOut.write(data[limit+2]); } } return dataOut.toByteArray(); }

Target:
private static byte[] clearZeroBytesFromString(byte[] data, int maxLength) { if (data == null) return null; ByteArrayOutputStream dataOut = new ByteArrayOutputStream() ; int limit = (maxLength < data.length) ? maxLength - 4 : data.length; for (int i = 0; i < limit; i++) { if (data[i] != 0x00) dataOut.write(data[i]); } if(maxLength < data.length) { if(data[limit-1] >= 0xC0 ) { dataOut.write(data[limit]); } if(data[limit-1] >= 0xE0 ) { dataOut.write(data[limit+1]); } if(data[limit-1] >= 0xF0 ) { dataOut.write(data[limit+2]); } } return dataOut.toByteArray(); }
Source:
public void createObjectFromJson_streamNullClass() throws IOException { InputStream in = TestHelper.loadJsonFromAssets(context, "array.json"); realm.beginTransaction(); AnnotationTypes result = realm.createObjectFromJson(null, in); realm.cancelTransaction(); in.close(); assertNull(result); }

Target:
public void createObjectFromJson_streamNullClass() throws IOException { InputStream in = TestHelper.loadJsonFromAssets(context, "array.json"); realm.beginTransaction(); assertNull(realm.createObjectFromJson(null, in)); realm.commitTransaction(); in.close(); }
Source:
private static void clickColumn(final SWTBotTree tree, SWTBotTreeColumn processColumn, SWTBotTestCondition condition) { processColumn.click(); SWTBotUtils.delay(1000); tree.pressShortcut(Keystrokes.HOME); SWTBotUtils.delay(2000); fBot.waitUntil(condition); }

Target:
private static void clickColumn(final SWTBotTree tree, SWTBotTreeColumn processColumn, SWTBotTestCondition condition) { processColumn.click(); fBot.waitUntil(condition); }
Source:
void doOnProcessorChange(List<String> processors) { List<String> currentProcessorIds = getActualProcessorIds(processors); Set<String> uniqueProcessorIds = new HashSet<String>(currentProcessorIds); if (currentProcessorIds.size() != uniqueProcessorIds.size()) { LOG.info("Processors: has duplicates. Not generating job model.", currentProcessorIds); return; } JobModel jobModel = generateNewJobModel(currentProcessorIds); if (!hasCreatedStreams) { CheckpointManagerUtil.createAndInit(jobModel, metrics.getMetricsRegistry()); ChangelogPartitionManager.createChangeLogStreams(this.getClass().getSimpleName(), jobModel); hasCreatedStreams = true; } String currentJMVersion = zkUtils.getJobModelVersion(); String nextJMVersion; if (currentJMVersion == null) { nextJMVersion = "1"; } else { nextJMVersion = Integer.toString(Integer.valueOf(currentJMVersion) + 1); } LOG.info("pid=" + processorId + "Generated new Job Model. Version = " + nextJMVersion); zkUtils.publishJobModel(nextJMVersion, jobModel); barrier.create(nextJMVersion, currentProcessorIds); zkUtils.publishJobModelVersion(currentJMVersion, nextJMVersion); LOG.info("pid=" + processorId + "Published new Job Model. Version = " + nextJMVersion); debounceTimer.scheduleAfterDebounceTime(ON_ZK_CLEANUP, 0, () -> zkUtils.cleanupZK(NUM_VERSIONS_TO_LEAVE)); }

Target:
void doOnProcessorChange(List<String> processors) { List<String> currentProcessorIds = getActualProcessorIds(processors); Set<String> uniqueProcessorIds = new HashSet<String>(currentProcessorIds); if (currentProcessorIds.size() != uniqueProcessorIds.size()) { LOG.info("Processors: has duplicates. Not generating job model.", currentProcessorIds); return; } JobModel jobModel = generateNewJobModel(currentProcessorIds); if (!hasCreatedStreams) { CheckpointManager checkpointManager = new TaskConfigJava(jobModel.getConfig()).getCheckpointManager(metrics.getMetricsRegistry()); if (checkpointManager != null) { checkpointManager.createResources(); } ChangelogStreamManager.createChangelogStreams(jobModel.getConfig(), jobModel.maxChangeLogStreamPartitions); hasCreatedStreams = true; } String currentJMVersion = zkUtils.getJobModelVersion(); String nextJMVersion = zkUtils.getNextJobModelVersion(currentJMVersion); LOG.info("pid=" + processorId + "Generated new Job Model. Version = " + nextJMVersion); zkUtils.publishJobModel(nextJMVersion, jobModel); barrier.create(nextJMVersion, currentProcessorIds); zkUtils.publishJobModelVersion(currentJMVersion, nextJMVersion); LOG.info("pid=" + processorId + "Published new Job Model. Version = " + nextJMVersion); debounceTimer.scheduleAfterDebounceTime(ON_ZK_CLEANUP, 0, () -> zkUtils.cleanupZK(NUM_VERSIONS_TO_LEAVE)); }
Source:
public RecentWikiActivity goBackToRWA() { wait.forElementClickable(backArrow); backArrow.click(); loading.handleAsyncPageReload(); PageObjectLogging.logInfo("The arrow that redirect user back to RWA was clicked"); Assertion.assertTrue(driver.getCurrentUrl().contains(URLsContent.RECENT_WIKI_ACTIVITY), "You were not redirected to the recent wiki activity"); PageObjectLogging.logInfo("You were redirected to the recent wiki activity"); return this; }

Target:
public RecentWikiActivity goBackToRWA() { wait.forElementClickable(backArrow); backArrow.click(); loading.handleAsyncPageReload(); PageObjectLogging.logInfo("The arrow that redirect user back to RWA was clicked"); return this; }
Source:
public static ParseNode getViewWhereWithViewTTL(StatementContext context, PTable table) throws SQLException { ParseNode viewWhere = null; Long nowTS = context.getConnection().getSCN() == null ? EnvironmentEdgeManager.currentTimeMillis() : context.getConnection().getSCN(); String viewStatement = null; String viewTTLFilterClause = String.format( "((%d - TO_NUMBER(phoenix_row_timestamp())) < %d)", nowTS, table.getViewTTL()); if (table.getViewStatement() != null) { viewStatement = table.getViewStatement(); } else if (table.getType() == PTableType.INDEX) { String schemaName = table.getParentSchemaName().getString(); String tableName = table.getParentTableName().getString(); PTable dataTable = PhoenixRuntime.getTable(context.getConnection(), SchemaUtil.getTableName(schemaName, tableName)); viewStatement = IndexUtil .rewriteViewStatement(context.getConnection(), table, dataTable, dataTable.getViewStatement()); } if (viewStatement != null) { ParseNodeFactory nodeFactory = new ParseNodeFactory(); ParseNode viewTTLFilter = SQLParser.parseCondition(viewTTLFilterClause); ParseNode viewStmtWhere = new SQLParser(viewStatement).parseQuery().getWhere(); List<ParseNode> children = Lists.newArrayList(viewStmtWhere, viewTTLFilter); viewWhere = nodeFactory.and(children); } return viewWhere; }

Target:
public static ParseNode getViewWhereWithViewTTL(StatementContext context, PTable table) throws SQLException { ParseNode viewWhere = null; String viewStatement = null; String viewTTLFilterClause = context.getConnection().getSCN() == null ? String.format( "((TO_NUMBER(CURRENT_TIME()) - TO_NUMBER(phoenix_row_timestamp())) < %d)", table.getViewTTL()) : String.format( "((%d - TO_NUMBER(phoenix_row_timestamp())) < %d)", context.getConnection().getSCN(), table.getViewTTL()); if (table.getViewStatement() != null) { viewStatement = table.getViewStatement(); } else if (table.getType() == PTableType.INDEX) { String schemaName = table.getParentSchemaName().getString(); String tableName = table.getParentTableName().getString(); PTable dataTable = PhoenixRuntime.getTable(context.getConnection(), SchemaUtil.getTableName(schemaName, tableName)); viewStatement = IndexUtil .rewriteViewStatement(context.getConnection(), table, dataTable, dataTable.getViewStatement()); } if (viewStatement != null) { ParseNodeFactory nodeFactory = new ParseNodeFactory(); ParseNode viewTTLFilter = SQLParser.parseCondition(viewTTLFilterClause); ParseNode viewStmtWhere = new SQLParser(viewStatement).parseQuery().getWhere(); List<ParseNode> children = Lists.newArrayList(viewStmtWhere, viewTTLFilter); viewWhere = nodeFactory.and(children); } return viewWhere; }