auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Response<T> parseResponse(com.squareup.okhttp.Response rawResponse) throws IOException { ResponseBody rawBody = rawResponse.body(); rawResponse = rawResponse.newBuilder() .body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength())) .build(); int code = rawResponse.code(); if (code < 200 || code >= 300) { try { ResponseBody bufferedBody = Utils.readBodyToBytesIfNecessary(rawBody); return Response.error(bufferedBody, rawResponse); } finally { closeQuietly(rawBody); } } if (code == 204 || code == 205) { return Response.success(null, rawResponse); } ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody); try { T body = responseConverter.convert(catchingBody); return Response.success(body, rawResponse); } catch (RuntimeException e) { catchingBody.throwIfCaught(); throw new RuntimeException("Problem has occurred during conversion of response for " + infoForException, e); } }

Target:
private Response<T> parseResponse(com.squareup.okhttp.Response rawResponse) throws IOException { ResponseBody rawBody = rawResponse.body(); rawResponse = rawResponse.newBuilder() .body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength())) .build(); int code = rawResponse.code(); if (code < 200 || code >= 300) { try { ResponseBody bufferedBody = Utils.readBodyToBytesIfNecessary(rawBody); return Response.error(bufferedBody, rawResponse); } finally { closeQuietly(rawBody); } } if (code == 204 || code == 205) { return Response.success(null, rawResponse); } ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody); try { T body = responseConverter.convert(catchingBody); return Response.success(body, rawResponse); } catch (RuntimeException e) { catchingBody.throwIfCaught(); throw new RuntimeException("Problem has occurred during conversion of response for " + toString(), e); } }
Source:
public void setScrollView(@Nullable ObservableWebView webView) { webview = webView; if (webview != null) { webview.addOnScrollChangeListener(this); webview.addOnDownMotionEventListener(this); webview.addOnUpOrCancelMotionEventListener(this); } }

Target:
public void setScrollView(@Nullable ObservableWebView webView) { this.webView = webView; if (this.webView != null) { this.webView.clearAllListeners(); this.webView.addOnScrollChangeListener(this); this.webView.addOnDownMotionEventListener(this); this.webView.addOnUpOrCancelMotionEventListener(this); } }
Source:
private static <T extends RpcScheduler> T createScheduler( Class<T> theClass, int priorityLevels, String ns, Configuration conf) { try { Constructor<T> ctor = theClass.getDeclaredConstructor(int.class, String.class, Configuration.class); return ctor.newInstance(priorityLevels, ns, conf); } catch (RuntimeException e) { throw e; } catch (Exception e) { } try { Constructor<T> ctor = theClass.getDeclaredConstructor(int.class); return ctor.newInstance(priorityLevels); } catch (RuntimeException e) { throw e; } catch (Exception e) { } try { Constructor<T> ctor = theClass.getDeclaredConstructor(); return ctor.newInstance(); } catch (RuntimeException e) { throw e; } catch (Exception e) { } throw new RuntimeException(theClass.getName() + " could not be constructed."); }

Target:
private static <T extends RpcScheduler> T createScheduler( Class<T> theClass, int priorityLevels, String ns, Configuration conf) { try { Constructor<T> ctor = theClass.getDeclaredConstructor(int.class, String.class, Configuration.class); return ctor.newInstance(priorityLevels, ns, conf); } catch (RuntimeException e) { throw e; } catch (InvocationTargetException e) { throw new RuntimeException(theClass.getName() + " could not be constructed.", e.getCause()); } catch (Exception e) { } try { Constructor<T> ctor = theClass.getDeclaredConstructor(int.class); return ctor.newInstance(priorityLevels); } catch (RuntimeException e) { throw e; } catch (InvocationTargetException e) { throw new RuntimeException(theClass.getName() + " could not be constructed.", e.getCause()); } catch (Exception e) { } try { Constructor<T> ctor = theClass.getDeclaredConstructor(); return ctor.newInstance(); } catch (RuntimeException e) { throw e; } catch (InvocationTargetException e) { throw new RuntimeException(theClass.getName() + " could not be constructed.", e.getCause()); } catch (Exception e) { } throw new RuntimeException(theClass.getName() + " could not be constructed."); }
Source:
public InputStream getMapContent() throws IOException { URL requestWorkspacesURL = new URL(getMapContextUrl()); HttpURLConnection connection = (HttpURLConnection) requestWorkspacesURL.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(cParams.getConnectionTimeOut()); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException(I18N.tr("HTTP Error {0} message : {1} while downloading from {2}",connection.getResponseCode(),connection.getResponseMessage(),getMapContextUrl())); } return connection.getInputStream(); }

Target:
public InputStream getMapContent() throws IOException { String url = RemoteCommons.getUrlContext(cParams, workspaceName, id); URL requestWorkspacesURL = new URL(url); HttpURLConnection connection = (HttpURLConnection) requestWorkspacesURL.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(cParams.getConnectionTimeOut()); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException(I18N.tr("HTTP Error {0} message : {1} while downloading from {2}", connection.getResponseCode(), connection.getResponseMessage(), url)); } return connection.getInputStream(); }
Source:
public TupleBatch[] partition(@Nonnull final TupleBatch tb) { BitSet[] partitions = new BitSet[numPartition()]; for (int i = 0; i < tb.numTuples(); i++) { partitions[tb.getInt(index, i) - 1].set(i); } TupleBatch[] tbs = new TupleBatch[numPartition()]; for (int i = 0; i < tbs.length; ++i) { tbs[i] = tb.filter(partitions[i]); } return tbs; }

Target:
public TupleBatch[] partition(@Nonnull final TupleBatch tb) { BitSet[] partitions = new BitSet[numPartitions()]; for (int i = 0; i < partitions.length; ++i) { partitions[i] = new BitSet(); } for (int i = 0; i < tb.numTuples(); i++) { partitions[tb.getInt(index, i) - 1].set(i); } TupleBatch[] tbs = new TupleBatch[numPartitions()]; for (int i = 0; i < tbs.length; ++i) { tbs[i] = tb.filter(partitions[i]); } return tbs; }
Source:
public void getResourcesFromADroolsPRJWithError() throws Exception { Path tmpRoot = Files.createTempDirectory("repo"); Path tmp = TestUtil.createAndCopyToDirectory(tmpRoot, "dummy", ResourcesConstants.KJAR_2_SINGLE_RESOURCES_WITH_ERROR); AFCompiler compiler = KieMavenCompilerFactory.getCompiler(KieDecorator.KIE_AFTER); WorkspaceCompilationInfo info = new WorkspaceCompilationInfo(Paths.get(tmp.toUri())); CompilationRequest req = new DefaultCompilationRequest(mavenRepo, info, new String[]{MavenCLIArgs.INSTALL}, Boolean.FALSE); KieCompilationResponse res = (KieCompilationResponse) compiler.compile(req); TestUtil.saveMavenLogIfCompilationResponseNotSuccessfull(tmp, res, this.getClass(), testName); if (!res.isSuccessful()) { List<String> msgs = res.getMavenOutput(); for (String msg : msgs) { logger.info(msg); } } assertThat(res.isSuccessful()).isTrue(); Optional<KieModuleMetaInfo> metaDataOptional = res.getKieModuleMetaInfo(); assertThat(metaDataOptional).isPresent(); KieModuleMetaInfo kieModuleMetaInfo = metaDataOptional.get(); assertThat(kieModuleMetaInfo).isNotNull(); Map<String, Set<String>> rulesBP = kieModuleMetaInfo.getRulesByPackage(); assertThat(rulesBP).hasSize(1); Optional<KieModule> kieModuleOptional = res.getKieModule(); assertThat(kieModuleOptional).isPresent(); List<String> classloaderOptional = CompilerClassloaderUtils.getStringFromTargets(tmpRoot); assertThat(classloaderOptional).hasSize(3); TestUtil.rm(tmpRoot.toFile()); }

Target:
public void getResourcesFromADroolsPRJWithError() throws Exception { Path tmpRoot = Files.createTempDirectory("repo"); Path tmp = TestUtil.createAndCopyToDirectory(tmpRoot, "dummy", ResourcesConstants.KJAR_2_SINGLE_RESOURCES_WITH_ERROR); AFCompiler compiler = KieMavenCompilerFactory.getCompiler(KieDecorator.KIE_AFTER); WorkspaceCompilationInfo info = new WorkspaceCompilationInfo(Paths.get(tmp.toUri())); CompilationRequest req = new DefaultCompilationRequest(mavenRepo, info, new String[]{MavenCLIArgs.INSTALL}, Boolean.FALSE); KieCompilationResponse res = (KieCompilationResponse) compiler.compile(req); TestUtil.saveMavenLogIfCompilationResponseNotSuccessfull(tmp, res, this.getClass(), testName); if (!res.isSuccessful()) { List<String> msgs = res.getMavenOutput(); for (String msg : msgs) { logger.info(msg); } } assertThat(res.isSuccessful()).isTrue(); Optional<KieModuleMetaInfo> metaDataOptional = res.getKieModuleMetaInfo(); assertThat(metaDataOptional).isPresent(); KieModuleMetaInfo kieModuleMetaInfo = metaDataOptional.get(); assertThat(kieModuleMetaInfo).isNotNull(); Map<String, Set<String>> rulesBP = kieModuleMetaInfo.getRulesByPackage(); assertThat(rulesBP).hasSize(1); Optional<KieModule> kieModuleOptional = res.getKieModule(); assertThat(kieModuleOptional).isPresent(); List<String> classloaderOptional = CompilerClassloaderUtils.getStringFromTargets(tmpRoot); assertThat(classloaderOptional).hasSize(3); }
Source:
public DecoratedCache(AdvancedCache<K, V> delegate, Flag... flags) { super(delegate); if (flags == null) throw new IllegalArgumentException("There is no point in using a DecoratedCache if neither a ClassLoader nor any Flags are set."); if (flags == null || flags.length == 0) this.flags = EnumUtil.EMPTY_BIT_SET; else { this.flags = EnumUtil.bitSetOf(flags); } cacheImplementation = (CacheImpl<K, V>) delegate; }

Target:
public DecoratedCache(AdvancedCache<K, V> delegate, Flag... flags) { super(delegate); if (flags == null) throw new IllegalArgumentException("There is no point in using a DecoratedCache if Flags are set."); if (flags.length == 0) this.flags = EnumUtil.EMPTY_BIT_SET; else { this.flags = EnumUtil.bitSetOf(flags); } cacheImplementation = (CacheImpl<K, V>) delegate; }
Source:
protected void installFromArchive() throws Exception { InstallLibertyTask installTask = (InstallLibertyTask) ant.createTask("antlib:net/wasdev/wlp/ant:install-liberty"); if (installTask == null) { throw new IllegalStateException("install-liberty task not found"); } installTask.setBaseDir(assemblyInstallDirectory.getAbsolutePath()); installTask.setLicenseCode(install.getLicenseCode()); installTask.setVersion(install.getVersion()); installTask.setRuntimeUrl(install.getRuntimeUrl()); installTask.setVerbose(install.isVerbose()); installTask.setMaxDownloadTime(install.getMaxDownloadTime()); installTask.setType(install.getType()); installTask.setOffline(settings.isOffline()); String cacheDir = install.getCacheDirectory(); if (cacheDir == null) { File dir = new File(artifactRepository.getBasedir(), "wlp-cache"); installTask.setCacheDir(dir.getAbsolutePath()); } else { installTask.setCacheDir(cacheDir); } String serverId = install.getServerId(); if (serverId != null) { Server server = settings.getServer(serverId); if (server == null) { throw new MojoExecutionException("Server id not found: " + serverId); } installTask.setUsername(server.getUsername()); installTask.setPassword(server.getPassword()); } else { installTask.setUsername(install.getUsername()); installTask.setPassword(install.getPassword()); } installTask.execute(); }

Target:
protected void installFromArchive() throws Exception { InstallLibertyTask installTask = (InstallLibertyTask) ant.createTask("antlib:net/wasdev/wlp/ant:install-liberty"); if (installTask == null) { throw new IllegalStateException(MessageFormat.format(messages.getString("error.dependencies.not.found"), "install-liberty")); } installTask.setBaseDir(assemblyInstallDirectory.getAbsolutePath()); installTask.setLicenseCode(install.getLicenseCode()); installTask.setVersion(install.getVersion()); installTask.setRuntimeUrl(install.getRuntimeUrl()); installTask.setVerbose(install.isVerbose()); installTask.setMaxDownloadTime(install.getMaxDownloadTime()); installTask.setType(install.getType()); installTask.setOffline(settings.isOffline()); String cacheDir = install.getCacheDirectory(); if (cacheDir == null) { File dir = new File(artifactRepository.getBasedir(), "wlp-cache"); installTask.setCacheDir(dir.getAbsolutePath()); } else { installTask.setCacheDir(cacheDir); } String serverId = install.getServerId(); if (serverId != null) { Server server = settings.getServer(serverId); if (server == null) { throw new MojoExecutionException("Server id not found: " + serverId); } installTask.setUsername(server.getUsername()); installTask.setPassword(server.getPassword()); } else { installTask.setUsername(install.getUsername()); installTask.setPassword(install.getPassword()); } installTask.execute(); }
Source:
protected void bindComment(final int row, final int col, final PatchLineComment line, final boolean isLast, boolean expandComment) { if (line.getStatus() == PatchLineComment.Status.DRAFT) { final CommentEditorPanel plc = new CommentEditorPanel(line); plc.addFocusHandler(this); plc.addBlurHandler(this); table.setWidget(row, col, plc); styleLastCommentCell(row, col, false); } else { final AccountInfo author = accountCache.get(line.getAuthor()); final PublishedCommentPanel panel = new PublishedCommentPanel(author, line); panel.setOpen(expandComment); panel.addFocusHandler(this); panel.addBlurHandler(this); table.setWidget(row, col, panel); styleLastCommentCell(row, col, line.getLine() == 0 ? true : false); CommentList l = (CommentList) getRowItem(row); if (l == null) { l = new CommentList(); setRowItem(row, l); } l.comments.add(line); l.panels.add(panel); } styleCommentRow(row); }

Target:
protected void bindComment(final int row, final int col, final PatchLineComment line, final boolean isLast, boolean expandComment) { if (line.getStatus() == PatchLineComment.Status.DRAFT) { final CommentEditorPanel plc = new CommentEditorPanel(line); plc.addFocusHandler(this); plc.addBlurHandler(this); table.setWidget(row, col, plc); styleLastCommentCell(row, col, line.getLine() == FILE_COMMENT_ROW); } else { final AccountInfo author = accountCache.get(line.getAuthor()); final PublishedCommentPanel panel = new PublishedCommentPanel(author, line); panel.setOpen(expandComment); panel.addFocusHandler(this); panel.addBlurHandler(this); table.setWidget(row, col, panel); styleLastCommentCell(row, col, line.getLine() == FILE_COMMENT_ROW); CommentList l = (CommentList) getRowItem(row); if (l == null) { l = new CommentList(); setRowItem(row, l); } l.comments.add(line); l.panels.add(panel); } styleCommentRow(row); }
Source:
private File copyEngineToTarget(File cachedEngineDir) throws MojoExecutionException { File targetEngine = getEngineDir(project); try { getLog().info("Parameter <testEngineLocation> is set to " + testEngineLocation + ", copying engine from: " + cachedEngineDir + " to " + targetEngine); FileUtils.copyDirectory(cachedEngineDir, targetEngine); return targetEngine; } catch (IOException ex) { getLog().warn("Could not copy engine from: " + cachedEngineDir + " to " + targetEngine); } return cachedEngineDir; }

Target:
private File copyEngineToTarget(File cachedEngineDir) throws MojoExecutionException { File targetEngine = getEngineDir(project); try { getLog().info("Parameter <testEngineLocation> is set to " + testEngineLocation + ", copying engine from: " + cachedEngineDir + " to " + targetEngine); FileUtils.copyDirectory(cachedEngineDir, targetEngine); return targetEngine; } catch (IOException ex) { getLog().warn("Could not copy engine from: " + cachedEngineDir + " to " + targetEngine, ex); } return cachedEngineDir; }
Source:
public void close() throws ResourceException { try { super.close(); } catch (Exception e) { e.printStackTrace(); } LogManager.logDetail(LogConstants.CTX_CONNECTOR, CassandraManagedConnectionFactory.UTIL.getString("shutting_down")); }

Target:
public void close() { super.close(); LogManager.logDetail(LogConstants.CTX_CONNECTOR, CassandraManagedConnectionFactory.UTIL.getString("shutting_down")); }
Source:
public void test_enqueuing_exceptional_yields2() { setUp(); BytecodeCFGBuilder.BytecodeCFG cfg = BytecodeCFGBuilder.buildCFG(TRY_WRONG_CATCH_SIGNATURE, squidClassLoader); BytecodeCFGBuilder.Block b2 = cfg.blocks().get(2); walker.programState = ProgramState.EMPTY_STATE.stackValue(new SymbolicValue()).stackValue(new SymbolicValue()); walker.programPosition = new ProgramPoint(b2).next().next(); walker.executeInstruction(b2.elements().get(3)); assertThat(walker.workList).hasSize(2); assertThat(walker.workList.pop().programState.exitValue()).isNotNull().isInstanceOf(SymbolicValue.ExceptionalSymbolicValue.class); assertThat(walker.workList.pop().programState.exitValue()).isNull(); }

Target:
public void test_enqueuing_exceptional_yields2() { initializeWalker(); BytecodeCFGBuilder.BytecodeCFG cfg = BytecodeCFGBuilder.buildCFG(TRY_WRONG_CATCH_SIGNATURE, squidClassLoader); BytecodeCFGBuilder.Block b2 = cfg.blocks().get(2); walker.programState = ProgramState.EMPTY_STATE.stackValue(new SymbolicValue()).stackValue(new SymbolicValue()); walker.programPosition = new ProgramPoint(b2).next().next(); walker.executeInstruction(b2.elements().get(3)); assertThat(walker.workList).hasSize(2); assertThat(walker.workList.pop().programState.exitValue()).isNotNull() .isInstanceOf(SymbolicValue.ExceptionalSymbolicValue.class) .extracting(sv -> ((SymbolicValue.ExceptionalSymbolicValue) sv).exceptionType().fullyQualifiedName()).containsExactly("java.lang.IllegalStateException"); assertThat(walker.workList.pop().programState.exitValue()).isNull(); }
Source:
private static List<String> generateColors() { List<String> colors = new ArrayList<>(); final BigDecimal brightnessSteps = new BigDecimal(2); final BigDecimal saturationSteps = new BigDecimal(2); final BigDecimal hueSteps = new BigDecimal(15); final BigDecimal brightnessStep = new BigDecimal("0.5").divide(brightnessSteps, 2, RoundingMode.HALF_UP); final BigDecimal saturationStep = new BigDecimal("0.6").divide(saturationSteps, 2, RoundingMode.HALF_UP); final BigDecimal hueStep = ONE.divide(hueSteps, 8, RoundingMode.HALF_UP); for (BigDecimal brightness = ONE; brightness.compareTo(new BigDecimal("0.5")) == 1; ) { for (BigDecimal saturation = ONE; saturation.compareTo(new BigDecimal("0.4")) >= 0; ) { for (BigDecimal hue = ZERO; hue.compareTo(ONE) < 1; ) { Color hsbColor = Color.getHSBColor(hue.floatValue(), saturation.floatValue(), brightness.floatValue()); colors.add(getHexCodeOfColor(hsbColor)); hue = hue.add(hueStep); } saturation = saturation.subtract(saturationStep); } brightness = brightness.subtract(brightnessStep); } return colors; }

Target:
private static List<String> generateColors() { List<String> colors = new ArrayList<>(); final BigDecimal brightnessSteps = new BigDecimal(2); final BigDecimal saturationSteps = new BigDecimal(1); final BigDecimal hueSteps = new BigDecimal(15); final BigDecimal brightnessStep = new BigDecimal("0.5").divide(brightnessSteps, 2, RoundingMode.HALF_UP); final BigDecimal saturationStep = new BigDecimal("0.6").divide(saturationSteps, 2, RoundingMode.HALF_UP); final BigDecimal hueStep = ONE.divide(hueSteps, 8, RoundingMode.HALF_UP); final BigDecimal brightnessLimit = new BigDecimal("0.5"); final BigDecimal saturationLimit = new BigDecimal("0.4"); for (BigDecimal brightness = ONE; brightness.compareTo(brightnessLimit) == 1; ) { for (BigDecimal saturation = ONE; saturation.compareTo(saturationLimit) >= 0; ) { for (BigDecimal hue = ZERO; hue.compareTo(ONE) < 1; ) { Color hsbColor = Color.getHSBColor(hue.floatValue(), saturation.floatValue(), brightness.floatValue()); colors.add(getHexCodeOfColor(hsbColor)); hue = hue.add(hueStep); } saturation = saturation.subtract(saturationStep); } brightness = brightness.subtract(brightnessStep); } return shuffle(colors); }
Source:
public String getUserName() { final UserCause userCause = getCause(UserCause.class); final String nameFromUserCause = userCause != null ? userCause.getUserName() : null; if (nameFromUserCause != null) { return nameFromUserCause; } final UserIdCause userIdCause = getCause(UserIdCause.class); final String nameFromUserIdCause = userIdCause != null ? userIdCause.getUserName() : null; if (nameFromUserIdCause != null) { return nameFromUserIdCause; } for (PromotionBadge badget : getStatus().getBadges()) { if (badget instanceof ManualCondition.Badge) { final String nameFromBadge = ((ManualCondition.Badge) badget).getUserName(); if (nameFromBadge != null) { return nameFromBadge; } } } return "anonymous"; }

Target:
public String getUserName() { final UserCause userCause = getCause(UserCause.class); final String nameFromUserCause = userCause != null ? userCause.getUserName() : null; if (nameFromUserCause != null) { return nameFromUserCause; } final UserIdCause userIdCause = getCause(UserIdCause.class); final String nameFromUserIdCause = userIdCause != null ? userIdCause.getUserName() : null; if (nameFromUserIdCause != null) { return nameFromUserIdCause; } for (PromotionBadge badget : getStatus().getBadges()) { if (badget instanceof ManualCondition.Badge) { final String nameFromBadge = ((ManualCondition.Badge) badget).getUserName(); if (nameFromBadge != null) { return nameFromBadge; } } } return Jenkins.ANONYMOUS.getName(); }
Source:
public Map<String, Map<String, Object>> extractBrokerConfigurations(Dictionary<String, ?> properties) { Map<String, Map<String, Object>> configPerBroker = new TreeMap<String, Map<String, Object>>(); Enumeration<String> keys = properties.keys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); String value = (String) properties.get(key); if (key.equals("service.pid")) { continue; } String[] subkeys = key.split("\\."); if (subkeys.length != 2 || StringUtils.isBlank(value)) { logger.debug("MQTT Broker property '{}={}' should have the format 'broker.propertykey=value'", key, value); continue; } String brokername = subkeys[0].toLowerCase(); Map<String, Object> brokerConfig = configPerBroker.get(brokername); if (brokerConfig == null) { brokerConfig = new TreeMap<>(); configPerBroker.put(brokername, brokerConfig); brokerConfig.put("name", brokername); } brokerConfig.put(subkeys[1], value); } return configPerBroker; }

Target:
public Map<String, Map<String, String>> extractBrokerConfigurations(Dictionary<String, ?> properties) { Map<String, Map<String, String>> configPerBroker = new HashMap<String, Map<String, String>>(); Enumeration<String> keys = properties.keys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); String value = (String) properties.get(key); if (key.equals("service.pid")) { continue; } String[] subkeys = key.split("\\."); if (subkeys.length != 2 || StringUtils.isBlank(value)) { logger.debug("MQTT Broker property '{}={}' should have the format 'broker.propertykey=value'", key, value); continue; } String brokername = subkeys[0].toLowerCase(); Map<String, String> brokerConfig = configPerBroker.get(brokername); if (brokerConfig == null) { brokerConfig = new HashMap<>(); configPerBroker.put(brokername, brokerConfig); brokerConfig.put(NAME_PROPERTY, brokername); } brokerConfig.put(subkeys[1], value); } return configPerBroker; }
Source:
public V get(final K key) throws CacheLoaderException { getObserver.begin(); statusTransitioner.checkAvailable(); checkNonNull(key); final Function<K, V> mappingFunction = memoize( new Function<K, V>() { @Override public V apply(final K k) { V loaded = null; try { if (cacheLoader != null) { cacheLoaderObserver.begin(); loaded = cacheLoader.load(k); cacheLoaderObserver.end(CacheLoaderOutcome.SUCCESS); getObserver.end(loaded != null ? GetOutcome.HIT_WITH_LOADER : GetOutcome.MISS_WITH_LOADER); } } catch (Exception e) { cacheLoaderObserver.end(CacheLoaderOutcome.FAILURE); throw newCacheLoaderException(e); } return loaded; } }); try { final Store.ValueHolder<V> valueHolder = store.computeIfAbsent(key, mappingFunction); if (valueHolder == null) { if (cacheLoader == null) { getObserver.end(GetOutcome.MISS_NO_LOADER); } return null; } else { if (cacheLoader == null) { getObserver.end(GetOutcome.HIT_NO_LOADER); } return valueHolder.value(); } } catch (CacheAccessException e) { try { if (cacheLoader == null) { return resilienceStrategy.getFailure(key, e); } else { return resilienceStrategy.getFailure(key, mappingFunction.apply(key), e); } } finally { getObserver.end(GetOutcome.FAILURE); } } }

Target:
public V get(final K key) throws CacheLoaderException { getObserver.begin(); statusTransitioner.checkAvailable(); checkNonNull(key); final Function<K, V> mappingFunction = memoize( new Function<K, V>() { @Override public V apply(final K k) { V loaded = null; try { if (cacheLoader != null) { cacheLoaderObserver.begin(); loaded = cacheLoader.load(k); cacheLoaderObserver.end(CacheLoaderOutcome.SUCCESS); getObserver.end(loaded != null ? GetOutcome.HIT_WITH_LOADER : GetOutcome.MISS_WITH_LOADER); } } catch (Exception e) { cacheLoaderObserver.end(CacheLoaderOutcome.FAILURE); throw newCacheLoaderException(e); } return loaded; } }); try { final Store.ValueHolder<V> valueHolder = store.computeIfAbsent(key, mappingFunction); if (valueHolder == null) { if (cacheLoader == null) { getObserver.end(GetOutcome.MISS_NO_LOADER); } return null; } else { if (cacheLoader == null) { getObserver.end(GetOutcome.HIT_NO_LOADER); } return valueHolder.value(); } } catch (CacheAccessException e) { try { if (cacheLoader == null) { return resilienceStrategy.getFailure(key, e); } else { V fromLoader; try { fromLoader = mappingFunction.apply(key); } catch (CacheLoaderException f) { return resilienceStrategy.getFailure(key, e, f); } return resilienceStrategy.getFailure(key, fromLoader, e); } } finally { getObserver.end(GetOutcome.FAILURE); } } }
Source:
private static UpdaterConfiguration makeAmazonUnboxConfiguration() { ImmutableSet<Publisher> targetSources = ImmutableSet.of(AMAZON_UNBOX, PA); return UpdaterConfiguration.builder() .withSource(AMAZON_UNBOX) .withItemEquivalenceUpdater( VOD_ITEM, targetSources ) .withTopLevelContainerEquivalenceUpdater( VOD_CONTAINER, targetSources ) .withNonTopLevelContainerEquivalenceUpdater( STANDARD_SERIES, targetSources ) .build(); }

Target:
private static UpdaterConfiguration makeAmazonUnboxConfiguration() { ImmutableSet<Publisher> targetSources = ImmutableSet.of(AMAZON_UNBOX, PA, RADIO_TIMES_UPCOMING); return UpdaterConfiguration.builder() .withSource(AMAZON_UNBOX) .withItemEquivalenceUpdater( VOD_ITEM, targetSources ) .withTopLevelContainerEquivalenceUpdater( VOD_CONTAINER, targetSources ) .withNonTopLevelContainerEquivalenceUpdater( STANDARD_SERIES, targetSources ) .build(); }
Source:
public boolean equals(Object o) { PageTitle other = (PageTitle)o; return other.getPrefixedText().equals(getPrefixedText()) && other.getSite().equals(getSite()); }

Target:
public boolean equals(Object o) { if (!(o instanceof PageTitle)) { return false; } PageTitle other = (PageTitle)o; return other.getPrefixedText().equals(getPrefixedText()) && other.getSite().equals(getSite()); }
Source:
public void testSetWifi() { ImsCall mTestImsCall = new ImsCall(mContext, mTestCallProfile); assertFalse(mTestImsCall.isWifiCall()); assertFalse(mTestImsCall.getRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE); mBundle.putString(ImsCallProfile.EXTRA_CALL_RAT_TYPE, ServiceState.RIL_RADIO_TECHNOLOGY_IWLAN + ""); assertTrue(mTestImsCall.isWifiCall()); assertFalse(mTestImsCall.getRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE); }

Target:
public void testSetWifi() { ImsCall mTestImsCall = new ImsCall(mContext, mTestCallProfile); assertFalse(mTestImsCall.isWifiCall()); assertNotEquals(mTestImsCall.getRadioTechnology(), ServiceState.RIL_RADIO_TECHNOLOGY_LTE); mBundle.putString(ImsCallProfile.EXTRA_CALL_RAT_TYPE, ServiceState.RIL_RADIO_TECHNOLOGY_IWLAN + ""); assertTrue(mTestImsCall.isWifiCall()); assertNotEquals(mTestImsCall.getRadioTechnology(), ServiceState.RIL_RADIO_TECHNOLOGY_LTE); }
Source:
private void validateSubscriptionResetCursors(final Subscription subscription, final List<NakadiCursor> cursors) throws ServiceUnavailableException, NoSuchSubscriptionException, UnableProcessException { validateCursorsBelongToSubscription(subscription, cursors); final Map<TopicRepository, List<NakadiCursor>> cursorsByRepo = cursors.stream() .collect(Collectors.groupingBy(c -> timelineService.getTopicRepository(c.getTimeline()))); for (final Map.Entry<TopicRepository, List<NakadiCursor>> repoEntry : cursorsByRepo.entrySet()) { final TopicRepository topicRepository = repoEntry.getKey(); final List<NakadiCursor> cursorsForRepo = repoEntry.getValue(); try { topicRepository.validateReadCursors(cursorsForRepo); } catch (final InvalidCursorException e) { throw new UnableProcessException(e.getMessage(), e); } } }

Target:
private void validateSubscriptionResetCursors(final Subscription subscription, final List<NakadiCursor> cursors) throws ServiceUnavailableException, CursorUnavailableException { validateCursorsBelongToSubscription(subscription, cursors); final Map<TopicRepository, List<NakadiCursor>> cursorsByRepo = cursors.stream() .collect(Collectors.groupingBy(c -> timelineService.getTopicRepository(c.getTimeline()))); for (final Map.Entry<TopicRepository, List<NakadiCursor>> repoEntry : cursorsByRepo.entrySet()) { final TopicRepository topicRepository = repoEntry.getKey(); final List<NakadiCursor> cursorsForRepo = repoEntry.getValue(); try { topicRepository.validateReadCursors(cursorsForRepo); } catch (final InvalidCursorException e) { throw new CursorUnavailableException(e.getMessage(), e); } } }
Source:
public void delete(long deletableTxnId) { try { CountDownLatch latch = new CountDownLatch(1); final ProcedureCallback cb = new ProcedureCallback() { @Override public void clientCallback(ClientResponse resp) throws Exception { if (resp.getStatus() != ClientResponse.SUCCESS) { logger.warn(String.format("Fail to execute migrating delete on table: %s,status: %s", m_tableName, resp.getStatusString())); } latch.countDown(); } }; ExportManager.instance().invokeMigrateRowsDelete(m_partitionId, m_tableName, m_batchSize, deletableTxnId, cb); try { latch.await(1, TimeUnit.MINUTES); } catch (InterruptedException e) { logger.warn("Migrating delete was interrupted" + e.getMessage()); } } catch (Exception e) { logger.error("Error deleting migrated rows", e); } catch (Error e) { VoltDB.crashLocalVoltDB("Error deleting migrated rows", true, e); } }

Target:
public void delete(long deletableTxnId) { try { CountDownLatch latch = new CountDownLatch(1); final ProcedureCallback cb = new ProcedureCallback() { @Override public void clientCallback(ClientResponse resp) throws Exception { if (resp.getStatus() != ClientResponse.SUCCESS) { logger.warn(String.format("Fail to execute migrating delete on table: %s,status: %s", m_tableName, resp.getStatusString())); } latch.countDown(); } }; ExportManager.instance().invokeMigrateRowsDelete(m_partitionId, m_tableName, m_batchSize, deletableTxnId, cb); try { latch.await(TTLManager.NT_PROC_TIMEOUT, TimeUnit.SECONDS); } catch (InterruptedException e) { logger.warn("Migrating delete was interrupted" + e.getMessage()); } } catch (Exception e) { logger.error("Error deleting migrated rows", e); } catch (Error e) { VoltDB.crashLocalVoltDB("Error deleting migrated rows", true, e); } }
Source:
protected Function<Feature, Optional<Feature>> getTransformingFunction( final SimpleFeatureType featureType) { Function<Feature, Optional<Feature>> function = (feature) -> { SimpleFeatureBuilder builder = new SimpleFeatureBuilder(featureType); for (Property property : feature.getProperties()) { if (property instanceof GeometryAttribute) { builder.set(featureType.getGeometryDescriptor().getName(), property.getValue()); } else { builder.set(property.getName().getLocalPart(), property.getValue()); } } Map<Object, Object> userData = feature.getUserData(); for (Entry<Object, Object> entry : userData.entrySet()) { builder.featureUserData(entry.getKey(), entry.getValue()); } long fidValue = nextId.incrementAndGet(); builder.featureUserData(Hints.PROVIDED_FID, Long.valueOf(fidValue)); fidMappings.put(Long.toString(fidValue), feature.getIdentifier().getID()); Feature modifiedFeature = builder.buildFeature(Long.toString(fidValue)); return Optional.fromNullable(modifiedFeature); }; return function; }

Target:
protected Function<Feature, Optional<Feature>> getTransformingFunction( final SimpleFeatureType featureType) { Function<Feature, Optional<Feature>> function = (feature) -> { SimpleFeatureBuilder builder = new SimpleFeatureBuilder(featureType); builder.init((SimpleFeature) feature); long fidValue = nextId.incrementAndGet(); builder.featureUserData(Hints.PROVIDED_FID, Long.valueOf(fidValue)); fidMappings.put(Long.toString(fidValue), feature.getIdentifier().getID()); Feature modifiedFeature = builder.buildFeature(Long.toString(fidValue)); return Optional.fromNullable(modifiedFeature); }; return function; }
Source:
public IPaperWallet generateWallet(String cryptoCurrency, String oneTimePassword, String userLanguage) { final KeyPairService keyPairService = new KeyPairServiceFactory().getService(); MnemonicKeyPair master = null; BaseKeyPair credentials = null; try { master = keyPairService.generateMasterMnemonicKeyPair(oneTimePassword); credentials = EncodingUtils.createBaseKeyPair( keyPairService.generateDerivedKey(master, true).toRawKeyPair()); } catch (AException e) { e.printStackTrace(); } String privateKey = credentials.getPrivateKey(); String address = credentials.getPublicKey(); byte[] content = ctx.createPaperWallet7ZIP(privateKey, address, oneTimePassword, cryptoCurrency); String messageText = "New wallet " + address + " use your onetime password to open the attachment."; String messageTextLang = readTemplate("/batm/config/template_wallet_" + userLanguage + ".txt"); if (messageTextLang != null) { messageText = messageTextLang; }else{ String messageTextEN = readTemplate("/batm/config/template_wallet_en.txt"); if (messageTextEN != null) { messageText = messageTextEN; } } return new AeternityPaperWallet(cryptoCurrency, content, address, privateKey, messageText,"application/zip", "zip"); }

Target:
public IPaperWallet generateWallet(String cryptoCurrency, String oneTimePassword, String userLanguage) { final KeyPairService keyPairService = new KeyPairServiceFactory().getService(); String mnemonicPassword = PasswordGenerator.generateRandomPassword(12); BaseKeyPair keyPair = null; MnemonicKeyPair master = null; try { master = keyPairService.generateMasterMnemonicKeyPair(mnemonicPassword); keyPair = EncodingUtils.createBaseKeyPair( keyPairService.generateDerivedKey(master, true).toRawKeyPair()); } catch (AException e) { e.printStackTrace(); } String privateKey = keyPair.getPrivateKey(); String address = keyPair.getPublicKey(); byte[] content = ctx.createPaperWallet7ZIP(privateKey, address, oneTimePassword, cryptoCurrency); String messageText = "New wallet " + address + " use your onetime password to open the attachment."; String messageTextLang = readTemplate("/batm/config/template_wallet_" + userLanguage + ".txt"); if (messageTextLang != null) { messageText = messageTextLang; }else{ String messageTextEN = readTemplate("/batm/config/template_wallet_en.txt"); if (messageTextEN != null) { messageText = messageTextEN; } } return new AeternityPaperWallet(cryptoCurrency, content, address, privateKey, messageText,"application/zip", "zip"); }
Source:
protected void connectServiceUp() { addEnricher(SensorTransformingEnricher.newInstanceTransforming(this, MANAGEMENT_URL_UP, Functions.<Boolean>identity(), SERVICE_UP)); }

Target:
protected void connectServiceUp() { serviceUpEnricher = SensorTransformingEnricher.newInstanceTransforming(this, MANAGEMENT_URL_UP, Functions.<Boolean>identity(), SERVICE_UP); addEnricher(serviceUpEnricher); }
Source:
private void handleInstallMessage(@NonNull Object arg) { lock.lock(); try { if (installed.get()) { warn("Received duplicate setup message with arg: " + arg); return; } if (arg instanceof List) { @SuppressWarnings("unchecked") List<Object> values = (List<Object>)arg; if (values.size() > 0 && values.get(0) instanceof Configuration) { Configuration config = (Configuration)values.get(0); ByteBuffer anrBuffer = null; if (values.size() > 1 && values.get(1) instanceof ByteBuffer) { anrBuffer = (ByteBuffer)values.get(1); } String reportPath = reportDirectory + UUID.randomUUID().toString() + ".crash"; install(reportPath, config.getDetectNdkCrashes(), Build.VERSION.SDK_INT, is32bit(), anrBuffer); installed.set(true); } } else { warn("Received install message with incorrect arg: " + arg); } } finally { lock.unlock(); } }

Target:
private void handleInstallMessage(@NonNull Object arg) { lock.lock(); try { if (installed.get()) { warn("Received duplicate setup message with arg: " + arg); } else if (arg instanceof List) { @SuppressWarnings("unchecked") List<Object> values = (List<Object>)arg; if (values.size() > 0 && values.get(0) instanceof Configuration) { Configuration config = (Configuration)values.get(0); ByteBuffer anrBuffer = null; if (values.size() > 1 && values.get(1) instanceof ByteBuffer) { anrBuffer = (ByteBuffer)values.get(1); } String reportPath = reportDirectory + UUID.randomUUID().toString() + ".crash"; install(reportPath, config.getDetectNdkCrashes(), Build.VERSION.SDK_INT, is32bit(), anrBuffer); installed.set(true); } } else { warn("Received install message with incorrect arg: " + arg); } } finally { lock.unlock(); } }
Source:
public RepositorySelectionPage(final boolean sourceSelection, final List<RemoteConfig> configuredRemotes, String presetUri) { super(RepositorySelectionPage.class.getName()); this.uri = new URIish(); this.sourceSelection = sourceSelection; String preset = presetUri; if (presetUri == null) { Clipboard clipboard = new Clipboard(Display.getCurrent()); String text = stripGitCloneCommand( (String) clipboard.getContents(TextTransfer.getInstance())); try { if (text != null) { text = text.trim(); int index = text.indexOf(' '); if (index > 0) text = text.substring(0, index); URIish u = new URIish(text); if (canHandleProtocol(u)) if (Protocol.GIT.handles(u) || Protocol.SSH.handles(u) || Protocol.HTTP.handles(u) || Protocol.HTTPS.handles(u) || text.endsWith(Constants.DOT_GIT_EXT)) preset = text; } } catch (URISyntaxException e) { } clipboard.dispose(); } this.presetUri = preset; this.configuredRemotes = getUsableConfigs(configuredRemotes); selection = RepositorySelection.INVALID_SELECTION; if (sourceSelection) { setTitle(UIText.RepositorySelectionPage_sourceSelectionTitle); setDescription(UIText.RepositorySelectionPage_sourceSelectionDescription); } else { setTitle(UIText.RepositorySelectionPage_destinationSelectionTitle); setDescription(UIText.RepositorySelectionPage_destinationSelectionDescription); } storeInSecureStore = getPreferenceStore().getBoolean( UIPreferences.CLONE_WIZARD_STORE_SECURESTORE); }

Target:
public RepositorySelectionPage(final boolean sourceSelection, final List<RemoteConfig> configuredRemotes, String presetUri) { super(RepositorySelectionPage.class.getName()); this.uri = new URIish(); this.sourceSelection = sourceSelection; String preset = presetUri; if (presetUri == null) { Clipboard clipboard = new Clipboard(Display.getCurrent()); String text = (String) clipboard .getContents(TextTransfer.getInstance()); try { if (text != null) { text = stripGitCloneCommand(text); int index = text.indexOf(' '); if (index > 0) text = text.substring(0, index); URIish u = new URIish(text); if (canHandleProtocol(u)) if (Protocol.GIT.handles(u) || Protocol.SSH.handles(u) || Protocol.HTTP.handles(u) || Protocol.HTTPS.handles(u) || text.endsWith(Constants.DOT_GIT_EXT)) preset = text; } } catch (URISyntaxException e) { } clipboard.dispose(); } this.presetUri = preset; this.configuredRemotes = getUsableConfigs(configuredRemotes); selection = RepositorySelection.INVALID_SELECTION; if (sourceSelection) { setTitle(UIText.RepositorySelectionPage_sourceSelectionTitle); setDescription(UIText.RepositorySelectionPage_sourceSelectionDescription); } else { setTitle(UIText.RepositorySelectionPage_destinationSelectionTitle); setDescription(UIText.RepositorySelectionPage_destinationSelectionDescription); } storeInSecureStore = getPreferenceStore().getBoolean( UIPreferences.CLONE_WIZARD_STORE_SECURESTORE); }
Source:
public boolean hasVariable(final String identifier) { if (identifier == null || identifier.isEmpty()) return false; return getVariable(identifier) != null; }

Target:
public boolean hasVariable(final String identifier) { return getVariable(identifier) != null; }
Source:
public void insertHeaderWithTimeValue() throws ParseException { final Map<String, Object> props = new HashMap<>(); props.put("header", "AAA"); props.put("literal.value", "14\\:34\\:54.346Z"); xform.configure(props); final SourceRecord record = new SourceRecord(null, null, "test", 0, null, null, null, null, null, null); final SourceRecord transformedRecord = xform.apply(record); SchemaAndValue schemaAndValue = new SchemaAndValue(Time.SCHEMA, new SimpleDateFormat("HH:mm:ss.SSS'Z'").parse("14:34:54.346Z")); Headers expected = new ConnectHeaders().add("AAA", schemaAndValue); assertEquals(1, transformedRecord.headers().size()); assertEquals(expected, transformedRecord.headers()); }

Target:
public void insertHeaderWithTimeValue() throws ParseException { final Map<String, Object> props = new HashMap<>(); props.put("header", "AAA"); props.put("literal.value", "14:34:54.346Z"); xform.configure(props); final SourceRecord record = new SourceRecord(null, null, "test", 0, null, null, null, null, null, null); final SourceRecord transformedRecord = xform.apply(record); SchemaAndValue schemaAndValue = new SchemaAndValue(Time.SCHEMA, new SimpleDateFormat("HH:mm:ss.SSS'Z'").parse("14:34:54.346Z")); Headers expected = new ConnectHeaders().add("AAA", schemaAndValue); assertEquals(1, transformedRecord.headers().size()); assertEquals(expected, transformedRecord.headers()); }
Source:
public List<String> getRecipients() { List<String> recipients = Lists.newArrayList(); Boolean consentNotificationEmailVerified = getStudy().isConsentNotificationEmailVerified(); if (consentNotificationEmailVerified == null || consentNotificationEmailVerified) { Set<String> studyRecipients = BridgeUtils.commaListToOrderedSet(getStudy().getConsentNotificationEmail()); recipients.addAll( studyRecipients ); } if (userEmail != null) { recipients.add(userEmail); } return recipients; }

Target:
public List<String> getRecipients() { return recipients; }
Source:
public Set<SessionEntity> getSessions(Collection<String> sessionIds) { List<SessionDataDto> sessionDataDtoList = databaseService.getSessionInfoService().getBySessionIds(0, sessionIds.size(), new HashSet<String>(sessionIds)); if (sessionDataDtoList.isEmpty()) { return Collections.emptySet(); } Set<SessionEntity> entities = new TreeSet<>(new SessionEntity.IdComparator()); for (SessionDataDto sessionDataDto : sessionDataDtoList) { SessionEntity sessionEntity = new SessionEntity(); sessionEntity.setId(sessionDataDto.getSessionId()); sessionEntity.setStartDate(sessionDataDto.getStartDate()); sessionEntity.setEndDate(sessionDataDto.getEndDate()); sessionEntity.setKernels(sessionDataDto.getActiveKernelsCount()); sessionEntity.setComment(sessionDataDto.getComment()); System.out.println(sessionEntity); entities.add(sessionEntity); } return entities; }

Target:
public Set<SessionEntity> getSessions(Collection<String> sessionIds) { List<SessionDataDto> sessionDataDtoList = databaseService.getSessionInfoService().getBySessionIds(0, sessionIds.size(), new HashSet<String>(sessionIds)); if (sessionDataDtoList.isEmpty()) { return Collections.emptySet(); } Set<SessionEntity> entities = new TreeSet<>(new SessionEntity.IdComparator()); for (SessionDataDto sessionDataDto : sessionDataDtoList) { SessionEntity sessionEntity = new SessionEntity(); sessionEntity.setId(sessionDataDto.getSessionId()); sessionEntity.setStartDate(sessionDataDto.getStartDate()); sessionEntity.setEndDate(sessionDataDto.getEndDate()); sessionEntity.setKernels(sessionDataDto.getActiveKernelsCount()); sessionEntity.setComment(sessionDataDto.getComment()); entities.add(sessionEntity); } return entities; }
Source:
public void testGetCellWhenEnumPresent() throws Exception { final String factType = "org.kiegroup.Car"; final String factField = "color"; final String dataType = DataType.DataTypes.NUMERIC.name(); doReturn(true).when(oracle).hasEnums(factType, factField); doReturn(factType).when(column).getFactType(); doReturn(factField).when(column).getFactField(); doReturn(dataType).when(column).getDataType(); testedFactory.getCell(column); verify(testedFactory).makeSingleSelectionEnumCell(factType, factField, dataType); }

Target:
public void testGetCellWhenEnumPresent() throws Exception { final String factType = "org.kiegroup.Car"; final String factField = "color"; final String dataType = DataType.DataTypes.STRING.name(); doReturn(true).when(oracle).hasEnums(factType, factField); doReturn(factType).when(column).getFactType(); doReturn(factField).when(column).getFactField(); doReturn(dataType).when(column).getDataType(); testedFactory.getCell(column); verify(testedFactory).makeSingleSelectionEnumCell(factType, factField, dataType); }
Source:
public PerspectiveDefinition buildPerspective() { PerspectiveDefinition perspective = new PerspectiveDefinitionImpl(StaticWorkbenchPanelPresenter.class.getName()); final PlaceRequest place = new DefaultPlaceRequest(DashboardsListScreen.ID); PartDefinitionImpl dashboardScreen = new PartDefinitionImpl(place); perspective.getRoot().addPart(dashboardScreen); perspective.setName("List Dashboards"); return perspective; }

Target:
public PerspectiveDefinition buildPerspective() { PerspectiveDefinition perspective = new PerspectiveDefinitionImpl(StaticWorkbenchPanelPresenter.class.getName()); final PlaceRequest place = new DefaultPlaceRequest(DashboardsListScreen.ID); PartDefinitionImpl dashboardScreen = new PartDefinitionImpl(place); perspective.getRoot().addPart(dashboardScreen); perspective.setName(i18n.listDashboardsScreenTitle()); return perspective; }
Source:
private boolean evaluateVelocityTemplate(DocumentReference userReference, String templateContent) { try { if (StringUtils.isBlank(templateContent)) { return true; } Template customTemplate = new StringTemplate( templateContent, Syntax.XWIKI_2_1, Syntax.PLAIN_1_0, userReference); StringWriter writer = new StringWriter(); templateManager.render(customTemplate, writer); return writer.toString().trim().contains("true"); } catch (Exception e) { return false; } }

Target:
private boolean evaluateVelocityTemplate(DocumentReference userReference, String templateContent) { try { if (StringUtils.isBlank(templateContent)) { return true; } Template customTemplate = new StringTemplate( templateContent, Syntax.XWIKI_2_1, Syntax.PLAIN_1_0, userReference); XDOM templateXDOM = templateManager.execute(customTemplate); WikiPrinter printer = new DefaultWikiPrinter(); BlockRenderer renderer = this.componentManagerProvider.get().getInstance(BlockRenderer.class, "plain"); renderer.render(templateXDOM, printer); return printer.toString().trim().equals("true"); } catch (Exception e) { logger.warn(String.format( "Unable to render a notification validation template. Error : %s\nStack trace : %s", e.getMessage(), e.getStackTrace())); return false; } }
Source:
private static List<Integer> trimTrailing(List<Integer> codePoints, int codePointToTrim) { List<Integer> trimmed = new ArrayList<>(codePoints); while (!trimmed.isEmpty() && trimmed.get(trimmed.size() - 1) == codePointToTrim) { trimmed.remove(trimmed.size() - 1); } return trimmed; }

Target:
private static List<Integer> trimTrailing(List<Integer> codePoints, int codePointToTrim) { int endIndex = codePoints.size(); while (endIndex > 0 && codePoints.get(endIndex - 1) == codePointToTrim) { endIndex--; } return ImmutableList.copyOf(codePoints.subList(0, endIndex)); }
Source:
private static boolean validParameters(String methodAnnotation,Class[] parameterTypes) { boolean flag = true; methodAnnotation = methodAnnotation.replace("@",""); List<Class> localMapping = mapping.get(methodAnnotation); if (localMapping == null) { return false; } for (Class parameterType : parameterTypes) { if (! localMapping.contains(parameterType)) { flag = false; break; } } return flag; }

Target:
private static boolean validParameters(String methodAnnotation, Class[] parameterTypes) { methodAnnotation = methodAnnotation.replace("@", ""); List<Class<?>> localMapping = mapping.get(methodAnnotation); if (localMapping == null) { return false; } for (Class<?> parameterType : parameterTypes) { if (!localMapping.contains(parameterType)) { return false; } } return true; }