auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void newVm() { if (getWindow() != null) { return; } UnitVmModel model = new UnitVmModel(new NewVmModelBehavior()); model.setTitle(ConstantsManager.getInstance() .getMessages() .newVmTitle(ConstantsManager.getInstance().getConstants().vm())); model.setHashName("new_vm"); model.setIsNew(true); model.getVmType().setSelectedItem(VmType.Server); model.setCustomPropertiesKeysList(getCustomPropertiesKeysList()); setWindow(model); model.initialize(getSystemTreeSelectedItem()); VmBasedWidgetSwitchModeCommand switchModeCommand = new VmBasedWidgetSwitchModeCommand(); switchModeCommand.init(model); model.getCommands().add(switchModeCommand); model.getProvisioning().setEntity(true); UICommand tempVar = new UICommand("OnSave", this); tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok()); tempVar.setIsDefault(true); model.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", this); tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); }

Target:
private void newVm() { if (getWindow() != null) { return; } UnitVmModel model = new UnitVmModel(new NewVmModelBehavior()); model.setTitle(ConstantsManager.getInstance().getConstants().newVmTitle()); model.setHashName("new_vm"); model.setIsNew(true); model.getVmType().setSelectedItem(VmType.Server); model.setCustomPropertiesKeysList(getCustomPropertiesKeysList()); setWindow(model); model.initialize(getSystemTreeSelectedItem()); VmBasedWidgetSwitchModeCommand switchModeCommand = new VmBasedWidgetSwitchModeCommand(); switchModeCommand.init(model); model.getCommands().add(switchModeCommand); model.getProvisioning().setEntity(true); UICommand tempVar = new UICommand("OnSave", this); tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok()); tempVar.setIsDefault(true); model.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", this); tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); }
Source:
public Optional<RestRouterConfiguration> build() { if (this.enabled) { try { validate(); } catch (Exception e) { throw logger.configurationValidationError(e); } return Optional.of(new RestRouterConfiguration(ip, port)); } return Optional.empty(); }

Target:
public RestRouterConfiguration build() { if (this.enabled) { try { validate(); } catch (Exception e) { throw logger.configurationValidationError(e); } return new RestRouterConfiguration(ip, port); } return null; }
Source:
private String makeStringFromSentences(List<String> sentences, int numSentences) { StringBuilder outStr = new StringBuilder(); for (int i = 0; i < Math.min(numSentences, sentences.size()); i++) { outStr.append(sentences.get(i)); outStr.append(' '); } return outStr.toString(); }

Target:
private String makeStringFromSentences(List<String> sentences, int numSentences) { return TextUtils.join(" ", sentences.subList(0, Math.min(numSentences, sentences.size()))); }
Source:
public void afterAnalysis( CommandEnvironment env, BuildRequest request, BuildOptions buildOptions, AnalysisResult analysisResult) { if (remoteOutputsMode != null && remoteOutputsMode.downloadToplevelOutputsOnly()) { Preconditions.checkState(actionContextProvider != null, "actionContextProvider was null"); boolean isTestCommand = env.getCommandName().equals("test"); TopLevelArtifactContext artifactContext = request.getTopLevelArtifactContext(); ImmutableSet.Builder<ActionInput> filesToDownload = ImmutableSet.builder(); for (ConfiguredTarget configuredTarget : analysisResult.getTargetsToBuild()) { if (isTestCommand && isTestRule(configuredTarget)) { filesToDownload.addAll(getTestOutputs(configuredTarget)); } else { filesToDownload.addAll(getArtifactsToBuild(configuredTarget, artifactContext).toList()); filesToDownload.addAll(getRunfiles(configuredTarget)); } } for (ActionInput actionInput : filesToDownload.build()) { if (!(actionInput instanceof Artifact)) { continue; } ActionExecutionMetadata action = (ActionExecutionMetadata) analysisResult.getActionGraph().getGeneratingAction((Artifact) actionInput); if (action.mayInsensitivelyPropagateInputs()) { filesToDownload.addAll(action.getInputs().toList()); } } actionContextProvider.setFilesToDownload(filesToDownload.build()); } }

Target:
public void afterAnalysis( CommandEnvironment env, BuildRequest request, BuildOptions buildOptions, AnalysisResult analysisResult) { if (remoteOutputsMode != null && remoteOutputsMode.downloadToplevelOutputsOnly() && actionContextProvider != null) { boolean isTestCommand = env.getCommandName().equals("test"); TopLevelArtifactContext artifactContext = request.getTopLevelArtifactContext(); Set<ActionInput> filesToDownload = new HashSet<>(); for (ConfiguredTarget configuredTarget : analysisResult.getTargetsToBuild()) { if (isTestCommand && isTestRule(configuredTarget)) { filesToDownload.addAll(getTestOutputs(configuredTarget)); } else { fetchSymlinkDependenciesRecursively( analysisResult.getActionGraph(), filesToDownload, getArtifactsToBuild(configuredTarget, artifactContext).toList()); fetchSymlinkDependenciesRecursively( analysisResult.getActionGraph(), filesToDownload, getRunfiles(configuredTarget)); } } actionContextProvider.setFilesToDownload(ImmutableSet.copyOf(filesToDownload)); } }
Source:
public SGLRParseResult actuallyParse(String text, @Nullable String filename, @Nullable JSGLRParserConfiguration parserConfig) throws SGLRException, InterruptedException { if(!parserConfig.implode || config.getImploderSetting() == ImploderImplementation.stratego) { parser.setTreeBuilder(new Asfix2TreeBuilder(termFactory)); } parser.setUseStructureRecovery(parserConfig.recovery); if(parserConfig.cursorPosition == Integer.MAX_VALUE) { parser.setCompletionParse(false, Integer.MAX_VALUE); } else { parser.setCompletionParse(parserConfig.completion, parserConfig.cursorPosition); } parser.setTimeout(parserConfig.timeout); final Disambiguator disambiguator = parser.getDisambiguator(); if(dialect != null) { disambiguator.setHeuristicFilters(true); } else { disambiguator.setHeuristicFilters(false); } String startSymbol = getOrDefaultStartSymbol(parserConfig); SGLRParseResult parseResult; ret: try { parseResult = parser.parse(text, filename, startSymbol); break ret; } catch(FilterException e) { if((e.getCause() == null || e.getCause() instanceof UnsupportedOperationException) && disambiguator.getFilterPriorities()) { disambiguator.setFilterPriorities(false); disambiguator.setFilterAssociativity(false); try { parseResult = parser.parse(text, filename, startSymbol); break ret; } finally { disambiguator.setFilterPriorities(true); } } throw e; } catch(StartSymbolException e) { if(dialect != null) { parseResult = parser.parse(text, filename, null); break ret; } else { throw e; } } if(config.getImploderSetting() == ImploderImplementation.stratego) { final implode_asfix_0_0 imploder = implode_asfix_0_0.instance; final Context strategoContext = new Context(this.termFactory); final IStrategoTerm syntaxTree = (IStrategoTerm) parseResult.output; return new SGLRParseResult(imploder.invoke(strategoContext, syntaxTree)); } else { return parseResult; } }

Target:
public SGLRParseResult actuallyParse(String text, @Nullable String filename, @Nullable JSGLRParserConfiguration parserConfig) throws SGLRException, InterruptedException { if(!parserConfig.implode || config.getImploderSetting() == ImploderImplementation.stratego) { parser.setTreeBuilder(new Asfix2TreeBuilder(termFactory)); } parser.setUseStructureRecovery(parserConfig.recovery); if(parserConfig.cursorPosition == Integer.MAX_VALUE) { parser.setCompletionParse(false, Integer.MAX_VALUE); } else { parser.setCompletionParse(parserConfig.completion, parserConfig.cursorPosition); } parser.setTimeout(parserConfig.timeout); final Disambiguator disambiguator = parser.getDisambiguator(); if(dialect != null) { disambiguator.setHeuristicFilters(true); } else { disambiguator.setHeuristicFilters(false); } SGLRParseResult parseResult = parseAndRecover(text, filename, disambiguator, getOrDefaultStartSymbol(parserConfig)); if(config.getImploderSetting() == ImploderImplementation.stratego) { final implode_asfix_0_0 imploder = implode_asfix_0_0.instance; final Context strategoContext = new Context(this.termFactory); final IStrategoTerm syntaxTree = (IStrategoTerm) parseResult.output; return new SGLRParseResult(imploder.invoke(strategoContext, syntaxTree)); } else { return parseResult; } }
Source:
public void initialize() { super.initialize(); if (fftType == null) { fftType = (C) new ComplexFloatType(); } padOp = (BinaryFunctionOp) Functions.binary(ops(), PadInputFFTMethods.class, RandomAccessibleInterval.class, RandomAccessibleInterval.class, Dimensions.class, fast); createOp = (UnaryFunctionOp) Functions.unary(ops(), CreateOutputFFTMethods.class, RandomAccessibleInterval.class, Dimensions.class, fftType, fast); fftMethodsOp = (UnaryComputerOp) Computers.nullary(ops(), FFTMethodsOpC.class, RandomAccessibleInterval.class, RandomAccessibleInterval.class); }

Target:
public void initialize() { super.initialize(); if (fftType == null) { fftType = (C)ops().create().nativeType(ComplexFloatType.class); } padOp = (BinaryFunctionOp) Functions.binary(ops(), PadInputFFTMethods.class, RandomAccessibleInterval.class, RandomAccessibleInterval.class, Dimensions.class, fast); createOp = (UnaryFunctionOp) Functions.unary(ops(), CreateOutputFFTMethods.class, RandomAccessibleInterval.class, Dimensions.class, fftType, fast); fftMethodsOp = (UnaryComputerOp) Computers.nullary(ops(), FFTMethodsOpC.class, RandomAccessibleInterval.class, RandomAccessibleInterval.class); }
Source:
public void not_equal() throws Exception { execute("a != null"); assertSingleValueInStack(EqualitySymbolicValue.class); RelationalSymbolicValue sv = (RelationalSymbolicValue) stack.peek(); assertThat(sv.leftOperand()).isEqualTo(simple1); assertThat(sv.rightOperand()).isEqualTo(SpecialSymbolicValue.NULL); assertSingleValueInStackWithConstraint(Constraint.BOOLEAN); }

Target:
public void not_equal() throws Exception { execute("a != null"); assertSingleValueInStack(RelationalSymbolicValue.create(Kind.NOT_EQUAL_TO, simple1, SpecialSymbolicValue.NULL)); }
Source:
public void compileQuery(List<String> statements) { try { LOG.info("Compiling query statements {}", statements); StreamlineSql stormSql = StreamlineSql.construct(); stormSql.execute(statements, channelHandler); channelContext = RulesDataSourcesProvider.getDataSource().getChannelContext(); LOG.info("Query statements successfully compiled, channelContext set to {}", channelContext); } catch (Exception e) { throw new RuntimeException(String.format("Error compiling query. Statements [%s]", statements), e); } }

Target:
public void compileQuery(List<String> statements) { try { LOG.info("Compiling query statements {}", statements); StreamlineSql streamlineSql = StreamlineSql.construct(); streamlineSql.execute(statements, channelHandler); channelContext = RulesDataSourcesProvider.getDataSource().getChannelContext(); LOG.info("Query statements successfully compiled, channelContext set to {}", channelContext); } catch (Exception e) { throw new RuntimeException(String.format("Error compiling query. Statements [%s]", statements), e); } }
Source:
public ModelInfo load() { switch (version) { case "4.1.2": return JAXB.unmarshal(QdmModelInfoProvider.class.getResourceAsStream("/gov/healthit/qdm/qdm-modelinfo.xml"), ModelInfo.class); case "4.2": return JAXB.unmarshal(QuickModelInfoProvider.class.getResourceAsStream("/gov/healthit/qdm/qdm-modelinfo-4.2.xml"), ModelInfo.class); case "5.0": default: return JAXB.unmarshal(QuickModelInfoProvider.class.getResourceAsStream("/gov/healthit/qdm/qdm-modelinfo-5.0.xml"), ModelInfo.class); } }

Target:
public ModelInfo load() { String localVersion = version == null ? "" : version; switch (localVersion) { case "4.1.2": return JAXB.unmarshal(QdmModelInfoProvider.class.getResourceAsStream("/gov/healthit/qdm/qdm-modelinfo.xml"), ModelInfo.class); case "4.2": return JAXB.unmarshal(QuickModelInfoProvider.class.getResourceAsStream("/gov/healthit/qdm/qdm-modelinfo-4.2.xml"), ModelInfo.class); case "5.0": case "": return JAXB.unmarshal(QuickModelInfoProvider.class.getResourceAsStream("/gov/healthit/qdm/qdm-modelinfo-5.0.xml"), ModelInfo.class); default: throw new IllegalArgumentException(String.format("Unknown version %s of the QDM model.", localVersion)); } }
Source:
public DataContainer toContainer() { DataContainer dataContainer = super.toContainer(); if (this.primaryEffect != null) { dataContainer = dataContainer.set(Keys.BEACON_PRIMARY_EFFECT.getQuery(), this.primaryEffect); } if (this.secondaryEffect != null) { dataContainer = dataContainer.set(Keys.BEACON_SECONDARY_EFFECT.getQuery(), this.secondaryEffect); } return dataContainer; }

Target:
public DataContainer toContainer() { DataContainer dataContainer = super.toContainer(); if (this.primaryEffect != null) { dataContainer = dataContainer.set(Keys.BEACON_PRIMARY_EFFECT.getQuery(), this.primaryEffect.getId()); } if (this.secondaryEffect != null) { dataContainer = dataContainer.set(Keys.BEACON_SECONDARY_EFFECT.getQuery(), this.secondaryEffect.getId()); } return dataContainer; }
Source:
public final synchronized void shutdown() throws InterruptedException { try { poolState = POOL_SHUTDOWN; LOGGER.info("{} - is closing down.", poolName); logPoolState("Before closing "); addConnectionExecutor.shutdown(); addConnectionExecutor.awaitTermination(5L, TimeUnit.SECONDS); if (config.getScheduledExecutorService() == null) { houseKeepingExecutorService.shutdown(); houseKeepingExecutorService.awaitTermination(5L, TimeUnit.SECONDS); } final ExecutorService assassinExecutor = createThreadPoolExecutor(config.getMaximumPoolSize(), "Hikari connection assassin", config.getThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy()); connectionBag.close(); try { final long start = clockSource.currentTime(); do { softEvictConnections(); abortActiveConnections(assassinExecutor); } while (getTotalConnections() > 0 && clockSource.elapsedMillis(start) < TimeUnit.SECONDS.toMillis(5)); } finally { assassinExecutor.shutdown(); assassinExecutor.awaitTermination(5L, TimeUnit.SECONDS); } poolElf.shutdownTimeoutExecutor(); closeConnectionExecutor.shutdown(); closeConnectionExecutor.awaitTermination(5L, TimeUnit.SECONDS); } finally { logPoolState("After closing "); poolElf.unregisterMBeans(); metricsTracker.close(); } }

Target:
public final synchronized void shutdown() throws InterruptedException { try { poolState = POOL_SHUTDOWN; LOGGER.info("{} - is closing down.", poolName); logPoolState("Before closing "); connectionBag.close(); softEvictConnections(); addConnectionExecutor.shutdown(); addConnectionExecutor.awaitTermination(5L, TimeUnit.SECONDS); if (config.getScheduledExecutorService() == null) { houseKeepingExecutorService.shutdown(); houseKeepingExecutorService.awaitTermination(5L, TimeUnit.SECONDS); } final ExecutorService assassinExecutor = createThreadPoolExecutor(config.getMaximumPoolSize(), "Hikari connection assassin", config.getThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy()); try { final long start = clockSource.currentTime(); do { softEvictConnections(); abortActiveConnections(assassinExecutor); } while (getTotalConnections() > 0 && clockSource.elapsedMillis(start) < TimeUnit.SECONDS.toMillis(5)); } finally { assassinExecutor.shutdown(); assassinExecutor.awaitTermination(5L, TimeUnit.SECONDS); } poolElf.shutdownTimeoutExecutor(); closeConnectionExecutor.shutdown(); closeConnectionExecutor.awaitTermination(5L, TimeUnit.SECONDS); } finally { logPoolState("After closing "); poolElf.unregisterMBeans(); metricsTracker.close(); } }
Source:
public void pack(String storageId, String repositoryId) throws IOException { String contextId = storageId + ":" + repositoryId + ":" + IndexTypeEnum.LOCAL.getType(); logger.info("Packing index for " + contextId + " ..."); final RepositoryIndexer indexer = repositoryIndexManager.getRepositoryIndexer(contextId); if (indexer == null) { throw new NullPointerException("Unable to find RepositoryIndexer by key " + contextId + ". \nAvailable keys are " + repositoryIndexManager.getIndexes().keySet()); } IndexingContext context = indexer.getIndexingContext(); final IndexSearcher indexSearcher = context.acquireIndexSearcher(); try { IndexPackingRequest request = new IndexPackingRequest(context, indexSearcher.getIndexReader(), new File(indexer.getRepositoryBasedir() + "/.index/local")); request.setUseTargetProperties(true); indexPacker.packIndex(request); logger.info("Index for " + storageId + ":" + repositoryId + ":" + IndexTypeEnum.LOCAL.getType() + " was packed successfully."); } finally { context.releaseIndexSearcher(indexSearcher); } }

Target:
public void pack(String storageId, String repositoryId) throws IOException { String contextId = getContextId(storageId, repositoryId, IndexTypeEnum.LOCAL.getType()); logger.info("Packing index for " + contextId + " ..."); final RepositoryIndexer indexer = repositoryIndexManager.getRepositoryIndexer(contextId); if (indexer == null) { throw new NullPointerException("Unable to find RepositoryIndexer by key " + contextId + ". \nAvailable keys are " + repositoryIndexManager.getIndexes().keySet()); } IndexingContext context = indexer.getIndexingContext(); final IndexSearcher indexSearcher = context.acquireIndexSearcher(); try { IndexPackingRequest request = new IndexPackingRequest(context, indexSearcher.getIndexReader(), new File(indexer.getRepositoryBasedir() + "/.index/local")); request.setUseTargetProperties(true); indexPacker.packIndex(request); logger.info("Index for " + storageId + ":" + repositoryId + ":" + IndexTypeEnum.LOCAL.getType() + " was packed successfully."); } finally { context.releaseIndexSearcher(indexSearcher); } }
Source:
public Statistics<?> build() { FloatStatistics stats = (FloatStatistics) super.build(); if (stats.hasNonNullValue()) { Float min = stats.genericGetMin(); Float max = stats.genericGetMax(); if (min.isNaN() || max.isNaN()) { stats.setMinMax(0.0f, 0.0f); ((Statistics<?>) stats).hasNonNullValue = false; } else { if (min == 0.0f) { stats.setMinMax(-0.0f, max); min = -0.0f; } if (max == -0.0f) { stats.setMinMax(min, 0.0f); } } } return stats; }

Target:
public Statistics<?> build() { FloatStatistics stats = (FloatStatistics) super.build(); if (stats.hasNonNullValue()) { Float min = stats.genericGetMin(); Float max = stats.genericGetMax(); if (min.isNaN() || max.isNaN()) { stats.setMinMax(0.0f, 0.0f); ((Statistics<?>) stats).hasNonNullValue = false; } else { if (Float.compare(min, 0.0f) == 0) { min = -0.0f; stats.setMinMax(min, max); } if (Float.compare(max, -0.0f) == 0) { max = 0.0f; stats.setMinMax(min, max); } } } return stats; }
Source:
public void testTimeOut(String timeout, int size, int lineNumber) throws IOException { XmlSuite suite = new XmlSuite(); suite.setTimeOut(timeout); StringReader stringReader = new StringReader(suite.toXml()); List<String> resultLines = Lists.newArrayList(); List<Integer> lineNumbers = grep(stringReader, "time-out=\"1000\"", resultLines); assertThat(lineNumbers.size()).isEqualTo(size); assertThat(resultLines.size()).isEqualTo(size); if (size > 0) { assertThat(lineNumbers.get(size-1)).isEqualTo(lineNumber); } }

Target:
public void testTimeOut(String timeout, int size, int lineNumber) throws IOException { XmlSuite suite = new XmlSuite(); suite.setTimeOut(timeout); StringReader stringReader = new StringReader(suite.toXml()); List<String> resultLines = Lists.newArrayList(); List<Integer> lineNumbers = grep(stringReader, "time-out=\"1000\"", resultLines); assertThat(lineNumbers).size().isEqualTo(size); assertThat(resultLines).size().isEqualTo(size); if (size > 0) { assertThat(lineNumbers.get(size-1)).isEqualTo(lineNumber); } }
Source:
protected boolean canDoAction() { parameter = getParameters(); if (!super.canDoAction()) { return false; } masterVolume = getGlusterVolume(); if (!masterVolume.isOnline()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_IS_DOWN); addCanDoActionMessageVariable("volumeName", masterVolume.getName()); return false; } List<GlusterGeoRepSession> sessions = getGlusterGeoRepDao().getGeoRepSessions(parameter.getVolumeId()); if (sessions != null) { for (GlusterGeoRepSession session : sessions) { if (session.getMasterVolumeId() == parameter.getVolumeId() && session.getSlaveHostName() == parameter.getSlaveHost() && session.getSlaveVolumeName() == parameter.getSlaveVolumeName()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GEOREP_SESSION_CREATED); return false; } } } if(parameter.getSlaveHost() == null || parameter.getSlaveVolumeName() == null || parameter.getUserName() == null || parameter.getSlavePassword() == null) { return false; } return true; }

Target:
protected boolean canDoAction() { parameter = getParameters(); if(parameter == null || parameter.getSlaveHost() == null || parameter.getSlaveVolumeName() == null || parameter.getUserName() == null || parameter.getSlaveUserPassword() == null) { return false; } masterVolume = getGlusterVolume(); if (!masterVolume.isOnline()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_IS_DOWN); addCanDoActionMessageVariable("volumeName", masterVolume.getName()); return false; } List<GlusterGeoRepSession> sessions = getGlusterGeoRepDao().getGeoRepSessions(parameter.getVolumeId()); if (sessions != null) { for (GlusterGeoRepSession session : sessions) { if (session.getMasterVolumeId() == parameter.getVolumeId() && session.getSlaveHostName() == parameter.getSlaveHost() && session.getSlaveVolumeName() == parameter.getSlaveVolumeName()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GEOREP_SESSION_CREATED); return false; } } } return true; }
Source:
private static @Nullable Long nullableNumberToLong(@Nullable Number number) { return number == null ? null : Long.valueOf(number.longValue()); }

Target:
private static @Nullable Long nullableNumberToLong(@Nullable Number number) { return (number == null ? null : Long.valueOf(number.longValue())); }
Source:
public void onDropItemRequest(DropItemRequest event, EntityRef character) { if (!event.getItem().exists() || !networkSystem.getOwnerEntity(event.getItem()).equals(networkSystem.getOwnerEntity(character))) { return; } EntityRef pickupItem = event.getItem(); EntityRef owner = pickupItem.getOwner(); if (owner.hasComponent(InventoryComponent.class)) { final EntityRef removedItem = inventoryManager.removeItem(owner, EntityRef.NULL, pickupItem, false, 1); if (removedItem != null) { pickupItem = removedItem; } } pickupItem.send(new DropItemEvent(event.getNewPosition())); if (pickupItem.hasComponent(PickupComponent.class)) { PickupComponent pickupComponent = pickupItem.getComponent(PickupComponent.class); pickupComponent.timeToPickUp = 2000; pickupComponent.timeDropped = time.getGameTimeInMs(); pickupItem.saveComponent(pickupComponent); } pickupItem.send(new ImpulseEvent(event.getImpulse())); }

Target:
public void onDropItemRequest(DropItemRequest event, EntityRef character) { if (!event.getItem().exists() || !networkSystem.getOwnerEntity(event.getItem()).equals(networkSystem.getOwnerEntity(character))) { return; } EntityRef pickupItem = event.getItem(); EntityRef owner = pickupItem.getOwner(); if (owner.hasComponent(InventoryComponent.class)) { final EntityRef removedItem = inventoryManager.removeItem(owner, EntityRef.NULL, pickupItem, false, 1); if (removedItem != null) { pickupItem = removedItem; } } pickupItem.send(new DropItemEvent(event.getNewPosition())); if (pickupItem.hasComponent(PickupComponent.class)) { PickupComponent pickupComponent = pickupItem.getComponent(PickupComponent.class); pickupComponent.timeDropped = time.getGameTimeInMs(); pickupItem.saveComponent(pickupComponent); } pickupItem.send(new ImpulseEvent(event.getImpulse())); }
Source:
public void verifyDeleteViaGlobalNotifications() { addVideoViaAjax(); deleteVideo(); Assertion.assertEquals("\"File:" + VideoContent.youtubeVideoURL2name + "\" has been deleted. (undelete)", getFlashMessageText()); PageObjectLogging.log("verifyDeleteVideoGlobalNotifications", "verify that video with following title was deleted: " + VideoContent.youtubeVideoURL2name, true); }

Target:
public void verifyDeleteViaGlobalNotifications() { addVideoViaAjax(VideoContent.youtubeVideoURL2); refreshPage(); deleteVideo(); String deletedVideo = "\"File:" + VideoContent.youtubeVideoURL2name + "\" has been deleted. (undelete)"; Assertion.assertEquals(deletedVideo, getFlashMessageText()); PageObjectLogging.log("verifyDeleteVideoGlobalNotifications", "verify video " + deletedVideo + " was deleted", true); }
Source:
public void downloadLatestSiteStats(final View view) { final Handler handler = new SiteDownloadHandler(view, numberFormat, getActivity().getPackageName(), getResources()); final ApiDownloader task = new ApiDownloader(getActivity(), ListFragment.lameStatic.dbHelper, "site-stats-cache.json", MainActivity.SITE_STATS_URL, false, false, false, ApiDownloader.REQUEST_GET, new ApiListener() { @Override public void requestComplete(final JSONObject json, final boolean isCache) { handleSiteStats(json, handler); } }); try { task.startDownload(this); } catch (WiGLEAuthException waex) }

Target:
public void downloadLatestSiteStats(final View view) { final Handler handler = new SiteDownloadHandler(view, numberFormat, getActivity().getPackageName(), getResources()); final ApiDownloader task = new ApiDownloader(getActivity(), ListFragment.lameStatic.dbHelper, "site-stats-cache.json", MainActivity.SITE_STATS_URL, false, false, false, ApiDownloader.REQUEST_GET, new ApiListener() { @Override public void requestComplete(final JSONObject json, final boolean isCache) { handleSiteStats(json, handler); } }); try { task.startDownload(this); } catch (WiGLEAuthException waex) { MainActivity.warn("Authentication error on site stats load (should not happen)", waex); } }
Source:
public void clearReceive() { if (networkReceive != null) { ReferenceCountUtil.release(networkReceive.getReceivedBytes().getAndRelease()); } networkReceive = null; }

Target:
public void clearReceive() { networkReceive = null; }
Source:
public void fullTextShouldWorkWithBindVar() throws Exception { Node n1 = session.getRootNode().addNode("n1"); n1.setProperty("n1-prop-1", "wow"); n1.setProperty("n1-prop-2", "any"); Node n2 = session.getRootNode().addNode("n2"); n2.setProperty("n2-prop-1", "test"); session.save(); String queryString = "select * from [nt:unstructured] as a where contains(a.*, 'wow')"; assertNodesAreFound(queryString, Query.JCR_SQL2, "/n1"); String queryStringWithBind = "select * from [nt:unstructured] as a where contains(a.*, $text)"; QueryManager queryManager = session.getWorkspace().getQueryManager(); Query query = queryManager.createQuery(queryStringWithBind, Query.JCR_SQL2); query.bindValue("text", session.getValueFactory().createValue("wow")); QueryResult result = query.execute(); NodeIterator nit = result.getNodes(); assertTrue(nit.hasNext()); Node n11 = nit.nextNode(); assertEquals("n1", n11.getName()); assertTrue(!nit.hasNext()); }

Target:
public void fullTextShouldWorkWithBindVar() throws Exception { Node n1 = session.getRootNode().addNode("n1"); n1.setProperty("n1-prop-1", "wow"); n1.setProperty("n1-prop-2", "any"); Node n2 = session.getRootNode().addNode("n2"); n2.setProperty("n2-prop-1", "test"); try { session.save(); String queryString = "select * from [nt:unstructured] as a where contains(a.*, 'wow')"; assertNodesAreFound(queryString, Query.JCR_SQL2, "/n1"); String queryStringWithBind = "select * from [nt:unstructured] as a where contains(a.*, $text)"; QueryManager queryManager = session.getWorkspace().getQueryManager(); Query query = queryManager.createQuery(queryStringWithBind, Query.JCR_SQL2); query.bindValue("text", session.getValueFactory().createValue("wow")); QueryResult result = query.execute(); NodeIterator nit = result.getNodes(); assertTrue(nit.hasNext()); Node n11 = nit.nextNode(); assertEquals("n1", n11.getName()); assertTrue(!nit.hasNext()); } finally { n1.remove(); n2.remove(); session.save(); } }
Source:
public void setDigestAlgorithm(String digestAlgorithm) throws NoSuchAlgorithmException { if (callbackWrapper != null) { throw new IllegalStateException("Cannot create a digest because some content has already been discarded"); } digest = MessageDigest.getInstance(digestAlgorithm); }

Target:
public void setDigestAlgorithm(String digestAlgorithm) throws NoSuchAlgorithmException { if (callbackWrapper != null) { throw new IllegalStateException("Cannot create a digest because some content may have been consumed"); } digest = MessageDigest.getInstance(digestAlgorithm); }
Source:
public String deploy(Artifact artifact) throws CarbonDeploymentException { logger.info("Deploying : " + artifact.getName()); if (artifact.getName().contains("sample1.txt")) { sample1Deployed = false; } else if (artifact.getName().contains("sample2.txt")) { sample2Deployed = false; } return null; }

Target:
public String deploy(Artifact artifact) throws CarbonDeploymentException { logger.info("Deploying : " + artifact.getName()); if (artifact.getName() != null && artifact.getName().contains("sample1.txt")) { sample1Deployed = false; } else if (artifact.getName() != null && artifact.getName().contains("sample2.txt")) { sample2Deployed = false; } return null; }
Source:
public void Cluster_SelectedItemChanged() { UpdateDefaultHost(); updateCustomPropertySheet(); UpdateMinAllocatedMemory(); UpdateNumOfSockets(); if ((VmTemplate) getModel().getTemplate().getSelectedItem() != null) { VmTemplate template = (VmTemplate) getModel().getTemplate().getSelectedItem(); updateQuotaByCluster(template.getQuotaId(), template.getQuotaName()); } updateCpuPinningVisibility(); }

Target:
public void Cluster_SelectedItemChanged() { UpdateDefaultHost(); updateCustomPropertySheet(); UpdateMinAllocatedMemory(); UpdateNumOfSockets(); if (getModel().getTemplate().getSelectedItem() != null) { VmTemplate template = (VmTemplate) getModel().getTemplate().getSelectedItem(); updateQuotaByCluster(template.getQuotaId(), template.getQuotaName()); } updateCpuPinningVisibility(); }
Source:
private void removeSelfFromListeners() { ISelectionService selectionService = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService(); if (selectionService != null && ReflectionHelper.getFieldValueWithoutException(selectionService, "listeners").isPresent()) { Optional<Object> listenersList = ReflectionHelper.getFieldValueWithoutException(selectionService, "listeners").filter(ListenerList.class::isInstance); if (listenersList.isPresent()) { selectionService.removeSelectionListener(this); } } }

Target:
private void removeSelfFromListeners() { ISelectionService selectionService = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService(); Optional<Object> fieldValueWithoutException = ReflectionHelper.getFieldValueWithoutException(selectionService, "listeners"); if (selectionService != null && fieldValueWithoutException.isPresent() && fieldValueWithoutException.filter(ListenerList.class::isInstance).isPresent()) { selectionService.removeSelectionListener(this); } }
Source:
public void initialise() { requiresCondition(() -> worldRenderer.getCurrentRenderStage() == MONO || worldRenderer.getCurrentRenderStage() == LEFT_EYE); addDesiredStateChange(new BindFBO(DEFAULT_FRAME_BUFFER_URN, displayResolutionDependentFBOs)); update(); addDesiredStateChange(new EnableMaterial("engine:prog.defaultTextured")); displayResolutionDependentFBOs.subscribe(this); }

Target:
public void initialise() { requiresCondition(() -> worldRenderer.getCurrentRenderStage() == MONO || worldRenderer.getCurrentRenderStage() == LEFT_EYE); addDesiredStateChange(new BindFBO(DEFAULT_FRAME_BUFFER_URN, displayResolutionDependentFBOs)); update(); displayResolutionDependentFBOs.subscribe(this); addDesiredStateChange(new EnableMaterial("engine:prog.defaultTextured")); }
Source:
public AggregatedResult<T, S> deserialize( JsonElement jsonElement, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (jsonElement == null) return null; JsonObject json = jsonElement.getAsJsonObject(); if (!json.has("range") || !json.has("value")) { throw new JsonParseException("no neceessary fields."); } Gson gson = new GsonBuilder() .registerTypeAdapter(TimeRange.class, new TimeRangeAdapter()) .registerTypeAdapter(HistoryState.class, new HistoryStateAdapter(this.stateClass)) .create(); TimeRange range = gson.fromJson(json.getAsJsonObject("range"), TimeRange.class); T value = (T)json.getAsJsonPrimitive("value").getAsNumber(); List<HistoryState<S>> aggregateObjects = null; if (json.has("objects")) { aggregateObjects = new ArrayList<>(); JsonArray objects = json.getAsJsonArray("objects"); for (int i = 0; i < objects.size(); ++i) { aggregateObjects.add(gson.fromJson(objects.get(i), HistoryState.class)); } } return new AggregatedResult(range, value, aggregateObjects); }

Target:
public AggregatedResult<T, S> deserialize( JsonElement jsonElement, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (jsonElement == null) return null; JsonObject json = jsonElement.getAsJsonObject(); if (!json.has("range") || !json.has("aggregations")) { throw new JsonParseException( "json doesn't contain both of 2 necessary fields: range and aggregations."); } Gson gson = new GsonBuilder() .registerTypeAdapter(TimeRange.class, new TimeRangeAdapter()) .registerTypeAdapter(HistoryState.class, new HistoryStateAdapter(this.stateClass)) .create(); TimeRange range = gson.fromJson(json.getAsJsonObject("range"), TimeRange.class); JsonArray aggregations = json.getAsJsonArray("aggregations"); if (aggregations.size() != 1) { throw new JsonParseException( "aggregations doesn't contain one object."); } JsonObject aggregation = aggregations.get(0).getAsJsonObject(); T value = null; List<HistoryState<S>> aggregateObjects = null; if (aggregation.has("value")) { value = gson.fromJson(aggregation.getAsJsonPrimitive("value"), this.fieldClass); } if (aggregation.has("objects")) { aggregateObjects = new ArrayList<>(); JsonArray objects = aggregation.getAsJsonArray("objects"); Type historyStateType = new TypeToken<HistoryState<S>>(){}.getType(); for (int i = 0; i < objects.size(); ++i) { HistoryState<S> historyState = gson.fromJson(objects.get(i), historyStateType); aggregateObjects.add(historyState); } } return new AggregatedResult<T, S>(range, value, aggregateObjects); }
Source:
default boolean accept(F file) { @SuppressWarnings("unchecked") F[] fileArray = (F[]) Array.newInstance(file.getClass(), 1); fileArray[0] = file; return filterFiles(fileArray).size() > 0; }

Target:
default boolean accept(F file) { throw new UnsupportedOperationException( "Filters that return true in supportsSingleFileFiltering() must implement this method"); }
Source:
protected void destroyVm() { boolean vmMigrating = getVm().getStatus() == VMStatus.MigratingFrom && getVm().getMigratingToVds() != null; setActionReturnValue(vmMigrating ? destroyMigratingVm() : destroyNonMigratingVm()); managedBlockStorageCommandUtil.disconnectManagedBlockStorageDisks(getVm(), vmHandler, getVdsId()); }

Target:
protected void destroyVm() { boolean vmMigrating = getVm().getStatus() == VMStatus.MigratingFrom && getVm().getMigratingToVds() != null; setActionReturnValue(vmMigrating ? destroyMigratingVm() : destroyNonMigratingVm()); }
Source:
public void destroySessionBack(final C context, final String ticket) { final Object trackableSession = store.get(ticket); logger.debug("ticket: -> trackableSession: {}", ticket, trackableSession); if (trackableSession == null) { logger.error("No trackable session found for back channel logout. Either the session store does not support to track session " + "or it has expired from the store and the store settings must be updated (expired data)"); } else { store.remove(ticket); final SessionStore sessionStore = context.getSessionStore(); if (sessionStore == null) { logger.error("No session store available for this web context"); } else { final SessionStore<C> newSessionStore = (SessionStore<C>) sessionStore.buildFromTrackableSession(context, trackableSession) .orElse(null); if (newSessionStore != null) { logger.debug("newSesionStore: {}", newSessionStore); final String sessionId = newSessionStore.getOrCreateSessionId(context); logger.debug("remove sessionId: {}", sessionId); store.remove(sessionId); destroy(context, newSessionStore, "back"); } else { logger.error("The session store should be able to build a new session store from the tracked session"); } } } }

Target:
public void destroySessionBack(final C context, final String ticket) { final Object trackableSession = store.get(ticket); logger.debug("ticket: -> trackableSession: {}", ticket, trackableSession); if (trackableSession == null) { logger.error("No trackable session found for back channel logout. Either the session store does not support to track session " + "or it has expired from the store and the store settings must be updated (expired data)"); } else { store.remove(ticket); final SessionStore sessionStore = context.getSessionStore(); if (sessionStore == null) { logger.error("No session store available for this web context"); } else { final Optional<SessionStore<C>> newSessionStoreOpt = sessionStore.buildFromTrackableSession(context, trackableSession); if (newSessionStoreOpt.isPresent()) { SessionStore<C> newSessionStore = newSessionStoreOpt.get(); logger.debug("newSesionStore: {}", newSessionStore); final String sessionId = newSessionStore.getOrCreateSessionId(context); logger.debug("remove sessionId: {}", sessionId); store.remove(sessionId); destroy(context, newSessionStore, "back"); } else { logger.error("The session store should be able to build a new session store from the tracked session"); } } } }
Source:
private static String evaluateStaticConstant(String fqn) { int lastPeriod = fqn.lastIndexOf("."); String clazzName = fqn.substring(0, lastPeriod); String constantName = fqn.substring(lastPeriod + 1); try { Class<?> clazz = Context.loadClass(clazzName); java.lang.reflect.Field constantField = clazz.getField(constantName); Object val = constantField.get(null); return val != null ? String.valueOf(val) : null; } catch (Exception ex) { throw new IllegalArgumentException("Unable to evaluate " + fqn, ex); } }

Target:
private static String evaluateStaticConstant(String fqn) { int lastPeriod = fqn.lastIndexOf("."); String clazzName = fqn.substring(0, lastPeriod); String constantName = fqn.substring(lastPeriod + 1); try { Class<?> clazz = Context.loadClass(clazzName); Field constantField = clazz.getField(constantName); Object val = constantField.get(null); return val != null ? String.valueOf(val) : null; } catch (Exception ex) { throw new IllegalArgumentException("Unable to evaluate " + fqn, ex); } }
Source:
public RepositoryFileTreeDto doGetTree( String pathId, Integer depth, String filter, Boolean showHidden, Boolean includeAcls, Boolean includeSystemFolders ) { String path = null; if ( pathId == null || pathId.equals( FileUtils.PATH_SEPARATOR ) ) { path = FileUtils.PATH_SEPARATOR; } else if ( !pathId.startsWith( FileUtils.PATH_SEPARATOR ) ) { path = idToPath( pathId ); } RepositoryRequest repositoryRequest = getRepositoryRequest( path, showHidden, depth, filter ); repositoryRequest.setIncludeAcls( includeAcls ); repositoryRequest.setIncludeSystemFolders( includeSystemFolders ); RepositoryFileTreeDto tree = null; try { tree = getRepoWs().getTreeFromRequest( repositoryRequest ); } catch ( Exception e ) { logger.error( "Problem getting path: " + path ); } if ( tree != null && isShowingTitle( repositoryRequest ) ) { Collator collator = getCollatorInstance(); collator.setStrength( Collator.PRIMARY ); sortByLocaleTitle( collator, tree ); } return tree; }

Target:
public RepositoryFileTreeDto doGetTree( String pathId, Integer depth, String filter, Boolean showHidden, Boolean includeAcls, Boolean includeSystemFolders ) { String path = null; if ( pathId == null || pathId.equals( FileUtils.PATH_SEPARATOR ) ) { path = FileUtils.PATH_SEPARATOR; } else if ( !pathId.startsWith( FileUtils.PATH_SEPARATOR ) ) { path = idToPath( pathId ); } RepositoryRequest repositoryRequest = getRepositoryRequest( path, showHidden, depth, filter ); repositoryRequest.setIncludeAcls( includeAcls ); repositoryRequest.setIncludeSystemFolders( includeSystemFolders ); RepositoryFileTreeDto tree = null; try { tree = getRepoWs().getTreeFromRequest( repositoryRequest ); } catch ( UnifiedRepositoryException e ) { logger.error( e.getCause() ); } if ( tree != null && isShowingTitle( repositoryRequest ) ) { Collator collator = getCollatorInstance(); collator.setStrength( Collator.PRIMARY ); sortByLocaleTitle( collator, tree ); } return tree; }
Source:
public static RestServiceErrorCode getRestServiceErrorCode(RouterErrorCode routerErrorCode) { switch (routerErrorCode) { case BlobTooLarge: case InvalidBlobId: case InvalidPutArgument: case BadInputChannel: return BadRequest; case BlobDeleted: case BlobExpired: return Deleted; case BlobDoesNotExist: return NotFound; case RangeNotSatisfiable: return RangeNotSatisfiable; case AmbryUnavailable: case InsufficientCapacity: case OperationTimedOut: case RouterClosed: case UnexpectedInternalError: default: return InternalServerError; } }

Target:
public static RestServiceErrorCode getRestServiceErrorCode(RouterErrorCode routerErrorCode) { switch (routerErrorCode) { case BlobTooLarge: case InvalidBlobId: case InvalidPutArgument: case BadInputChannel: return BadRequest; case BlobDeleted: case BlobExpired: return Deleted; case BlobDoesNotExist: return NotFound; case RangeNotSatisfiable: return RangeNotSatisfiable; case AmbryUnavailable: case InsufficientCapacity: case OperationTimedOut: case RouterClosed: case UnexpectedInternalError: case ChannelClosed: default: return InternalServerError; } }
Source:
public Alias alias() throws IOException { final Aliases aliases = this.user().aliases(); if (!aliases.iterate().iterator().hasNext()) { throw new RsForward( HttpURLConnection.HTTP_MOVED_TEMP, "/login/start" ); } final Alias alias = aliases.iterate().iterator().next(); if (alias.photo().equals(Alias.BLANK)) { final Identity identity = new RqAuth(this).identity(); if (identity.urn().startsWith("urn:github:")) { alias.photo(URI.create(identity.properties().get("avatar"))); } else if (identity.urn().startsWith("urn:facebook:") || identity.urn().startsWith("urn:google:")) { alias.photo(URI.create(identity.properties().get("picture"))); } } return alias; }

Target:
public Alias alias() throws IOException { final Aliases aliases = this.user().aliases(); if (!aliases.iterate().iterator().hasNext()) { throw new RsForward( HttpURLConnection.HTTP_MOVED_TEMP, "/login/start" ); } final Alias alias = aliases.iterate().iterator().next(); final URI photo; final Identity identity = new RqAuth(this).identity(); if (identity.urn().startsWith("urn:github:")) { photo = URI.create(identity.properties().get("avatar")); } else if (identity.urn().startsWith("urn:facebook:") || identity.urn().startsWith("urn:google:")) { photo = URI.create(identity.properties().get("picture")); } else { photo = Alias.BLANK; } if (!alias.photo().equals(photo)) { alias.photo(photo); } return alias; }
Source:
private RedisResponse doSet(Command command, ExecutionHandlerContext context, ByteArrayWrapper key, ByteArrayWrapper value, RedisStringCommands redisStringCommands, SetOptions setOptions) { boolean result = redisStringCommands.set(key, value, setOptions); if (result) { command.setResponse(Coder.getSimpleStringResponse(context.getByteBufAllocator(), SUCCESS)); return RedisResponse.string(SUCCESS); } return RedisResponse.nil(); }

Target:
private RedisResponse doSet(Command command, ExecutionHandlerContext context, ByteArrayWrapper key, ByteArrayWrapper value, RedisStringCommands redisStringCommands, SetOptions setOptions) { boolean result = redisStringCommands.set(key, value, setOptions); if (result) { return RedisResponse.string(SUCCESS); } return RedisResponse.nil(); }
Source:
public void testGetEntry() { Optional o = metacardMapper.getEntry(e -> e.getFeatureProperty().equals(FEATURE_NAME)); assertThat(o.isPresent(), is(true)); o = metacardMapper.getEntry(e -> e.getFeatureProperty().equals(NON_EXISTENT_FEATURE)); assertThat(o.isPresent(), is(false)); o = metacardMapper.getEntry(null); assertThat(o, is(Optional.empty())); }

Target:
public void testGetEntry() { Optional optionalEntry = metacardMapper.getEntry(e -> e.getFeatureProperty().equals(FEATURE_NAME)); assertThat(optionalEntry.isPresent(), is(true)); optionalEntry = metacardMapper.getEntry(e -> e.getFeatureProperty().equals(NON_EXISTENT_FEATURE)); assertThat(optionalEntry.isPresent(), is(false)); optionalEntry = metacardMapper.getEntry(null); assertThat(optionalEntry, is(Optional.empty())); }
Source:
public Pair<String, List<Object>> getTableInsertData(Persistable p){ String built = "INSERT INTO " + scrubName(name) + " ("; HashMap<String, Object> contentValues = DatabaseHelper.getMetaFieldsAndValues(p); ArrayList<Object> params = new ArrayList<Object>(); for(int i = 0 ; i < rawCols.size() ; ++i) { built += rawCols.elementAt(i); if(i < rawCols.size() - 1) { built += ", "; } } built += ") VALUES ("; for(int i = 0 ; i < rawCols.size() ; ++i) { Object currentValue = contentValues.get(rawCols.elementAt(i)); built += "?"; params.add(currentValue); if(i < rawCols.size() - 1) { built += ", "; } } built += ");"; return new Pair(built, params); }

Target:
public Pair<String, List<Object>> getTableInsertData(Persistable p){ StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("INSERT INTO " + scrubName(name) + " ("); HashMap<String, Object> contentValues = DatabaseHelper.getMetaFieldsAndValues(p); ArrayList<Object> params = new ArrayList<Object>(); for(int i = 0 ; i < rawCols.size() ; ++i) { stringBuilder.append(rawCols.elementAt(i)); if(i < rawCols.size() - 1) { stringBuilder.append(", "); } } stringBuilder.append(") VALUES ("); for(int i = 0 ; i < rawCols.size() ; ++i) { Object currentValue = contentValues.get(rawCols.elementAt(i)); stringBuilder.append("?"); params.add(currentValue); if(i < rawCols.size() - 1) { stringBuilder.append(", "); } } stringBuilder.append(");"); return new Pair<String, List<Object>>(stringBuilder.toString(), params); }
Source:
private static Class<?> compileWrapperClass(SubjectFactory<?, ?> subjectFactory) { Class<?> subjectClass = subjectFactory.getSubjectClass(); String wrapperClassName = subjectClass.getSimpleName() + ITERATING_WRAPPER; List<Method> methods = Arrays.asList(subjectClass.getMethods()); String subjectName = subjectClass.getSimpleName(); Class<?> targetType = ReflectionUtil.capture(subjectClass, 1); StringBuffer code = new StringBuffer(); code.append("package ").append(subjectClass.getPackage().getName()).append(";\n\n"); code.append("public class ").append(wrapperClassName).append(" ") .append("extends ").append(subjectName).append(" {\n"); appendConstructor(wrapperClassName, targetType, code); for (Method m : methods) { appendMethodWrapper(code, subjectClass, targetType, m); } code.append("}\n"); String out = code.toString(); ClassLoader classLoader; try { classLoader = new CompilingClassLoader( subjectClass.getClassLoader(), subjectClass.getName() + ITERATING_WRAPPER, out, null); } catch (CompilerException e) { throw new Error("Could not compile class " + wrapperClassName + " with source:\n" + out , e); } try { Class<?> wrapper = classLoader.loadClass(subjectClass.getName() + ITERATING_WRAPPER); return wrapper; } catch (ClassNotFoundException e) { throw new Error("Could not load class " + subjectName, e); } }

Target:
private static Class<?> compileWrapperClass(SubjectFactory<?, ?> subjectFactory) { IteratingWrapperClassBuilder builder = new IteratingWrapperClassBuilder(subjectFactory); String out = builder.build().toString(); ClassLoader classLoader; try { classLoader = new CompilingClassLoader( subjectFactory.getSubjectClass().getClassLoader(), builder.className, out, null); } catch (CompilerException e) { throw new Error("Could not compile class " + builder.className + " with source:\n" + out , e); } try { Class<?> wrapper = classLoader.loadClass(builder.className); return wrapper; } catch (ClassNotFoundException e) { throw new Error("Could not load class " + subjectFactory.getSubjectClass().getSimpleName(), e); } }