auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Position scrollToColumnHeader(Position position, int headerRow, int scrollableColumn) { int column = scrollViewport(position, position.row, scrollableColumn).column; return new Position(headerRow, column); }

Target:
public Position scrollToColumnHeader(Position position, int headerRow, int scrollableColumn) { Position viewportPosition = new Position(position); ViewportLayer viewportLayer = getViewportLayer(viewportPosition); if (viewportLayer == null) { throw new IllegalArgumentException("No viewport layer found at position " + position); } int scrollableRow = viewportLayer.localToUnderlyingRowPosition(viewportPosition.row); int column = scrollViewport(position, scrollableRow, scrollableColumn).column; return new Position(headerRow, column); }
Source:
protected String getExpressionForOperation(InitialOperation initialOperation) { if (initialOperation != null) { Optional<SiriusInitialOperationAdapter> optionalAdapter = initialOperation.eAdapters().stream().filter(SiriusInitialOperationAdapter.class::isInstance) .map(SiriusInitialOperationAdapter.class::cast).findFirst(); String expression = optionalAdapter.map(SiriusInitialOperationAdapter::getInitialOperationURI).orElseGet(() -> EcoreUtil.getURI(initialOperation).toString()); expression = expression.replace("'", "\\'"); return MessageFormat.format("aql:input.executeOperation(self, ''{0}'')", expression); } return null; }

Target:
protected String getExpressionForOperation(InitialOperation initialOperation) { if (initialOperation != null) { String expression = ""; Adapter adapter = EcoreUtil.getExistingAdapter(initialOperation, SiriusInitialOperationAdapter.class); if (adapter instanceof SiriusInitialOperationAdapter) { expression = ((SiriusInitialOperationAdapter) adapter).getInitialOperationURI().toString(); } else { expression = EcoreUtil.getURI(initialOperation).toString(); } expression = expression.replace("'", "\\'"); return MessageFormat.format("aql:input.executeOperation(self, ''{0}'')", expression); } return null; }
Source:
protected void restore(Bundle savedInstanceState) { blocksApiVersion = config.getApiUrlVersionConfig().getBlocksApiVersion(); courseData = (EnrolledCoursesResponse) savedInstanceState.getSerializable(Router.EXTRA_COURSE_DATA); courseUpgradeData = (CourseUpgradeResponse) savedInstanceState.getParcelable(Router.EXTRA_COURSE_UPGRADE_DATA); courseComponentId = savedInstanceState.getString(Router.EXTRA_COURSE_COMPONENT_ID); if (courseComponentId == null) { final String courseId = courseData.getCourse().getId(); getHierarchyCall = courseApi.getCourseStructure(blocksApiVersion, courseId); getHierarchyCall.enqueue(new CourseAPI.GetCourseStructureCallback(this, courseId, new ProgressViewController(progressWheel), errorNotification, snackbarErrorNotification, this) { @Override protected void onResponse(@NonNull final CourseComponent courseComponent) { courseComponentId = courseComponent.getId(); invalidateOptionsMenu(); onLoadData(); } @Override protected void onFinish() { isInitialServerCallDone = true; } }); } }

Target:
protected void restore(Bundle savedInstanceState) { blocksApiVersion = config.getApiUrlVersionConfig().getBlocksApiVersion(); courseData = (EnrolledCoursesResponse) savedInstanceState.getSerializable(Router.EXTRA_COURSE_DATA); courseUpgradeData = savedInstanceState.getParcelable(Router.EXTRA_COURSE_UPGRADE_DATA); courseComponentId = savedInstanceState.getString(Router.EXTRA_COURSE_COMPONENT_ID); if (courseComponentId == null) { final String courseId = courseData.getCourse().getId(); getHierarchyCall = courseApi.getCourseStructure(blocksApiVersion, courseId); getHierarchyCall.enqueue(new CourseAPI.GetCourseStructureCallback(this, courseId, new ProgressViewController(progressWheel), errorNotification, snackbarErrorNotification, this) { @Override protected void onResponse(@NonNull final CourseComponent courseComponent) { courseComponentId = courseComponent.getId(); invalidateOptionsMenu(); onLoadData(); } @Override protected void onFinish() { isInitialServerCallDone = true; } }); } }
Source:
private void loadData(int episodeId, int showId) { Observable<Integer> userShowEpisodesObservable = client.profileEpisodesOfShow(showId) .defaultIfEmpty(new UserShowEpisodes(showId, Collections.emptyList())) .map(userShowEpisodes -> extractMyRating(userShowEpisodes, episodeId)) .subscribeOn(Schedulers.computation()); Observable.combineLatest(client.episodeInformation(episodeId), client.comments(episodeId), userShowEpisodesObservable, ActivityInformation::new) .compose(bindToLifecycle()) .subscribe(this::bind); }

Target:
private void loadData(int episodeId, int showId) { Observable<Integer> userShowEpisodesObservable = client.profileEpisodesOfShow(showId) .defaultIfEmpty(new UserShowEpisodes(showId, Collections.emptyList())) .observeOn(Schedulers.computation()) .map(userShowEpisodes -> extractMyRating(userShowEpisodes, episodeId)) .observeOn(AndroidSchedulers.mainThread()); Observable.combineLatest(client.episodeInformation(episodeId), client.comments(episodeId), userShowEpisodesObservable, ActivityInformation::new) .compose(bindToLifecycle()) .subscribe(this::bind); }
Source:
public String getGsCredentialsPath() { return getString("secor.gs.credentials.path", null); }

Target:
public String getGsCredentialsPath() { return getString("secor.gs.credentials.path"); }
Source:
public void foo(String r) { String init = "Bob is a Bird... Bob is a Plane... Bob is Superman!"; String changed = init.replaceAll("Bob is", "It's"); changed = init.replaceAll("\\w*\\sis", "It's"); changed = init.replaceAll(r, "It's"); changed = init.replaceAll(".", "It's"); changed = init.replaceAll("$", "It's"); changed = init.replaceAll("|", "It's"); changed = init.replaceAll("(", "It's"); changed = init.replaceAll(")", "It's"); changed = init.replaceAll("[", "It's"); changed = init.replaceAll("{", "It's"); changed = init.replaceAll("^", "It's"); changed = init.replaceAll("?", "It's"); changed = init.replaceAll("*", "It's"); changed = init.replaceAll("+", "It's"); changed = init.replaceAll("\\", "It's"); }

Target:
public void foo(String r) { String init = "Bob is a Bird... Bob is a Plane... Bob is Superman!"; String changed = init.replaceAll("Bob is", "It's"); changed = init.replaceAll("\\w*\\sis", "It's"); changed = init.replaceAll(r, "It's"); changed = init.replaceAll(".", "It's"); changed = init.replaceAll("$", "It's"); changed = init.replaceAll("|", "It's"); changed = init.replaceAll("(", "It's"); changed = init.replaceAll("[", "It's"); changed = init.replaceAll("{", "It's"); changed = init.replaceAll("^", "It's"); changed = init.replaceAll("?", "It's"); changed = init.replaceAll("*", "It's"); changed = init.replaceAll("+", "It's"); changed = init.replaceAll("\\", "It's"); }
Source:
public synchronized Map<Object, Object> getMap() throws IOException { if (valuesMap == null) { HttpURLConnection urlConnection = createURLConnection(url); InputStreamReader reader = request(urlConnection); this.valuesMap = reader!=null?read(reader):new HashMap<Object, Object>(); } return valuesMap; }

Target:
public synchronized Map<Object, Object> getMap() throws IOException { if (valuesMap == null) { HttpURLConnection urlConnection = createURLConnection(url); InputStreamReader reader = request(urlConnection); if(reader != null) { try { Properties pr = new Properties(); pr.load(reader); valuesMap = pr; } finally { reader.close(); } } if(valuesMap == null) { valuesMap = Collections.emptyMap(); } } return valuesMap; }
Source:
public void within(double seconds, Closure<?> conditions) throws InterruptedException { long timeoutMillis = toMillis(seconds); long start = System.currentTimeMillis(); long lastAttempt = 0; if (initialDelay > 0) { Thread.sleep(toMillis(initialDelay)); } long currDelay = toMillis(delay); int attempts = 0; long elapsedTime = 0; Throwable testException = null; while (elapsedTime <= timeoutMillis) { try { try { GroovyRuntimeUtil.invokeClosure(conditions); } finally { lastAttempt = System.currentTimeMillis(); attempts++; } return; } catch (Throwable e) { testException = e; elapsedTime = lastAttempt - start; final long timeout = Math.min(currDelay, start + timeoutMillis - System.currentTimeMillis()); if (timeout > 0) { Thread.sleep(timeout); } currDelay *= factor; } } String msg = String.format("Condition not satisfied after %1.2f seconds and %d attempts", elapsedTime / 1000d, attempts); throw new SpockTimeoutError(seconds, msg, testException); }

Target:
public void within(double seconds, Closure<?> conditions) throws InterruptedException { long timeoutMillis = toMillis(seconds); long start = System.currentTimeMillis(); if (initialDelay > 0) { Thread.sleep(toMillis(initialDelay)); } long currDelay = toMillis(delay); int attempts = 0; long elapsedTime = 0; Throwable testException = null; while (elapsedTime <= timeoutMillis) { try { attempts++; GroovyRuntimeUtil.invokeClosure(conditions); return; } catch (Throwable e) { elapsedTime = System.currentTimeMillis() - start; testException = e; final long sleepMillis = Math.min(currDelay, start + timeoutMillis - System.currentTimeMillis()); if (sleepMillis > 0) { Thread.sleep(sleepMillis); } currDelay *= factor; } } String msg = String.format("Condition not satisfied after %1.2f seconds and %d attempts", elapsedTime / 1000d, attempts); throw new SpockTimeoutError(seconds, msg, testException); }
Source:
private boolean doPoll() { IntegrationResourceHolder holder = this.bindResourceHolderIfNecessary( this.getResourceKey(), this.getResourceToBind()); Message<?> message = null; try { message = this.receiveMessage(); } catch (Exception e) { if (Thread.interrupted()) { if (logger.isDebugEnabled()) { logger.debug("Poll interrupted - during stop()? : " + e.getMessage()); } return false; } else { throw (RuntimeException) e; } } boolean result; if (message == null) { if (this.logger.isDebugEnabled()) { this.logger.debug("Received no Message during the poll, returning 'false'"); } result = false; } else { if (this.logger.isDebugEnabled()) { this.logger.debug("Poll resulted in Message: " + message); } if (holder != null) { holder.setMessage(message); } try { this.handleMessage(message); } catch (Exception e) { if (e instanceof MessagingException) { throw new OriginalMessageContainingMessagingException(message, (MessagingException) e); } else { throw new MessagingException(message, e); } } result = true; } return result; }

Target:
private boolean doPoll() { IntegrationResourceHolder holder = this.bindResourceHolderIfNecessary( this.getResourceKey(), this.getResourceToBind()); Message<?> message = null; try { message = this.receiveMessage(); } catch (Exception e) { if (Thread.interrupted()) { if (logger.isDebugEnabled()) { logger.debug("Poll interrupted - during stop()? : " + e.getMessage()); } return false; } else { throw (RuntimeException) e; } } boolean result; if (message == null) { if (this.logger.isDebugEnabled()) { this.logger.debug("Received no Message during the poll, returning 'false'"); } result = false; } else { if (this.logger.isDebugEnabled()) { this.logger.debug("Poll resulted in Message: " + message); } if (holder != null) { holder.setMessage(message); } try { this.handleMessage(message); } catch (Exception e) { if (e instanceof MessagingException) { throw new MessagingExceptionWrapper(message, (MessagingException) e); } else { throw new MessagingException(message, e); } } result = true; } return result; }
Source:
public void canDoReverseLookups() throws UnknownHostException, ExecutionException, InterruptedException { assertThat(dnsResolver.reverseLookup(InetAddress.getByName("173.242.186.51")).get().get(), equalTo("rnd.opennms.ca")); assertThat(dnsResolver.reverseLookup(InetAddress.getByName("1.1.1.1")).get(), equalTo(Optional.empty())); assertThat(dnsResolver.reverseLookup(InetAddressUtils.addr("fe80::")).get(), equalTo(Optional.empty())); }

Target:
public void canDoReverseLookups() throws UnknownHostException, ExecutionException, InterruptedException { assertThat(dnsResolver.reverseLookup(InetAddress.getByName("173.242.186.51")).get().get(), equalTo("rnd.opennms.ca")); assertThat(dnsResolver.reverseLookup(InetAddress.getByName("2600:5800:fc29:0003:0000:0000:0000:0001")).get().get(), equalTo("secret.opennms.com")); assertThat(dnsResolver.reverseLookup(InetAddress.getByName("1.1.1.1")).get(), equalTo(Optional.empty())); assertThat(dnsResolver.reverseLookup(InetAddressUtils.addr("2606:4700:4700::1111")).get(), equalTo(Optional.empty())); }
Source:
public static Entry create(String accountId, String bucketId, String contentType, String fileId, Map<String, String> fileInfo, String fileName, long uploadTimestamp) { return new AutoValue_ListUnfinishedLargeFilesResponse_Entry(accountId, bucketId, contentType, fileId, fileInfo, fileName, new Date(uploadTimestamp)); }

Target:
public static Entry create(String accountId, String bucketId, String contentType, String fileId, Map<String, String> fileInfo, String fileName, long uploadTimestamp) { return new AutoValue_ListUnfinishedLargeFilesResponse_Entry(accountId, bucketId, contentType, fileId, ImmutableMap.copyOf(fileInfo), fileName, new Date(uploadTimestamp)); }
Source:
public V put(K key, V value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); Data valueData = toData(value); Data result = putInternal(key, valueData, ttl, ttlUnit, maxIdle, maxIdleUnit); return toObject(result); }

Target:
public V put(K key, V value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) { if (isClusterVersionLessThan(V3_11)) { throw new UnsupportedOperationException("put with Max-Idle operation is available " + "when cluster version is 3.11 or higher"); } checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); Data valueData = toData(value); Data result = putInternal(key, valueData, ttl, ttlUnit, maxIdle, maxIdleUnit); return toObject(result); }
Source:
protected int createGammaId() throws OseeCoreException { if (artifact.isUseBackingdata()) { return artifact.getGammaId(); } return ConnectionHandler.getSequence().getNextGammaId(); }

Target:
protected int createGammaId() throws OseeCoreException { return artifact.isUseBackingdata() ? artifact.getGammaId() : ConnectionHandler.getSequence().getNextGammaId(); }
Source:
public FormValidation doCheck(@AncestorInPath AbstractProject project, @QueryParameter String value) { if (project == null) return FormValidation.ok(); if(!project.hasPermission(Item.CONFIGURE)) return FormValidation.ok(); StringTokenizer tokens = new StringTokenizer(Util.fixNull(value),","); boolean hasProjects = false; while(tokens.hasMoreTokens()) { String projectName = tokens.nextToken().trim(); if (StringUtils.isNotBlank(projectName)) { Item item = Jenkins.getInstance().getItem(projectName,project,Item.class); if (item == null) { AbstractProject nearest = AbstractProject.findNearest(projectName,project.getParent()); String alternative = nearest != null ? nearest.getRelativeNameFrom(project) : "?"; return FormValidation.error(Messages.BuildTrigger_NoSuchProject(projectName, alternative)); } if(!(item instanceof AbstractProject)) return FormValidation.error(Messages.BuildTrigger_NotBuildable(projectName)); Authentication auth = Tasks.getAuthenticationOf(project); if (auth.equals(ACL.SYSTEM) && !QueueItemAuthenticatorConfiguration.get().getAuthenticators().isEmpty()) { auth = Jenkins.ANONYMOUS; } if (!item.getACL().hasPermission(auth, Item.BUILD)) { return FormValidation.error(Messages.BuildTrigger_you_have_no_permission_to_build_(projectName)); } hasProjects = true; } } if (!hasProjects) { return FormValidation.error(Messages.BuildTrigger_NoProjectSpecified()); } return FormValidation.ok(); }

Target:
public FormValidation doCheck(@AncestorInPath AbstractProject project, @QueryParameter String value) { if (project == null) return FormValidation.ok(Messages.BuildTrigger_ok_ancestor_is_null()); if(!project.hasPermission(Item.CONFIGURE)) return FormValidation.ok(); StringTokenizer tokens = new StringTokenizer(Util.fixNull(value),","); boolean hasProjects = false; while(tokens.hasMoreTokens()) { String projectName = tokens.nextToken().trim(); if (StringUtils.isNotBlank(projectName)) { Item item = Jenkins.getInstance().getItem(projectName,project,Item.class); if (item == null) { AbstractProject nearest = AbstractProject.findNearest(projectName,project.getParent()); String alternative = nearest != null ? nearest.getRelativeNameFrom(project) : "?"; return FormValidation.error(Messages.BuildTrigger_NoSuchProject(projectName, alternative)); } if(!(item instanceof AbstractProject)) return FormValidation.error(Messages.BuildTrigger_NotBuildable(projectName)); Authentication auth = Tasks.getAuthenticationOf(project); if (auth.equals(ACL.SYSTEM) && !QueueItemAuthenticatorConfiguration.get().getAuthenticators().isEmpty()) { auth = Jenkins.ANONYMOUS; } if (!item.getACL().hasPermission(auth, Item.BUILD)) { return FormValidation.error(Messages.BuildTrigger_you_have_no_permission_to_build_(projectName)); } hasProjects = true; } } if (!hasProjects) { return FormValidation.error(Messages.BuildTrigger_NoProjectSpecified()); } return FormValidation.ok(); }
Source:
public void useEqualsWhenTrueThenCustomMediaTypeIsMatched() throws HttpMediaTypeNotAcceptableException { request.addHeader("Accept", "text/unique"); matcher = new MediaTypeRequestMatcher(new MediaType("text", "unique")); matcher.setUseEquals(true); assertThat(matcher.matches(request)).isTrue(); }

Target:
public void useEqualsWhenTrueThenCustomMediaTypeIsMatched() { request.addHeader("Accept", "text/unique"); matcher = new MediaTypeRequestMatcher(new MediaType("text", "unique")); matcher.setUseEquals(true); assertThat(matcher.matches(request)).isTrue(); }
Source:
public void compute(final A[] input, final A[] output) { ops().run(ChunkerInterleaved.class, new Chunk() { @Override public void execute(long startIndex, final int stepSize, final long numSteps) { int i = (int)startIndex; int ctr = 0; while (ctr < numSteps) { output[i] = input[i]; i += stepSize; ctr++; } } }, input.length); }

Target:
public void compute(final A[] input, final A[] output) { ops().run(ChunkerInterleaved.class, new Chunk() { @Override public void execute(long startIndex, final long stepSize, final long numSteps) { int i = startIndex==0 ? 0 : ArrayUtils.safeMultiply32(startIndex); int stepSizeSafe32 = stepSize == 0 ? 0 : ArrayUtils.safeMultiply32(stepSize); int ctr = 0; while (ctr < numSteps) { output[i] = input[i]; i += stepSizeSafe32; ctr++; } } }, input.length); }
Source:
private void getUserCredentials() { repoSelector.setDisable(true); new LoginDialog(mainStage, columns).show().thenApply(success -> { if (success) { browserComponent.initialise(); setExpandedWidth(false); columns.loadIssues(); triggerEvent(new LoginEvent()); repoSelector.setDisable(false); repoSelector.refreshComboBoxContents(ServiceManager.getInstance().getRepoId().generateId()); triggerEvent(new BoardSavedEvent()); getMenuControl().scrollTo(columns.getCurrentlySelectedColumn().get(), columns.getChildren().size()); } else { quit(); } return true; }).exceptionally(e -> { logger.error(e.getLocalizedMessage(), e); return false; }); }

Target:
private void getUserCredentials() { repoSelector.setDisable(true); new LoginDialog(mainStage, columns).show().thenApply(success -> { if (success) { browserComponent.initialise(); setExpandedWidth(false); columns.loadIssues(); triggerEvent(new LoginEvent()); repoSelector.setDisable(false); repoSelector.refreshComboBoxContents(ServiceManager.getInstance().getRepoId().generateId()); triggerEvent(new BoardSavedEvent()); if(columns.getCurrentlySelectedColumn().isPresent()) { getMenuControl().scrollTo(columns.getCurrentlySelectedColumn().get(), columns.getChildren().size()); } } else { quit(); } return true; }).exceptionally(e -> { logger.error(e.getLocalizedMessage(), e); return false; }); }
Source:
public Result close() throws IOException { try { if (commitStep > 1 && commitCounter > 0 && connection != null && statement != null) { cleanWrites(); connection.commit(); connection.setAutoCommit(true); commitCounter = 0; } if (rs != null) { rs.close(); } if (statement != null) { statement.close(); } sink.closeConnection(container, connection); } catch (SQLException e) { throw new IOException(e); } return result; }

Target:
public Result close() throws IOException { try { cleanWrites(); if (commitStep > 1 && commitCounter > 0 && connection != null && statement != null) { connection.commit(); connection.setAutoCommit(true); commitCounter = 0; } if (rs != null) { rs.close(); } if (statement != null) { statement.close(); } sink.closeConnection(container, connection); } catch (SQLException e) { throw new IOException(e); } return result; }
Source:
@Override public IgniteFuture<?> addData(K key, V val) { if (closedStreamer) throw new IllegalStateException("Data streamer has been closed.", cancellationReason); A.notNull(key, "key"); if (val == null) checkSecurityPermission(SecurityPermission.CACHE_REMOVE); else checkSecurityPermission(SecurityPermission.CACHE_PUT); KeyCacheObject key0 = cacheObjProc.toCacheKeyObject(cacheObjCtx, null, key, true); CacheObject val0 = cacheObjProc.toCacheObject(cacheObjCtx, val, true); DataStreamerEntry entry = new DataStreamerEntry(key0, val0); IgniteCacheFutureImpl fut = null; enterBusy(); try { long threadId = Thread.currentThread().getId(); bufMapReadLock.lock(); try { if (!threadBufMap.containsKey(threadId)) { IgniteCacheFutureImpl futPerThread = new IgniteCacheFutureImpl(new GridFutureAdapter()); List<DataStreamerEntry> entriesPerThread = new ArrayList<>(bufLdrSizePerThread); futPerThread.internalFuture().listen(rmvActiveFut); activeFuts.add(futPerThread.internalFuture()); threadBufMap.put(threadId, new IgniteBiTuple(futPerThread, entriesPerThread)); } IgniteBiTuple<IgniteCacheFutureImpl, List<DataStreamerEntry>> futBufPair = threadBufMap.get(threadId); fut = futBufPair.get1(); Collection<DataStreamerEntry> entries = futBufPair.get2(); entries.add(entry); if (entries.size() == bufLdrSizePerThread) { loadData(entries, fut); threadBufMap.remove(threadId); } return fut; } finally { bufMapReadLock.unlock(); } } catch (Throwable e) { if (fut == null) throw e; GridFutureAdapter internalFut = (GridFutureAdapter) fut.internalFuture(); internalFut.onDone(e); if (e instanceof Error || e instanceof IgniteDataStreamerTimeoutException) throw e; return fut; } finally { leaveBusy(); } }

Target:
@Override public IgniteFuture<?> addData(K key, V val) { A.notNull(key, "key"); if (val == null) checkSecurityPermission(SecurityPermission.CACHE_REMOVE); else checkSecurityPermission(SecurityPermission.CACHE_PUT); KeyCacheObject key0 = cacheObjProc.toCacheKeyObject(cacheObjCtx, null, key, true); CacheObject val0 = cacheObjProc.toCacheObject(cacheObjCtx, val, true); return addDataInternal(Collections.singleton(new DataStreamerEntry(key0, val0))); }
Source:
public void testExceptionStoredOnCallingUncaughtException() { assertTrue(sharedPreferences.getString(EXCEPTION_FOR_REPORT, "").isEmpty()); new BaseExceptionHandler().uncaughtExceptionTest(new RuntimeException("Test Error")); assertFalse(sharedPreferences.getString(EXCEPTION_FOR_REPORT, "").isEmpty()); }

Target:
public void testExceptionStoredOnCallingUncaughtException() { assertTrue(sharedPreferences.getString(EXCEPTION_FOR_REPORT, "").isEmpty()); BaseExceptionHandler baseExceptionHandler = new BaseExceptionHandler() { @Override protected void exit() { } }; baseExceptionHandler.uncaughtException(null, new RuntimeException("Test Error")); assertFalse(sharedPreferences.getString(EXCEPTION_FOR_REPORT, "").isEmpty()); }
Source:
private AbstractFile getAbstractFile(String file) { Path path = Paths.get(file); String fileName = path.getFileName().toString(); String filePath = path.getParent().toString().replaceAll("\\\\", "/"); if (filePath.endsWith("/") == false) { filePath += "/"; } if (previousFile != null && previousFile.getName().equalsIgnoreCase(fileName) && previousFile.getParentPath().equalsIgnoreCase(filePath)) { return previousFile; } try { List<AbstractFile> abstractFiles = fileManager.findFiles(fileName, filePath); if (abstractFiles.size() == 1) { return abstractFiles.get(0); } for (AbstractFile resolvedFile : abstractFiles) { if (filePath.toLowerCase().matches(resolvedFile.getParentPath().toLowerCase())) { previousFile = resolvedFile; return resolvedFile; } } } catch (TskCoreException ex) { logger.log(Level.WARNING, Bundle.PlasoIngestModule_exception_find_file(), ex); } return null; }

Target:
private AbstractFile getAbstractFile(String file) { Path path = Paths.get(file); String fileName = path.getFileName().toString(); String filePath = path.getParent().toString().replaceAll("\\\\", "/"); if (filePath.endsWith("/") == false) { filePath += "/"; } if (previousFile != null && previousFile.getName().equalsIgnoreCase(fileName) && previousFile.getParentPath().equalsIgnoreCase(filePath)) { return previousFile; } try { List<AbstractFile> abstractFiles = fileManager.findFiles(fileName, filePath); if (abstractFiles.size() == 1) { return abstractFiles.get(0); } for (AbstractFile resolvedFile : abstractFiles) { if (filePath.equalsIgnoreCase(resolvedFile.getParentPath())) { previousFile = resolvedFile; return resolvedFile; } } } catch (TskCoreException ex) { logger.log(Level.WARNING, Bundle.PlasoIngestModule_exception_find_file(), ex); } return null; }
Source:
public KeycloakDeployment resolve(final HttpFacade.Request request) { Assert.requireNonNull(request, "request"); final String realmName = Optional.ofNullable(request.getHeader(REALM_NAME_HEADER)). orElse(configuration.getRealmName()); final String applicationName = Optional.ofNullable(request.getHeader(APPLICATION_NAME_HEADER)). orElse(configuration.getApplicationName()); final String authEndPoint = configuration.getAuthEndpoint(); Optional.ofNullable(realmName).orElseThrow(() -> new SecurityException("Realm name for security check is not configured!")); Optional.ofNullable(applicationName).orElseThrow(() -> new SecurityException("Application name for security check is not configured!")); Optional.ofNullable(authEndPoint).orElseThrow(() -> new SecurityException("Auth endpoint for security check is not configured!")); final AdapterConfig adapterConfig = new AdapterConfig(); if(isRealmExist(realmName)){ adapterConfig.setRealm(realmName); }else{ throw new SecurityException("Access Denied"); } adapterConfig.setResource(applicationName); adapterConfig.setAuthServerUrl(authEndPoint); Optional.ofNullable(request.getHeader(BEARER_ONLY_HEADER)). ifPresent(v -> adapterConfig.setBearerOnly(true)); return KeycloakDeploymentBuilder.build(adapterConfig); }

Target:
public KeycloakDeployment resolve(final HttpFacade.Request request) { Assert.requireNonNull(request, "request"); final String realmName = Optional.ofNullable(request.getHeader(REALM_NAME_HEADER)). orElse(configuration.getRealmName()); final String applicationName = Optional.ofNullable(request.getHeader(APPLICATION_NAME_HEADER)). orElse(configuration.getApplicationName()); final String authEndPoint = configuration.getAuthEndpoint(); Optional.ofNullable(realmName).orElseThrow(() -> new SecurityException("Realm name for security check is not configured!")); Optional.ofNullable(applicationName).orElseThrow(() -> new SecurityException("Application name for security check is not configured!")); Optional.ofNullable(authEndPoint).orElseThrow(() -> new SecurityException("Auth endpoint for security check is not configured!")); final AdapterConfig adapterConfig = new AdapterConfig(); if(isRealmAllowed(realmName)){ adapterConfig.setRealm(realmName); }else{ throw new SecurityException("Access Denied! The given realm is not in the allowed realms."); } adapterConfig.setResource(applicationName); adapterConfig.setAuthServerUrl(authEndPoint); Optional.ofNullable(request.getHeader(BEARER_ONLY_HEADER)). ifPresent(v -> adapterConfig.setBearerOnly(true)); return KeycloakDeploymentBuilder.build(adapterConfig); }
Source:
public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException { op = ExtUtil.readInt(in); readExpressions(in, pf); computedCacheability = ExtUtil.readBool(in); exprIsCacheable = ExtUtil.readBool(in); computedContextTypes = ExtUtil.readBool(in); contextRefIsRelevant = ExtUtil.readBool(in); originalContextRefIsRelevant = ExtUtil.readBool(in); }

Target:
public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException { op = ExtUtil.readInt(in); readExpressions(in, pf); cacheState = (CacheableExprState)ExtUtil.read(in, CacheableExprState.class, pf); }
Source:
Object[][] samFilesforFingerprinting() { return new Object[][]{ new Object[]{"NA12891.over.fingerprints.r1.sam", true}, new Object[]{"aligned_queryname_sorted.sam", false}, new Object[]{"aligned_unsorted.sam", false}, }; }

Target:
Object[][] samFilesforFingerprinting() { return new Object[][]{ {"NA12891.over.fingerprints.r1.sam", true}, {"aligned_queryname_sorted.sam", false}, {"aligned_unsorted.sam", false}, }; }
Source:
protected void buildScript(int age) { if (age == 0) { init(); } if (age == 0) { addPendingClient(new AnnouncementClient()); } addPendingClient(new AggregatedFeedContentClient()); addPendingClient(new ContinueReadingClient()); if (age == 0) { addPendingClient(new MainPageClient()); } addPendingClient(new BecauseYouReadClient()); if (age == 0) { addPendingClient(new RandomClient()); } }

Target:
protected void buildScript(int age) { if (age == 0) { addPendingClient(new SearchClient()); addPendingClient(new AnnouncementClient()); } addPendingClient(new AggregatedFeedContentClient()); addPendingClient(new ContinueReadingClient()); if (age == 0) { addPendingClient(new MainPageClient()); } addPendingClient(new BecauseYouReadClient()); if (age == 0) { addPendingClient(new RandomClient()); } }
Source:
private Attribute getChangePasswordAttribute(Attribute oldPasswordAttribute, Object oldCredential, Object newPassword) throws DirectoryServerManagerException { String passwordHashMethod = null; if (oldCredential != null) { try { NamingEnumeration passwords = oldPasswordAttribute.getAll(); if (passwords.hasMore()) { byte[] byteArray = (byte[]) passwords.next(); String password = new String(byteArray, java.nio.charset.StandardCharsets.UTF_8); if (password.startsWith("{")) { passwordHashMethod = password.substring(password.indexOf("{") + 1, password.indexOf("}")); } if (!password.equals(getPasswordToStore((String) oldCredential, passwordHashMethod))) { throw new DirectoryServerManagerException("Old password does not match"); } } } catch (NamingException e) { log.error("Unable to retrieve old password details.", e); throw new DirectoryServerManagerException("Could not find old password details", e); } } Attribute passwordAttribute = new BasicAttribute(LDAPServerManagerConstants.LDAP_PASSWORD); passwordAttribute.add(getPasswordToStore((String) newPassword, passwordHashMethod)); return passwordAttribute; }

Target:
private Attribute getChangePasswordAttribute(Attribute oldPasswordAttribute, Object oldCredential, Object newPassword) throws DirectoryServerManagerException { String passwordHashMethod = null; if (oldCredential != null) { try { NamingEnumeration passwords = oldPasswordAttribute.getAll(); if (passwords.hasMore()) { byte[] byteArray = (byte[]) passwords.next(); String password = new String(byteArray, StandardCharsets.UTF_8); if (password.startsWith("{")) { passwordHashMethod = password.substring(password.indexOf("{") + 1, password.indexOf("}")); } if (!password.equals(getPasswordToStore((String) oldCredential, passwordHashMethod))) { throw new DirectoryServerManagerException("Old password does not match"); } } } catch (NamingException e) { log.error("Unable to retrieve old password details.", e); throw new DirectoryServerManagerException("Could not find old password details"); } } Attribute passwordAttribute = new BasicAttribute(LDAPServerManagerConstants.LDAP_PASSWORD); passwordAttribute.add(getPasswordToStore((String) newPassword, passwordHashMethod)); return passwordAttribute; }
Source:
private void verifyShowHide(boolean positive) { if(positive) { when(serviceCaller.call(any(RemoteCallback.class), any(ErrorCallback.class))) .thenAnswer(new LoadContentAnswer(importsService, importsContent, null)); } else { when(serviceCaller.call(any(RemoteCallback.class), any(ErrorCallback.class))) .thenAnswer(new LoadContentAnswer(importsService, importsContent, errorCallback)); } presenter.init(path, placeRequest); verify(view, times(2)).showLoading(); if(positive) { verify(view).hideBusyIndicator(); } else { verify(errorCallback).error(any(Message.class), any(Throwable.class)); } }

Target:
private void verifyShowHide(boolean positive) { when(serviceCaller.call(any(RemoteCallback.class), any(ErrorCallback.class))) .thenAnswer(new LoadContentAnswer(importsService, importsContent, positive ? null : errorCallback)); presenter.init(path, placeRequest); verify(view).showLoading(); if(positive) { verify(view).hideBusyIndicator(); } else { verify(errorCallback).error(any(Message.class), any(Throwable.class)); } }
Source:
private int expectedAssociationNumber() { if ( TestHelper.getCurrentDialectType().equals( GridDialectType.NEO4J ) || TestHelper.getCurrentDialectType().equals( GridDialectType.NEO4J_REMOTE )) { return 1; } else { return 2; } }

Target:
private int expectedAssociationNumber() { if ( EnumSet.of( NEO4J, NEO4J_REMOTE ).contains( TestHelper.getCurrentDialectType() ) ) { return 1; } else { return 2; } }
Source:
public void countActiveUsers() { Metrics.gauge(METRIC_USERS_ACTIVE, this.personService.getActivePersons().size()); }

Target:
void countActiveUsers() { Metrics.gauge(METRIC_USERS_ACTIVE, this.personService.getActivePersons().size()); }
Source:
public static KafkaConsumer<byte[], byte[]> getKafkaConsumerImpl(String systemName, String clientId, Config config) { Map<String, String> injectProps = new HashMap<>(); KafkaConsumerConfig consumerConfig = KafkaConsumerConfig.getKafkaSystemConsumerConfig(config, systemName, clientId, injectProps); LOG.info("KafkaClient properties for systemName {}: {}", systemName, consumerConfig.originals()); return new KafkaConsumer<>(consumerConfig.originals()); }

Target:
public static KafkaConsumer<byte[], byte[]> getKafkaConsumerImpl(String systemName, String clientId, Config config) { KafkaConsumerConfig consumerConfig = KafkaConsumerConfig.getKafkaSystemConsumerConfig(config, systemName, clientId); LOG.info("{}: KafkaClient properties {}", systemName, consumerConfig); return new KafkaConsumer(consumerConfig); }
Source:
public static int getBatchSize(Schema schema) { int batchSize = 1000 * 10; for (int j = 0; j < schema.numColumns(); ++j) { Type type = schema.getColumnType(j); if (type == Type.BLOB_TYPE) { batchSize = 1; } } return batchSize; }

Target:
public static int getBatchSize(Schema schema) { int batchSize = 1000 * 10; if (schema.getColumnTypes().indexOf(Type.BLOB_TYPE) >= 0) batchSize = 1; return batchSize; }
Source:
protected String createFilePath(Object binaryuri) { String path = ""; destMediaPath = ""; if (binaryuri instanceof Uri) { try { path = UriToFilePath.getPathFromUri(CommCareApplication.instance(), (Uri)binaryuri); } catch (UriToFilePath.NoDataColumnForUriException e) { InputStream inputStream; try { inputStream = getContext().getContentResolver().openInputStream((Uri)binaryuri); } catch (FileNotFoundException e1) { showToast("form.attachment.notfound"); e1.printStackTrace(); return ""; } recordedFileName = FileUtil.getFileName(((Uri)binaryuri).getPath()); destMediaPath = mInstanceFolder + System.currentTimeMillis() + FileUtil.getExtension(((Uri)binaryuri).getPath()); try { FileUtil.copyFile(inputStream, new File(destMediaPath)); } catch (IOException e1) { e1.printStackTrace(); showToast("form.attachment.copy.fail"); return ""; } path = destMediaPath; } customFileTag = ""; } else { path = (String)binaryuri; customFileTag = CUSTOM_TAG; } return path; }

Target:
private String createFilePath(Object binaryuri) throws IOException { String path = ""; destMediaPath = ""; if (binaryuri instanceof Uri) { try { path = UriToFilePath.getPathFromUri(CommCareApplication.instance(), (Uri)binaryuri); } catch (UriToFilePath.NoDataColumnForUriException e) { InputStream inputStream = getContext().getContentResolver().openInputStream((Uri)binaryuri); recordedFileName = FileUtil.getFileName(((Uri)binaryuri).getPath()); destMediaPath = mInstanceFolder + System.currentTimeMillis() + FileUtil.getExtension(((Uri)binaryuri).getPath()); FileUtil.copyFile(inputStream, new File(destMediaPath)); path = destMediaPath; } customFileTag = ""; } else { path = (String)binaryuri; customFileTag = CUSTOM_TAG; } return path; }
Source:
public boolean isObjectLegalHoldEnabled(String bucketName, String objectName, String versionId) throws IllegalArgumentException, InsufficientDataException, InternalException, InvalidBucketNameException, InvalidKeyException, InvalidResponseException, IOException, NoSuchAlgorithmException, XmlParserException { Map<String, String> queryParamMap = new HashMap<>(); queryParamMap.put("legal-hold", ""); if (versionId != null && !versionId.isEmpty()) { queryParamMap.put("versionId", versionId); } Response response = null; try { response = executeGet(bucketName, objectName, null, queryParamMap); ResponseBody body = response.body(); LegalHold result = Xml.unmarshal(LegalHold.class, body.charStream()); return result.status(); } catch (ErrorResponseException e) { if (e.errorResponse().errorCode() == ErrorCode.NO_SUCH_OBJECT_LOCK_CONFIGURATION) { return false; } } finally { if (response != null) { response.body().close(); } } return false; }

Target:
public boolean isObjectLegalHoldEnabled(String bucketName, String objectName, String versionId) throws ErrorResponseException, IllegalArgumentException, InsufficientDataException, InternalException, InvalidBucketNameException, InvalidKeyException, InvalidResponseException, IOException, NoSuchAlgorithmException, XmlParserException { Map<String, String> queryParamMap = new HashMap<>(); queryParamMap.put("legal-hold", ""); if (versionId != null && !versionId.isEmpty()) { queryParamMap.put("versionId", versionId); } try (Response response = executeGet(bucketName, objectName, null, queryParamMap)) { LegalHold result = Xml.unmarshal(LegalHold.class, response.body().charStream()); return result.status(); } catch (ErrorResponseException e) { if (e.errorResponse().errorCode() != ErrorCode.NO_SUCH_OBJECT_LOCK_CONFIGURATION) { throw e; } } return false; }
Source:
public void checkVisitedNode() { List<Node> nodes = lexer.parse(readFile("scanner/testFile.html")); HtmlSourceCode htmlSourceCode = createHtmlSourceCode("scanner/testFile.html"); htlScanner.scan(nodes, htmlSourceCode); assertEquals(3, counterVisitor.getExpressionCounter()); }

Target:
public void checkVisitedNode() { HtmlSourceCode htmlSourceCode = createHtmlSourceCode("scanner/testFile.html"); try (Reader reader = readFile("scanner/testFile.html")) { List<Node> nodes = lexer.parse(reader); htlScanner.scan(nodes, htmlSourceCode); } catch (IOException e) { throw Throwables.propagate(e); } assertEquals(1, counterVisitor.getCounter(CommentNode.class).intValue()); assertEquals(7, counterVisitor.getCounter(TagNode.class).intValue()); assertEquals(3, counterVisitor.getCounter(Expression.class).intValue()); }
Source:
public void run() { try { while (running.get()) { Reference<? extends ScopeCleanupMarker> ref = markerReferenceQueue.remove(1000); if (ref != null && ref instanceof ScopeCleanupAction) { Object markerKey = ((ScopeCleanupAction)ref).getId(); ScopeCleanupAction cleanupAction = scopedCleanupActions.remove(markerKey); if (cleanupAction != null) { cleanupAction.call(); } } } LOGGER.info("PreDestroyMonitor.ScopedCleanupWorker is exiting"); } catch (InterruptedException e) { LOGGER.info("PreDestroyMonitor.ScopedCleanupWorker is exiting due to thread interrupt"); } }

Target:
public void run() { try { while (running.get()) { Reference<? extends ScopeCleanupMarker> ref = markerReferenceQueue.remove(1000); if (ref != null && ref instanceof ScopeCleanupAction) { Object markerKey = ((ScopeCleanupAction) ref).getId(); ScopeCleanupAction cleanupAction = scopedCleanupActions.remove(markerKey); if (cleanupAction != null) { cleanupAction.call(); } } } LOGGER.info("PreDestroyMonitor.ScopedCleanupWorker is exiting"); } catch (InterruptedException e) { LOGGER.info("PreDestroyMonitor.ScopedCleanupWorker is exiting due to thread interrupt"); Thread.currentThread().interrupt(); } }
Source:
public String toString() { return "Suggestion{" + "primaryLine='" + primaryLine + '\'' + ", city='" + city + '\'' + ", state='" + state + '\'' + ", zipCode='" + zipCode + '\'' + '}'; }

Target:
public String toString() { return String.format( "Suggestion{primaryLine='%s', city='%s', state='%s', zipCode='%s'}", primaryLine, city, state, zipCode ); }
Source:
public void destroy() { DBUtils.cleanup(driverClass); dbManager.destroy(); }

Target:
public void destroy() { try { DBUtils.cleanup(driverClass); } finally { dbManager.destroy(); } }
Source:
public String toString() { String flattenValue = values.stream().filter(value -> !CoreUtils.isNullOrEmpty(value)) .map(this::escapeValue).collect(Collectors.joining(COMMA)); if (CoreUtils.isNullOrEmpty(flattenValue)) { throw logger.logExceptionAsError( new IllegalArgumentException("There must be at least one valid value for scoring parameter values.")); } return name + SEPARATOR + values.stream().filter(value -> !CoreUtils.isNullOrEmpty(value)) .map(this::escapeValue).collect(Collectors.joining(COMMA)); }

Target:
public String toString() { String flattenValue = values.stream().filter(value -> !CoreUtils.isNullOrEmpty(value)) .map(ScoringParameter::escapeValue).collect(Collectors.joining(COMMA)); if (CoreUtils.isNullOrEmpty(flattenValue)) { throw logger.logExceptionAsError( new IllegalArgumentException("There must be at least one valid value for scoring parameter values.")); } return name + DASH + flattenValue; }
Source:
MessageHandler createMethodInvokingHandler(Object targetObject, String targetMethodName) { MessageHandler directHandler = null; directHandler = createDirectHandlerIfPossible(targetObject, targetMethodName); if (directHandler != null) { return directHandler; } else { ServiceActivatingHandler handler = (StringUtils.hasText(targetMethodName)) ? new ServiceActivatingHandler(targetObject, targetMethodName) : new ServiceActivatingHandler(targetObject); return this.configureHandler(handler); } }

Target:
MessageHandler createMethodInvokingHandler(Object targetObject, String targetMethodName) { MessageHandler handler = null; handler = createDirectHandlerIfPossible(targetObject, targetMethodName); if (handler == null) { handler = configureHandler( StringUtils.hasText(targetMethodName) ? new ServiceActivatingHandler(targetObject, targetMethodName) : new ServiceActivatingHandler(targetObject)); } return handler; }
Source:
protected void createDefaultEditPolicies() { super.createDefaultEditPolicies(); installEditPolicy(EditPolicyRoles.CREATION_ROLE, new RTSideAffixedNodesCreationEditPolicy()); installEditPolicy(EditPolicyRoles.DRAG_DROP_ROLE, new RTCustomDiagramDragDropEditPolicy()); installEditPolicy("CanonicalPortDisplay", new CanonicalPortDisplayEditPolicy()); }

Target:
protected void createDefaultEditPolicies() { super.createDefaultEditPolicies(); installEditPolicy(EditPolicyRoles.CREATION_ROLE, new RTSideAffixedNodesCreationEditPolicy()); installEditPolicy(EditPolicyRoles.DRAG_DROP_ROLE, new RTCustomDiagramDragDropEditPolicy()); installEditPolicy(CanonicalPortDisplayEditPolicy.CANONICAL_PORT_DISPLAY_ROLE, new CanonicalPortDisplayEditPolicy()); }
Source:
public void endElement(final String uri, final String localName, final String qName) throws SAXException { processRoleStack.pop(); final DitaClass cls = classes.pop(); if ((cls == null || !cls.isValid()) && !ELEMENT_NAME_DITA.equals(localName)) { return; } getContentHandler().endElement(uri, localName, qName); }

Target:
public void endElement(final String uri, final String localName, final String qName) throws SAXException { processRoleStack.pop(); classes.pop(); getContentHandler().endElement(uri, localName, qName); }
Source:
private void handleAsrr(final Map<String, String> parameters, int code) { if (parameters.containsKey("asrr")) { String asrr = parameters.get("asrr"); if (!StringUtils.isEmpty(asrr)) { try { asrr = new String(Hex.decodeHex(asrr.toCharArray())); } catch (DecoderException e) { logger.error("asrr parameter cannot be decoded"); fail(code); } } final IvrEndpointResponse result = new IvrEndpointResponse(new CollectedResult(asrr, true, code == 101)); for (final ActorRef observer : observers) { observer.tell(result, self()); } } else { logger.error("asrr parameter is missing"); fail(code); } }

Target:
private void handleAsrr(final Map<String, String> parameters, int code) { if (parameters.containsKey("asrr")) { String asrr = parameters.get("asrr"); if (!StringUtils.isEmpty(asrr)) { try { asrr = new String(Hex.decodeHex(asrr.toCharArray())); } catch (DecoderException e) { logger.error("asrr parameter cannot be decoded.", e); fail(code); } } final IvrEndpointResponse result = new IvrEndpointResponse(new CollectedResult(asrr, true, code == 101)); for (final ActorRef observer : observers) { observer.tell(result, self()); } } else { logger.error("asrr parameter is missing"); fail(code); } }
Source:
public AssignmentServiceImpl() { this.strategy = registry.getStrategy(System.getProperty("org.jbpm.task.assignment.strategy", "PotentialOwnerBusyness")); }

Target:
public AssignmentServiceImpl() { this.strategy = registry.getStrategy(System.getProperty("org.jbpm.task.assignment.strategy", PotentialOwnerBusynessAssignmentStrategy.IDENTIFIER)); }
Source:
private DropdownListSearchPanel() { listsTableModel = new KeywordListsTableModel(); keywordsTableModel = new KeywordsTableModel(); initComponents(); customizeComponents(); dataSourceList.setModel(getDataSourceListModel()); dataSourceList.addListSelectionListener((ListSelectionEvent evt) -> { firePropertyChange(Bundle.DropdownSingleTermSearchPanel_selected(), null, null); }); dataSourceList.addMouseMotionListener(new MouseMotionListener() { @Override public void mouseDragged(MouseEvent evt) { } @Override public void mouseMoved(MouseEvent evt) { JList<String> DsList = (JList<String>) evt.getSource(); int index = DsList.locationToIndex(evt.getPoint()); if (index > -1) { DsList.setToolTipText(getDataSourceToolTipList().get(index)); } } }); }

Target:
private DropdownListSearchPanel() { listsTableModel = new KeywordListsTableModel(); keywordsTableModel = new KeywordsTableModel(); initComponents(); customizeComponents(); dataSourceList.setModel(getDataSourceListModel()); dataSourceList.addListSelectionListener((ListSelectionEvent evt) -> { firePropertyChange(Bundle.DropdownSingleTermSearchPanel_selected(), null, null); }); dataSourceList.addMouseMotionListener(new MouseMotionListener() { @Override public void mouseDragged(MouseEvent evt) { } @Override public void mouseMoved(MouseEvent evt) { JList<String> dsList = (JList<String>) evt.getSource(); int index = dsList.locationToIndex(evt.getPoint()); if (index > -1) { dsList.setToolTipText(getDataSourceToolTipList().get(index)); } } }); }
Source:
public R apply(ASTNode t) { try { Method visitorMethod = this.getClass().getDeclaredMethod("apply", t.getClass()); return (R) visitorMethod.invoke(this, t); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException e) { throw new VisitingException(makeErrorMessage(t), e); } catch (InvocationTargetException e) { if (e.getCause() instanceof InvocationTargetException) throw (VisitingException) e.getCause(); else if (e.getCause() instanceof RuntimeException) throw (RuntimeException) e.getCause(); else throw new VisitingException(makeErrorMessage(t), e); } }

Target:
public R apply(ASTNode t) { try { MethodHandles.Lookup lookup = MethodHandles.lookup(); Method visitMethod = this.getClass().getDeclaredMethod("apply", t.getClass()); MethodHandle visitMethodHandle = lookup.unreflect(visitMethod); return (R) visitMethodHandle.invoke(this, t); } catch (NoSuchMethodException e) { throw new VisitingException("Visitor " + this.getClass() + " is missing a definition for visit(" + t.getClass() + ")" + ". Encounteed when visiting " + makeErrorMessage(t), e); } catch (Throwable e) { throw new VisitingException(makeErrorMessage(t), e); } }